text
stringlengths
2
1.05M
/* * Copyright 2019 Lightbend Inc. * * 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. */ const should = require("chai").should(); const Long = require("long"); const PNCounter = require("../../src/crdts/pncounter"); const protobufHelper = require("../../src/protobuf-helper"); const CrdtDelta = protobufHelper.moduleRoot.cloudstate.crdt.CrdtDelta; function roundTripDelta(delta) { return CrdtDelta.decode(CrdtDelta.encode(delta).finish()); } describe("PNCounter", () => { it("should have a value of zero when instantiated", () => { const counter = new PNCounter(); counter.value.should.equal(0); should.equal(counter.getAndResetDelta(), null); }); it("should reflect a delta update", () => { const counter = new PNCounter(); counter.applyDelta(roundTripDelta({ pncounter: { change: 10 } })); counter.value.should.equal(10); // Try incrementing it again counter.applyDelta(roundTripDelta({ pncounter: { change: -3 } })); counter.value.should.equal(7); }); it("should generate deltas", () => { const counter = new PNCounter(); counter.increment(10); counter.value.should.equal(10); roundTripDelta(counter.getAndResetDelta()).pncounter.change.toNumber().should.equal(10); should.equal(counter.getAndResetDelta(), null); counter.decrement(3); counter.value.should.equal(7); counter.decrement(4); counter.value.should.equal(3); roundTripDelta(counter.getAndResetDelta()).pncounter.change.toNumber().should.equal(-7); should.equal(counter.getAndResetDelta(), null); }); it("should support long values", () => { const impossibleDouble = Long.ZERO.add(Number.MAX_SAFE_INTEGER).add(1); const counter = new PNCounter(); counter.increment(Number.MAX_SAFE_INTEGER); counter.increment(1); counter.longValue.should.eql(impossibleDouble); roundTripDelta(counter.getAndResetDelta()).pncounter.change.should.eql(impossibleDouble); }); it("should support incrementing by long values", () => { const impossibleDouble = Long.ZERO.add(Number.MAX_SAFE_INTEGER).add(1); const counter = new PNCounter(); counter.increment(impossibleDouble); counter.longValue.should.eql(impossibleDouble); roundTripDelta(counter.getAndResetDelta()).pncounter.change.should.eql(impossibleDouble); }); it("should support empty initial deltas (for ORMap added)", () => { const counter = new PNCounter(); counter.value.should.equal(0); should.equal(counter.getAndResetDelta(), null); roundTripDelta(counter.getAndResetDelta(/* initial = */ true)).pncounter.change.toNumber().should.equal(0); }); });
import express from 'express' // const PatientController = require('../controllers/patient-controller'); // import {PatientController} from '../controllers/patient-controller'; import {getItems, getItemById, createItem, updateItem, deleteItem} from '../controllers/patient-controller.js'; export const router = express.Router(); router.get('/items', getItems); router.get('/item/:id', getItemById); router.post('/item', createItem); router.put('/item/:id', updateItem); router.delete('/item/:id', deleteItem); // module.exports = router;
var webPasses = require('../lib/http-proxy/passes/web-incoming'), httpProxy = require('../lib/http-proxy'), expect = require('expect.js'), http = require('http'); describe('lib/http-proxy/passes/web.js', function() { describe('#deleteLength', function() { it('should change `content-length`', function() { var stubRequest = { method: 'DELETE', headers: {} }; webPasses.deleteLength(stubRequest, {}, {}); expect(stubRequest.headers['content-length']).to.eql('0'); }) }); describe('#timeout', function() { it('should set timeout on the socket', function() { var done = false, stubRequest = { socket: { setTimeout: function(value) { done = value; } } } webPasses.timeout(stubRequest, {}, { timeout: 5000}); expect(done).to.eql(5000); }); }); describe('#XHeaders', function () { var stubRequest = { connection: { remoteAddress: '192.168.1.2', remotePort: '8080' }, headers: { host: '192.168.1.2:8080' } } it('set the correct x-forwarded-* headers', function () { webPasses.XHeaders(stubRequest, {}, { xfwd: true }); expect(stubRequest.headers['x-forwarded-for']).to.be('192.168.1.2'); expect(stubRequest.headers['x-forwarded-port']).to.be('8080'); expect(stubRequest.headers['x-forwarded-proto']).to.be('http'); }); }); }); describe('#createProxyServer.web() using own http server', function () { it('should proxy the request using the web proxy handler', function (done) { var proxy = httpProxy.createProxyServer({ target: 'http://127.0.0.1:8080' }); function requestHandler(req, res) { proxy.web(req, res); } var proxyServer = http.createServer(requestHandler); var source = http.createServer(function(req, res) { source.close(); proxyServer.close(); expect(req.method).to.eql('GET'); expect(req.headers.host.split(':')[1]).to.eql('8081'); done(); }); proxyServer.listen('8081'); source.listen('8080'); http.request('http://127.0.0.1:8081', function() {}).end(); }); it('should detect a proxyReq event and modify headers', function (done) { var proxy = httpProxy.createProxyServer({ target: 'http://127.0.0.1:8080', }); proxy.on('proxyReq', function(proxyReq, req, res, options) { proxyReq.setHeader('X-Special-Proxy-Header', 'foobar'); }); function requestHandler(req, res) { proxy.web(req, res); } var proxyServer = http.createServer(requestHandler); var source = http.createServer(function(req, res) { source.close(); proxyServer.close(); expect(req.headers['x-special-proxy-header']).to.eql('foobar'); done(); }); proxyServer.listen('8081'); source.listen('8080'); http.request('http://127.0.0.1:8081', function() {}).end(); }); it('should proxy the request and handle error via callback', function(done) { var proxy = httpProxy.createProxyServer({ target: 'http://127.0.0.1:8080' }); var proxyServer = http.createServer(requestHandler); function requestHandler(req, res) { proxy.web(req, res, function (err) { proxyServer.close(); expect(err).to.be.an(Error); expect(err.code).to.be('ECONNREFUSED'); done(); }); } proxyServer.listen('8082'); http.request({ hostname: '127.0.0.1', port: '8082', method: 'GET', }, function() {}).end(); }); it('should proxy the request and handle error via event listener', function(done) { var proxy = httpProxy.createProxyServer({ target: 'http://127.0.0.1:8080' }); var proxyServer = http.createServer(requestHandler); function requestHandler(req, res) { proxy.once('error', function (err, errReq, errRes) { proxyServer.close(); expect(err).to.be.an(Error); expect(errReq).to.be.equal(req); expect(errRes).to.be.equal(res); expect(err.code).to.be('ECONNREFUSED'); done(); }); proxy.web(req, res); } proxyServer.listen('8083'); http.request({ hostname: '127.0.0.1', port: '8083', method: 'GET', }, function() {}).end(); }); it('should proxy the request and handle timeout error (proxyTimeout)', function(done) { var proxy = httpProxy.createProxyServer({ target: 'http://127.0.0.1:45000', proxyTimeout: 100 }); require('net').createServer().listen(45000); var proxyServer = http.createServer(requestHandler); var started = new Date().getTime(); function requestHandler(req, res) { proxy.once('error', function (err, errReq, errRes) { proxyServer.close(); expect(err).to.be.an(Error); expect(errReq).to.be.equal(req); expect(errRes).to.be.equal(res); expect(new Date().getTime() - started).to.be.greaterThan(99); expect(err.code).to.be('ECONNRESET'); done(); }); proxy.web(req, res); } proxyServer.listen('8084'); http.request({ hostname: '127.0.0.1', port: '8084', method: 'GET', }, function() {}).end(); }); it('should proxy the request and handle timeout error', function(done) { var proxy = httpProxy.createProxyServer({ target: 'http://127.0.0.1:45001', timeout: 100 }); require('net').createServer().listen(45001); var proxyServer = http.createServer(requestHandler); var cnt = 0; var doneOne = function() { cnt += 1; if(cnt === 2) done(); } var started = new Date().getTime(); function requestHandler(req, res) { proxy.once('error', function (err, errReq, errRes) { proxyServer.close(); expect(err).to.be.an(Error); expect(errReq).to.be.equal(req); expect(errRes).to.be.equal(res); expect(err.code).to.be('ECONNRESET'); doneOne(); }); proxy.web(req, res); } proxyServer.listen('8085'); var req = http.request({ hostname: '127.0.0.1', port: '8085', method: 'GET', }, function() {}); req.on('error', function(err) { expect(err).to.be.an(Error); expect(err.code).to.be('ECONNRESET'); expect(new Date().getTime() - started).to.be.greaterThan(99); doneOne(); }); req.end(); }); it('should proxy the request and provide a proxyRes event with the request and response parameters', function(done) { var proxy = httpProxy.createProxyServer({ target: 'http://127.0.0.1:8080' }); function requestHandler(req, res) { proxy.once('proxyRes', function (proxyRes, pReq, pRes) { source.close(); proxyServer.close(); expect(pReq).to.be.equal(req); expect(pRes).to.be.equal(res); done(); }); proxy.web(req, res); } var proxyServer = http.createServer(requestHandler); var source = http.createServer(function(req, res) { res.end('Response'); }); proxyServer.listen('8086'); source.listen('8080'); http.request('http://127.0.0.1:8086', function() {}).end(); }); it('should proxy the request and handle changeOrigin option', function (done) { var proxy = httpProxy.createProxyServer({ target: 'http://127.0.0.1:8080', changeOrigin: true }); function requestHandler(req, res) { proxy.web(req, res); } var proxyServer = http.createServer(requestHandler); var source = http.createServer(function(req, res) { source.close(); proxyServer.close(); expect(req.method).to.eql('GET'); expect(req.headers.host.split(':')[1]).to.eql('8080'); done(); }); proxyServer.listen('8081'); source.listen('8080'); http.request('http://127.0.0.1:8081', function() {}).end(); }); });
'use strict'; module.exports = function(grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), app: 'app', dist: 'dist', test: 'test', sass: { dist: { options: { style: 'expanded', // expanded or nested or compact or compressed loadPath: '<%= app %>/bower_components/foundation/scss', compass: true, quiet: true }, files: { '<%= app %>/css/app.css': '<%= app %>/scss/app.scss' } } }, postcss: { options: { processors: [ require('autoprefixer')({browsers: 'last 2 versions'}) ] }, dist: { src: '<%= app %>/css/app.css' } }, jshint: { options: { jshintrc: '.jshintrc' }, all: [ 'Gruntfile.js', '<%= app %>/js/**/*.js' ] }, karma: { unit: { configFile: '<%= test %>/karma.conf.js' } }, clean: { dist: { src: ['<%= dist %>/*'] }, }, copy: { dist: { files: [{ expand: true, cwd:'<%= app %>/', src: ['fonts/**', '**/*.html', '!**/*.scss', '!bower_components/**'], dest: '<%= dist %>/' }] }, }, imagemin: { target: { files: [{ expand: true, cwd: '<%= app %>/images/', src: ['**/*.{jpg,gif,svg,jpeg,png}'], dest: '<%= dist %>/images/' }] } }, uglify: { options: { preserveComments: 'some', mangle: false } }, useminPrepare: { html: ['<%= app %>/index.html'], options: { dest: '<%= dist %>' } }, usemin: { html: ['<%= dist %>/**/*.html', '!<%= app %>/bower_components/**'], css: ['<%= dist %>/css/**/*.css'], options: { dirs: ['<%= dist %>'] } }, watch: { grunt: { files: ['Gruntfile.js'], tasks: ['sass', 'postcss'] }, sass: { files: '<%= app %>/scss/**/*.scss', tasks: ['sass', 'postcss'] }, livereload: { files: ['<%= app %>/**/*.html', '!<%= app %>/bower_components/**', '<%= app %>/js/**/*.js', '<%= app %>/css/**/*.css', '<%= app %>/images/**/*.{jpg,gif,svg,jpeg,png}'], options: { livereload: true } } }, connect: { app: { options: { port: 9000, base: '<%= app %>/', open: true, livereload: true, hostname: '127.0.0.1' } }, dist: { options: { port: 9001, base: '<%= dist %>/', open: true, keepalive: true, livereload: false, hostname: '127.0.0.1' } } }, wiredep: { target: { src: [ '<%= app %>/**/*.html' ], exclude: [ 'modernizr', 'jquery-placeholder', 'foundation' ] } } }); grunt.registerTask('compile-sass', ['sass', 'postcss']); grunt.registerTask('bower-install', ['wiredep']); grunt.registerTask('default', ['compile-sass', 'bower-install', 'connect:app', 'watch']); grunt.registerTask('validate-js', ['jshint']); grunt.registerTask('server-dist', ['connect:dist']); grunt.registerTask('publish', ['compile-sass', 'clean:dist', 'validate-js', 'useminPrepare', 'copy:dist', 'newer:imagemin', 'concat', 'cssmin', 'uglify', 'usemin']); grunt.loadNpmTasks('grunt-karma'); };
/* See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Esri Inc. licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(["dojo/_base/declare", "dojo/_base/lang", "dojo/_base/array", "dojo/topic", "app/context/app-topics", "app/common/Templated", "dojo/text!./templates/App.html", "dojo/i18n!../nls/resources", "app/etc/util", "app/main/SearchPanel", "app/main/MapPanel", "app/main/AboutPanel", "app/content/MetadataEditor", "app/content/UploadMetadata"], function(declare, lang, array, topic, appTopics, Templated, template, i18n, util, SearchPanel, MapPanel, AboutPanel, MetadataEditor, UploadMetadata) { var oThisClass = declare([Templated], { i18n: i18n, templateString: template, postCreate: function() { this.inherited(arguments); var self = this; this.updateUI(); var ignoreMapPanelActivated = false; $("a[href='#searchPanel']").on("shown.bs.tab",lang.hitch(this, function(e) { this.setHash('searchPanel') })); $("a[href='#mapPanel']").on("shown.bs.tab",lang.hitch(this, function(e) { this.setHash('mapPanel') if (!ignoreMapPanelActivated && !self.mapPanel.mapWasInitialized) { self.mapPanel.ensureMap(); } })); $("a[href='#aboutPanel']").on("shown.bs.tab",lang.hitch(this, function(e) { this.setHash('aboutPanel') })); topic.subscribe(appTopics.AddToMapClicked,lang.hitch(this, function(params){ if (self.mapPanel.mapWasInitialized) { $("a[href='#mapPanel']").tab("show"); self.mapPanel.addToMap(params); } else { var urlParams = {resource: params.type+":"+this.normalizeUrl(params.url)}; ignoreMapPanelActivated = true; $("a[href='#mapPanel']").tab("show"); self.mapPanel.ensureMap(urlParams); ignoreMapPanelActivated = false; } })); topic.subscribe(appTopics.SignedIn,function(params){ self.updateUI(); }); $("#idAppDropdown").on("show.bs.dropdown",function() { self.updateUI(); }); if (location.hash==null || location.hash.length==0) { this.setHash('searchPanel') } else if ( $("a[href='"+location.hash+"']").length > 0) { $("a[href='"+location.hash+"']").tab("show"); } }, /* =================================================================================== */ setHash: function(hash) { var el = document.getElementById(hash); var id = el.id; el.removeAttribute('id'); location.hash = hash; el.setAttribute('id',id); }, createMetadataClicked: function() { var editor = new MetadataEditor(); editor.show(); }, signInClicked: function() { AppContext.appUser.showSignIn(); }, signOutClicked: function() { AppContext.appUser.signOut(); }, uploadClicked: function() { if (AppContext.appUser.isPublisher()) (new UploadMetadata()).show(); }, editFacetClicked: function() { console.warn("TODO provide edit facet functionality in App.js") }, /* =================================================================================== */ getCreateAccountUrl: function() { if (AppContext.geoportal && AppContext.geoportal.createAccountUrl) { return util.checkMixedContent(AppContext.geoportal.createAccountUrl); } return null; }, updateUI: function() { var updateHref = function(node,link,href) { if (typeof href === "string" && href.length > 0) { link.href = href; node.style.display = ""; } else { link.href = "#"; node.style.display = "none"; } }; var v; if (AppContext.appUser.isSignedIn()) { v = i18n.nav.welcomePattern.replace("{name}",AppContext.appUser.getUsername()); util.setNodeText(this.usernameNode,v); this.userOptionsNode.style.display = ""; this.signInNode.style.display = "none"; this.signOutNode.style.display = ""; this.adminOptionsBtnNode.style.display = ""; updateHref(this.createAccountNode,this.createAccountLink,null); updateHref(this.myProfileNode,this.myProfileLink,AppContext.appUser.getMyProfileUrl()); } else { this.usernameNode.innerHTML = ""; this.userOptionsNode.style.display = "none"; this.createAccountNode.style.display = "none"; this.signInNode.style.display = ""; this.signOutNode.style.display = "none"; this.adminOptionsBtnNode.style.display = "none"; updateHref(this.createAccountNode,this.createAccountLink,this.getCreateAccountUrl()); updateHref(this.myProfileNode,this.myProfileLink,null); } var isAdmin = AppContext.appUser.isAdmin(); var isPublisher = AppContext.appUser.isPublisher(); $("li[data-role='admin']").each(function(i,nd) { if (isAdmin) nd.style.display = ""; else nd.style.display = "none"; }); $("li[data-role='publisher']").each(function(i,nd) { if (isPublisher) nd.style.display = ""; else nd.style.display = "none"; }); if (!FileReader) this.uploadNode.style.display = "none"; }, normalizeUrl: function(url) { var services = ["mapserver", "imageserver", "featureserver", "streamserver", "vectortileserver"]; var selSrv = array.filter(services, function(srv) { return url.toLowerCase().indexOf(srv)>=0; }); if (selSrv && selSrv.length>0) { var srv = selSrv[0]; url = url.substr(0, url.toLowerCase().indexOf(srv) + srv.length); } return url; }, _onHome: function() { this.searchPanelLink.click() location.hash = "searchPanel" } }); return oThisClass; });
const AWS = require('aws-sdk'); require('amazon-cognito-js'); const { onConflict, onDatasetDeleted, onDatasetsMerged } = require('./sync-handlers'); const cognitoSyncManager = () => new AWS.CognitoSyncManager({ DataStore: AWS.CognitoSyncManager.StoreInMemory }); const getCognitoCredentials = (accessToken) => { // Initialize the Amazon Cognito credentials provider AWS.config.region = process.env.COGNITO_AWS_REGION; AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: process.env.COGNITO_IDENTITY_POOL_ID, Logins: { 'www.amazon.com': accessToken }, }); return AWS.config.credentials.getPromise(); }; const openOrCreateDataset = datasetName => new Promise((resolve, reject) => { cognitoSyncManager().openOrCreateDataset(datasetName, (error, dataset) => { if (error) { console.error(`Failed to open dataset: ${datasetName}`, error); return reject(error); } console.log('Opened dataset:', datasetName); return resolve(dataset); }); }); const saveItemsToDataset = (dataset, items) => new Promise((resolve, reject) => { dataset.putAll(items, (error) => { if (error) { console.error(`Failed to save items to dataset: ${items}`, error); return reject(error); } console.log('Saved items to dataset:', items); return resolve(dataset); }); }); const saveItemToDataset = (dataset, itemId, item) => new Promise((resolve, reject) => { dataset.put(itemId, item, (error, record) => { if (error) { console.error(`Failed to save item to dataset: ${item}`, error); return reject(error); } console.log('Saved item to dataset:', record); return resolve(dataset); }); }); const removeItemsFromDataset = (dataset, itemIds) => { // Save null values for the specified item IDs, causing them to be removed upon synchronization. const removedItems = itemIds.reduce((records, itemId) => ({ ...records, [itemId]: null }), {}); return saveItemsToDataset(dataset, removedItems); }; const removeItemFromDataset = (dataset, itemId) => new Promise((resolve, reject) => { dataset.remove(itemId, (error, record) => { if (error) { console.error(`Failed to remove item from dataset: ${itemId}`, error); return reject(error); } console.log('Removed item from dataset:', record); return resolve(dataset); }); }); const synchronizeDataset = dataset => new Promise((resolve, reject) => { dataset.synchronize({ onSuccess(syncedDataset, updatedRecords) { console.log('Synchronized dataset to remote store:', `${updatedRecords.length} records updated`); resolve(syncedDataset); }, onFailure(error) { console.error('Failed to synchronize dataset to remote store:', error); reject(error); }, onConflict, onDatasetDeleted, onDatasetsMerged, }); }); module.exports = { getCognitoCredentials, openOrCreateDataset, saveItemsToDataset, saveItemToDataset, removeItemsFromDataset, removeItemFromDataset, synchronizeDataset, };
Template[getTemplate('postUpvote')].helpers({ upvoted: function(){ var user = Meteor.user(); if(!user) return false; return _.include(this.upvoters, user._id); }, oneBasedRank: function(){ if(typeof this.rank !== 'undefined') return this.rank + 1; } }); Template[getTemplate('postUpvote')].events({ 'click .upvote-link': function(e, instance){ var post = this; e.preventDefault(); if(!Meteor.user()){ Router.go('/signin'); throwError(i18n.t("Please log in first")); } Meteor.call('upvotePost', post, function(error, result){ trackEvent("post upvoted", {'_id': post._id}); }); } });
var m = require('mithril'); module.exports = m.trust('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="full" width="24" height="24" viewBox="0 0 24.00 24.00" enable-background="new 0 0 24.00 24.00" xml:space="preserve"><path fill="#000000" fill-opacity="1" stroke-width="1.33333" stroke-linejoin="miter" d="M 3,4C 1.89001,3.9966 1,4.89 1,6L 1,17L 3,17C 3,18.6568 4.34315,20 6,20C 7.65685,20 9,18.6568 9,17L 15,17C 15,18.6568 16.3431,20 18,20C 19.6569,20 21,18.6568 21,17L 23,17L 23,14C 23,12.89 22.11,12 21,12L 19,12L 19,9.5L 23,9.5L 23,6C 23,4.89 22.1097,3.975 21,4L 3,4 Z M 2.5,5.5L 6.5,5.5L 6.5,8L 2.5,8L 2.5,5.5 Z M 8,5.5L 12,5.5L 12,8L 8,8L 8,5.5 Z M 13.5,5.5L 17.5,5.5L 17.5,8L 13.5,8L 13.5,5.5 Z M 19,5.5L 21.5,5.5L 21.5,8L 19,8L 19,5.5 Z M 13.5,9.5L 17.5,9.5L 17.5,12L 13.5,12L 13.5,9.5 Z M 2.5,9.5L 6.5,9.5L 6.5,12L 2.5,12L 2.5,9.5 Z M 8,9.5L 12,9.5L 12,12L 8,12L 8,9.5 Z M 6,15.5C 6.82843,15.5 7.5,16.1716 7.5,17C 7.5,17.8284 6.82843,18.5 6,18.5C 5.17157,18.5 4.5,17.8284 4.5,17C 4.5,16.1716 5.17157,15.5 6,15.5 Z M 18,15.5C 18.8284,15.5 19.5,16.1716 19.5,17C 19.5,17.8284 18.8284,18.5 18,18.5C 17.1716,18.5 16.5,17.8284 16.5,17C 16.5,16.1716 17.1716,15.5 18,15.5 Z "/></svg>');
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ import 'plugins/security/views/management/change_password_form/change_password_form'; import 'plugins/security/views/management/password_form/password_form'; import 'plugins/security/views/management/users'; import 'plugins/security/views/management/roles'; import 'plugins/security/views/management/edit_user'; import 'plugins/security/views/management/edit_role/index'; import 'plugins/security/views/management/management.less'; import routes from 'ui/routes'; import { XPackInfoProvider } from 'plugins/xpack_main/services/xpack_info'; import '../../services/shield_user'; import { ROLES_PATH, USERS_PATH } from './management_urls'; import { management } from 'ui/management'; routes.defaults(/\/management/, { resolve: { securityManagementSection: function (ShieldUser, Private) { const xpackInfo = Private(XPackInfoProvider); const showSecurityLinks = xpackInfo.get('features.security.showLinks'); function deregisterSecurity() { management.deregister('security'); } function ensureSecurityRegistered() { const registerSecurity = () => management.register('security', { display: 'Security', order: 10 }); const getSecurity = () => management.getSection('security'); const security = (management.hasItem('security')) ? getSecurity() : registerSecurity(); if (!security.hasItem('users')) { security.register('users', { name: 'securityUsersLink', order: 10, display: 'Users', url: `#${USERS_PATH}`, }); } if (!security.hasItem('roles')) { security.register('roles', { name: 'securityRolesLink', order: 20, display: 'Roles', url: `#${ROLES_PATH}`, }); } } deregisterSecurity(); if (!showSecurityLinks) return; // getCurrent will reject if there is no authenticated user, so we prevent them from seeing the security // management screens // // $promise is used here because the result is an ngResource, not a promise itself return ShieldUser.getCurrent().$promise .then(ensureSecurityRegistered) .catch(deregisterSecurity); } } });
/*! DataTables 1.10.16 * ©2008-2017 SpryMedia Ltd - datatables.net/license */ /** * @summary DataTables * @description Paginate, search and order HTML tables * @version 1.10.16 * @file jquery.dataTables.js * @author SpryMedia Ltd * @contact www.datatables.net * @copyright Copyright 2008-2017 SpryMedia Ltd. * * This source file is free software, available under the following license: * MIT license - http://datatables.net/license * * This source file is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details. * * For details please refer to: http://www.datatables.net */ /*jslint evil: true, undef: true, browser: true */ /*globals $,require,jQuery,define,_selector_run,_selector_opts,_selector_first,_selector_row_indexes,_ext,_Api,_api_register,_api_registerPlural,_re_new_lines,_re_html,_re_formatted_numeric,_re_escape_regex,_empty,_intVal,_numToDecimal,_isNumber,_isHtml,_htmlNumeric,_pluck,_pluck_order,_range,_stripHtml,_unique,_fnBuildAjax,_fnAjaxUpdate,_fnAjaxParameters,_fnAjaxUpdateDraw,_fnAjaxDataSrc,_fnAddColumn,_fnColumnOptions,_fnAdjustColumnSizing,_fnVisibleToColumnIndex,_fnColumnIndexToVisible,_fnVisbleColumns,_fnGetColumns,_fnColumnTypes,_fnApplyColumnDefs,_fnHungarianMap,_fnCamelToHungarian,_fnLanguageCompat,_fnBrowserDetect,_fnAddData,_fnAddTr,_fnNodeToDataIndex,_fnNodeToColumnIndex,_fnGetCellData,_fnSetCellData,_fnSplitObjNotation,_fnGetObjectDataFn,_fnSetObjectDataFn,_fnGetDataMaster,_fnClearTable,_fnDeleteIndex,_fnInvalidate,_fnGetRowElements,_fnCreateTr,_fnBuildHead,_fnDrawHead,_fnDraw,_fnReDraw,_fnAddOptionsHtml,_fnDetectHeader,_fnGetUniqueThs,_fnFeatureHtmlFilter,_fnFilterComplete,_fnFilterCustom,_fnFilterColumn,_fnFilter,_fnFilterCreateSearch,_fnEscapeRegex,_fnFilterData,_fnFeatureHtmlInfo,_fnUpdateInfo,_fnInfoMacros,_fnInitialise,_fnInitComplete,_fnLengthChange,_fnFeatureHtmlLength,_fnFeatureHtmlPaginate,_fnPageChange,_fnFeatureHtmlProcessing,_fnProcessingDisplay,_fnFeatureHtmlTable,_fnScrollDraw,_fnApplyToChildren,_fnCalculateColumnWidths,_fnThrottle,_fnConvertToWidth,_fnGetWidestNode,_fnGetMaxLenString,_fnStringToCss,_fnSortFlatten,_fnSort,_fnSortAria,_fnSortListener,_fnSortAttachListener,_fnSortingClasses,_fnSortData,_fnSaveState,_fnLoadState,_fnSettingsFromNode,_fnLog,_fnMap,_fnBindAction,_fnCallbackReg,_fnCallbackFire,_fnLengthOverflow,_fnRenderer,_fnDataSource,_fnRowAttributes*/ (function( factory ) { "use strict"; if ( typeof define === 'function' && define.amd ) { // AMD define( ['jquery'], function ( $ ) { return factory( $, window, document ); } ); } else if ( typeof exports === 'object' ) { // CommonJS module.exports = function (root, $) { if ( ! root ) { // CommonJS environments without a window global must pass a // root. This will give an error otherwise root = window; } if ( ! $ ) { $ = typeof window !== 'undefined' ? // jQuery's factory checks for a global window require('jquery') : require('jquery')( root ); } return factory( $, root, root.document ); }; } else { // Browser factory( jQuery, window, document ); } } (function( $, window, document, undefined ) { "use strict"; /** * DataTables is a plug-in for the jQuery Javascript library. It is a highly * flexible tool, based upon the foundations of progressive enhancement, * which will add advanced interaction controls to any HTML table. For a * full list of features please refer to * [DataTables.net](href="http://datatables.net). * * Note that the `DataTable` object is not a global variable but is aliased * to `jQuery.fn.DataTable` and `jQuery.fn.dataTable` through which it may * be accessed. * * @class * @param {object} [init={}] Configuration object for DataTables. Options * are defined by {@link DataTable.defaults} * @requires jQuery 1.7+ * * @example * // Basic initialisation * $(document).ready( function { * $('#example').dataTable(); * } ); * * @example * // Initialisation with configuration options - in this case, disable * // pagination and sorting. * $(document).ready( function { * $('#example').dataTable( { * "paginate": false, * "sort": false * } ); * } ); */ var DataTable = function ( options ) { /** * Perform a jQuery selector action on the table's TR elements (from the tbody) and * return the resulting jQuery object. * @param {string|node|jQuery} sSelector jQuery selector or node collection to act on * @param {object} [oOpts] Optional parameters for modifying the rows to be included * @param {string} [oOpts.filter=none] Select TR elements that meet the current filter * criterion ("applied") or all TR elements (i.e. no filter). * @param {string} [oOpts.order=current] Order of the TR elements in the processed array. * Can be either 'current', whereby the current sorting of the table is used, or * 'original' whereby the original order the data was read into the table is used. * @param {string} [oOpts.page=all] Limit the selection to the currently displayed page * ("current") or not ("all"). If 'current' is given, then order is assumed to be * 'current' and filter is 'applied', regardless of what they might be given as. * @returns {object} jQuery object, filtered by the given selector. * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Highlight every second row * oTable.$('tr:odd').css('backgroundColor', 'blue'); * } ); * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Filter to rows with 'Webkit' in them, add a background colour and then * // remove the filter, thus highlighting the 'Webkit' rows only. * oTable.fnFilter('Webkit'); * oTable.$('tr', {"search": "applied"}).css('backgroundColor', 'blue'); * oTable.fnFilter(''); * } ); */ this.$ = function ( sSelector, oOpts ) { return this.api(true).$( sSelector, oOpts ); }; /** * Almost identical to $ in operation, but in this case returns the data for the matched * rows - as such, the jQuery selector used should match TR row nodes or TD/TH cell nodes * rather than any descendants, so the data can be obtained for the row/cell. If matching * rows are found, the data returned is the original data array/object that was used to * create the row (or a generated array if from a DOM source). * * This method is often useful in-combination with $ where both functions are given the * same parameters and the array indexes will match identically. * @param {string|node|jQuery} sSelector jQuery selector or node collection to act on * @param {object} [oOpts] Optional parameters for modifying the rows to be included * @param {string} [oOpts.filter=none] Select elements that meet the current filter * criterion ("applied") or all elements (i.e. no filter). * @param {string} [oOpts.order=current] Order of the data in the processed array. * Can be either 'current', whereby the current sorting of the table is used, or * 'original' whereby the original order the data was read into the table is used. * @param {string} [oOpts.page=all] Limit the selection to the currently displayed page * ("current") or not ("all"). If 'current' is given, then order is assumed to be * 'current' and filter is 'applied', regardless of what they might be given as. * @returns {array} Data for the matched elements. If any elements, as a result of the * selector, were not TR, TD or TH elements in the DataTable, they will have a null * entry in the array. * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Get the data from the first row in the table * var data = oTable._('tr:first'); * * // Do something useful with the data * alert( "First cell is: "+data[0] ); * } ); * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Filter to 'Webkit' and get all data for * oTable.fnFilter('Webkit'); * var data = oTable._('tr', {"search": "applied"}); * * // Do something with the data * alert( data.length+" rows matched the search" ); * } ); */ this._ = function ( sSelector, oOpts ) { return this.api(true).rows( sSelector, oOpts ).data(); }; /** * Create a DataTables Api instance, with the currently selected tables for * the Api's context. * @param {boolean} [traditional=false] Set the API instance's context to be * only the table referred to by the `DataTable.ext.iApiIndex` option, as was * used in the API presented by DataTables 1.9- (i.e. the traditional mode), * or if all tables captured in the jQuery object should be used. * @return {DataTables.Api} */ this.api = function ( traditional ) { return traditional ? new _Api( _fnSettingsFromNode( this[ _ext.iApiIndex ] ) ) : new _Api( this ); }; /** * Add a single new row or multiple rows of data to the table. Please note * that this is suitable for client-side processing only - if you are using * server-side processing (i.e. "bServerSide": true), then to add data, you * must add it to the data source, i.e. the server-side, through an Ajax call. * @param {array|object} data The data to be added to the table. This can be: * <ul> * <li>1D array of data - add a single row with the data provided</li> * <li>2D array of arrays - add multiple rows in a single call</li> * <li>object - data object when using <i>mData</i></li> * <li>array of objects - multiple data objects when using <i>mData</i></li> * </ul> * @param {bool} [redraw=true] redraw the table or not * @returns {array} An array of integers, representing the list of indexes in * <i>aoData</i> ({@link DataTable.models.oSettings}) that have been added to * the table. * @dtopt API * @deprecated Since v1.10 * * @example * // Global var for counter * var giCount = 2; * * $(document).ready(function() { * $('#example').dataTable(); * } ); * * function fnClickAddRow() { * $('#example').dataTable().fnAddData( [ * giCount+".1", * giCount+".2", * giCount+".3", * giCount+".4" ] * ); * * giCount++; * } */ this.fnAddData = function( data, redraw ) { var api = this.api( true ); /* Check if we want to add multiple rows or not */ var rows = $.isArray(data) && ( $.isArray(data[0]) || $.isPlainObject(data[0]) ) ? api.rows.add( data ) : api.row.add( data ); if ( redraw === undefined || redraw ) { api.draw(); } return rows.flatten().toArray(); }; /** * This function will make DataTables recalculate the column sizes, based on the data * contained in the table and the sizes applied to the columns (in the DOM, CSS or * through the sWidth parameter). This can be useful when the width of the table's * parent element changes (for example a window resize). * @param {boolean} [bRedraw=true] Redraw the table or not, you will typically want to * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable( { * "sScrollY": "200px", * "bPaginate": false * } ); * * $(window).on('resize', function () { * oTable.fnAdjustColumnSizing(); * } ); * } ); */ this.fnAdjustColumnSizing = function ( bRedraw ) { var api = this.api( true ).columns.adjust(); var settings = api.settings()[0]; var scroll = settings.oScroll; if ( bRedraw === undefined || bRedraw ) { api.draw( false ); } else if ( scroll.sX !== "" || scroll.sY !== "" ) { /* If not redrawing, but scrolling, we want to apply the new column sizes anyway */ _fnScrollDraw( settings ); } }; /** * Quickly and simply clear a table * @param {bool} [bRedraw=true] redraw the table or not * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Immediately 'nuke' the current rows (perhaps waiting for an Ajax callback...) * oTable.fnClearTable(); * } ); */ this.fnClearTable = function( bRedraw ) { var api = this.api( true ).clear(); if ( bRedraw === undefined || bRedraw ) { api.draw(); } }; /** * The exact opposite of 'opening' a row, this function will close any rows which * are currently 'open'. * @param {node} nTr the table row to 'close' * @returns {int} 0 on success, or 1 if failed (can't find the row) * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable; * * // 'open' an information row when a row is clicked on * $('#example tbody tr').click( function () { * if ( oTable.fnIsOpen(this) ) { * oTable.fnClose( this ); * } else { * oTable.fnOpen( this, "Temporary row opened", "info_row" ); * } * } ); * * oTable = $('#example').dataTable(); * } ); */ this.fnClose = function( nTr ) { this.api( true ).row( nTr ).child.hide(); }; /** * Remove a row for the table * @param {mixed} target The index of the row from aoData to be deleted, or * the TR element you want to delete * @param {function|null} [callBack] Callback function * @param {bool} [redraw=true] Redraw the table or not * @returns {array} The row that was deleted * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Immediately remove the first row * oTable.fnDeleteRow( 0 ); * } ); */ this.fnDeleteRow = function( target, callback, redraw ) { var api = this.api( true ); var rows = api.rows( target ); var settings = rows.settings()[0]; var data = settings.aoData[ rows[0][0] ]; rows.remove(); if ( callback ) { callback.call( this, settings, data ); } if ( redraw === undefined || redraw ) { api.draw(); } return data; }; /** * Restore the table to it's original state in the DOM by removing all of DataTables * enhancements, alterations to the DOM structure of the table and event listeners. * @param {boolean} [remove=false] Completely remove the table from the DOM * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * // This example is fairly pointless in reality, but shows how fnDestroy can be used * var oTable = $('#example').dataTable(); * oTable.fnDestroy(); * } ); */ this.fnDestroy = function ( remove ) { this.api( true ).destroy( remove ); }; /** * Redraw the table * @param {bool} [complete=true] Re-filter and resort (if enabled) the table before the draw. * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Re-draw the table - you wouldn't want to do it here, but it's an example :-) * oTable.fnDraw(); * } ); */ this.fnDraw = function( complete ) { // Note that this isn't an exact match to the old call to _fnDraw - it takes // into account the new data, but can hold position. this.api( true ).draw( complete ); }; /** * Filter the input based on data * @param {string} sInput String to filter the table on * @param {int|null} [iColumn] Column to limit filtering to * @param {bool} [bRegex=false] Treat as regular expression or not * @param {bool} [bSmart=true] Perform smart filtering or not * @param {bool} [bShowGlobal=true] Show the input global filter in it's input box(es) * @param {bool} [bCaseInsensitive=true] Do case-insensitive matching (true) or not (false) * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Sometime later - filter... * oTable.fnFilter( 'test string' ); * } ); */ this.fnFilter = function( sInput, iColumn, bRegex, bSmart, bShowGlobal, bCaseInsensitive ) { var api = this.api( true ); if ( iColumn === null || iColumn === undefined ) { api.search( sInput, bRegex, bSmart, bCaseInsensitive ); } else { api.column( iColumn ).search( sInput, bRegex, bSmart, bCaseInsensitive ); } api.draw(); }; /** * Get the data for the whole table, an individual row or an individual cell based on the * provided parameters. * @param {int|node} [src] A TR row node, TD/TH cell node or an integer. If given as * a TR node then the data source for the whole row will be returned. If given as a * TD/TH cell node then iCol will be automatically calculated and the data for the * cell returned. If given as an integer, then this is treated as the aoData internal * data index for the row (see fnGetPosition) and the data for that row used. * @param {int} [col] Optional column index that you want the data of. * @returns {array|object|string} If mRow is undefined, then the data for all rows is * returned. If mRow is defined, just data for that row, and is iCol is * defined, only data for the designated cell is returned. * @dtopt API * @deprecated Since v1.10 * * @example * // Row data * $(document).ready(function() { * oTable = $('#example').dataTable(); * * oTable.$('tr').click( function () { * var data = oTable.fnGetData( this ); * // ... do something with the array / object of data for the row * } ); * } ); * * @example * // Individual cell data * $(document).ready(function() { * oTable = $('#example').dataTable(); * * oTable.$('td').click( function () { * var sData = oTable.fnGetData( this ); * alert( 'The cell clicked on had the value of '+sData ); * } ); * } ); */ this.fnGetData = function( src, col ) { var api = this.api( true ); if ( src !== undefined ) { var type = src.nodeName ? src.nodeName.toLowerCase() : ''; return col !== undefined || type == 'td' || type == 'th' ? api.cell( src, col ).data() : api.row( src ).data() || null; } return api.data().toArray(); }; /** * Get an array of the TR nodes that are used in the table's body. Note that you will * typically want to use the '$' API method in preference to this as it is more * flexible. * @param {int} [iRow] Optional row index for the TR element you want * @returns {array|node} If iRow is undefined, returns an array of all TR elements * in the table's body, or iRow is defined, just the TR element requested. * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Get the nodes from the table * var nNodes = oTable.fnGetNodes( ); * } ); */ this.fnGetNodes = function( iRow ) { var api = this.api( true ); return iRow !== undefined ? api.row( iRow ).node() : api.rows().nodes().flatten().toArray(); }; /** * Get the array indexes of a particular cell from it's DOM element * and column index including hidden columns * @param {node} node this can either be a TR, TD or TH in the table's body * @returns {int} If nNode is given as a TR, then a single index is returned, or * if given as a cell, an array of [row index, column index (visible), * column index (all)] is given. * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * $('#example tbody td').click( function () { * // Get the position of the current data from the node * var aPos = oTable.fnGetPosition( this ); * * // Get the data array for this row * var aData = oTable.fnGetData( aPos[0] ); * * // Update the data array and return the value * aData[ aPos[1] ] = 'clicked'; * this.innerHTML = 'clicked'; * } ); * * // Init DataTables * oTable = $('#example').dataTable(); * } ); */ this.fnGetPosition = function( node ) { var api = this.api( true ); var nodeName = node.nodeName.toUpperCase(); if ( nodeName == 'TR' ) { return api.row( node ).index(); } else if ( nodeName == 'TD' || nodeName == 'TH' ) { var cell = api.cell( node ).index(); return [ cell.row, cell.columnVisible, cell.column ]; } return null; }; /** * Check to see if a row is 'open' or not. * @param {node} nTr the table row to check * @returns {boolean} true if the row is currently open, false otherwise * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable; * * // 'open' an information row when a row is clicked on * $('#example tbody tr').click( function () { * if ( oTable.fnIsOpen(this) ) { * oTable.fnClose( this ); * } else { * oTable.fnOpen( this, "Temporary row opened", "info_row" ); * } * } ); * * oTable = $('#example').dataTable(); * } ); */ this.fnIsOpen = function( nTr ) { return this.api( true ).row( nTr ).child.isShown(); }; /** * This function will place a new row directly after a row which is currently * on display on the page, with the HTML contents that is passed into the * function. This can be used, for example, to ask for confirmation that a * particular record should be deleted. * @param {node} nTr The table row to 'open' * @param {string|node|jQuery} mHtml The HTML to put into the row * @param {string} sClass Class to give the new TD cell * @returns {node} The row opened. Note that if the table row passed in as the * first parameter, is not found in the table, this method will silently * return. * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable; * * // 'open' an information row when a row is clicked on * $('#example tbody tr').click( function () { * if ( oTable.fnIsOpen(this) ) { * oTable.fnClose( this ); * } else { * oTable.fnOpen( this, "Temporary row opened", "info_row" ); * } * } ); * * oTable = $('#example').dataTable(); * } ); */ this.fnOpen = function( nTr, mHtml, sClass ) { return this.api( true ) .row( nTr ) .child( mHtml, sClass ) .show() .child()[0]; }; /** * Change the pagination - provides the internal logic for pagination in a simple API * function. With this function you can have a DataTables table go to the next, * previous, first or last pages. * @param {string|int} mAction Paging action to take: "first", "previous", "next" or "last" * or page number to jump to (integer), note that page 0 is the first page. * @param {bool} [bRedraw=true] Redraw the table or not * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * oTable.fnPageChange( 'next' ); * } ); */ this.fnPageChange = function ( mAction, bRedraw ) { var api = this.api( true ).page( mAction ); if ( bRedraw === undefined || bRedraw ) { api.draw(false); } }; /** * Show a particular column * @param {int} iCol The column whose display should be changed * @param {bool} bShow Show (true) or hide (false) the column * @param {bool} [bRedraw=true] Redraw the table or not * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Hide the second column after initialisation * oTable.fnSetColumnVis( 1, false ); * } ); */ this.fnSetColumnVis = function ( iCol, bShow, bRedraw ) { var api = this.api( true ).column( iCol ).visible( bShow ); if ( bRedraw === undefined || bRedraw ) { api.columns.adjust().draw(); } }; /** * Get the settings for a particular table for external manipulation * @returns {object} DataTables settings object. See * {@link DataTable.models.oSettings} * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * var oSettings = oTable.fnSettings(); * * // Show an example parameter from the settings * alert( oSettings._iDisplayStart ); * } ); */ this.fnSettings = function() { return _fnSettingsFromNode( this[_ext.iApiIndex] ); }; /** * Sort the table by a particular column * @param {int} iCol the data index to sort on. Note that this will not match the * 'display index' if you have hidden data entries * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Sort immediately with columns 0 and 1 * oTable.fnSort( [ [0,'asc'], [1,'asc'] ] ); * } ); */ this.fnSort = function( aaSort ) { this.api( true ).order( aaSort ).draw(); }; /** * Attach a sort listener to an element for a given column * @param {node} nNode the element to attach the sort listener to * @param {int} iColumn the column that a click on this node will sort on * @param {function} [fnCallback] callback function when sort is run * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Sort on column 1, when 'sorter' is clicked on * oTable.fnSortListener( document.getElementById('sorter'), 1 ); * } ); */ this.fnSortListener = function( nNode, iColumn, fnCallback ) { this.api( true ).order.listener( nNode, iColumn, fnCallback ); }; /** * Update a table cell or row - this method will accept either a single value to * update the cell with, an array of values with one element for each column or * an object in the same format as the original data source. The function is * self-referencing in order to make the multi column updates easier. * @param {object|array|string} mData Data to update the cell/row with * @param {node|int} mRow TR element you want to update or the aoData index * @param {int} [iColumn] The column to update, give as null or undefined to * update a whole row. * @param {bool} [bRedraw=true] Redraw the table or not * @param {bool} [bAction=true] Perform pre-draw actions or not * @returns {int} 0 on success, 1 on error * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * oTable.fnUpdate( 'Example update', 0, 0 ); // Single cell * oTable.fnUpdate( ['a', 'b', 'c', 'd', 'e'], $('tbody tr')[0] ); // Row * } ); */ this.fnUpdate = function( mData, mRow, iColumn, bRedraw, bAction ) { var api = this.api( true ); if ( iColumn === undefined || iColumn === null ) { api.row( mRow ).data( mData ); } else { api.cell( mRow, iColumn ).data( mData ); } if ( bAction === undefined || bAction ) { api.columns.adjust(); } if ( bRedraw === undefined || bRedraw ) { api.draw(); } return 0; }; /** * Provide a common method for plug-ins to check the version of DataTables being used, in order * to ensure compatibility. * @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note that the * formats "X" and "X.Y" are also acceptable. * @returns {boolean} true if this version of DataTables is greater or equal to the required * version, or false if this version of DataTales is not suitable * @method * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * alert( oTable.fnVersionCheck( '1.9.0' ) ); * } ); */ this.fnVersionCheck = _ext.fnVersionCheck; var _that = this; var emptyInit = options === undefined; var len = this.length; if ( emptyInit ) { options = {}; } this.oApi = this.internal = _ext.internal; // Extend with old style plug-in API methods for ( var fn in DataTable.ext.internal ) { if ( fn ) { this[fn] = _fnExternApiFunc(fn); } } this.each(function() { // For each initialisation we want to give it a clean initialisation // object that can be bashed around var o = {}; var oInit = len > 1 ? // optimisation for single table case _fnExtend( o, options, true ) : options; /*global oInit,_that,emptyInit*/ var i=0, iLen, j, jLen, k, kLen; var sId = this.getAttribute( 'id' ); var bInitHandedOff = false; var defaults = DataTable.defaults; var $this = $(this); /* Sanity check */ if ( this.nodeName.toLowerCase() != 'table' ) { _fnLog( null, 0, 'Non-table node initialisation ('+this.nodeName+')', 2 ); return; } /* Backwards compatibility for the defaults */ _fnCompatOpts( defaults ); _fnCompatCols( defaults.column ); /* Convert the camel-case defaults to Hungarian */ _fnCamelToHungarian( defaults, defaults, true ); _fnCamelToHungarian( defaults.column, defaults.column, true ); /* Setting up the initialisation object */ _fnCamelToHungarian( defaults, $.extend( oInit, $this.data() ) ); /* Check to see if we are re-initialising a table */ var allSettings = DataTable.settings; for ( i=0, iLen=allSettings.length ; i<iLen ; i++ ) { var s = allSettings[i]; /* Base check on table node */ if ( s.nTable == this || s.nTHead.parentNode == this || (s.nTFoot && s.nTFoot.parentNode == this) ) { var bRetrieve = oInit.bRetrieve !== undefined ? oInit.bRetrieve : defaults.bRetrieve; var bDestroy = oInit.bDestroy !== undefined ? oInit.bDestroy : defaults.bDestroy; if ( emptyInit || bRetrieve ) { return s.oInstance; } else if ( bDestroy ) { s.oInstance.fnDestroy(); break; } else { _fnLog( s, 0, 'Cannot reinitialise DataTable', 3 ); return; } } /* If the element we are initialising has the same ID as a table which was previously * initialised, but the table nodes don't match (from before) then we destroy the old * instance by simply deleting it. This is under the assumption that the table has been * destroyed by other methods. Anyone using non-id selectors will need to do this manually */ if ( s.sTableId == this.id ) { allSettings.splice( i, 1 ); break; } } /* Ensure the table has an ID - required for accessibility */ if ( sId === null || sId === "" ) { sId = "DataTables_Table_"+(DataTable.ext._unique++); this.id = sId; } /* Create the settings object for this table and set some of the default parameters */ var oSettings = $.extend( true, {}, DataTable.models.oSettings, { "sDestroyWidth": $this[0].style.width, "sInstance": sId, "sTableId": sId } ); oSettings.nTable = this; oSettings.oApi = _that.internal; oSettings.oInit = oInit; allSettings.push( oSettings ); // Need to add the instance after the instance after the settings object has been added // to the settings array, so we can self reference the table instance if more than one oSettings.oInstance = (_that.length===1) ? _that : $this.dataTable(); // Backwards compatibility, before we apply all the defaults _fnCompatOpts( oInit ); if ( oInit.oLanguage ) { _fnLanguageCompat( oInit.oLanguage ); } // If the length menu is given, but the init display length is not, use the length menu if ( oInit.aLengthMenu && ! oInit.iDisplayLength ) { oInit.iDisplayLength = $.isArray( oInit.aLengthMenu[0] ) ? oInit.aLengthMenu[0][0] : oInit.aLengthMenu[0]; } // Apply the defaults and init options to make a single init object will all // options defined from defaults and instance options. oInit = _fnExtend( $.extend( true, {}, defaults ), oInit ); // Map the initialisation options onto the settings object _fnMap( oSettings.oFeatures, oInit, [ "bPaginate", "bLengthChange", "bFilter", "bSort", "bSortMulti", "bInfo", "bProcessing", "bAutoWidth", "bSortClasses", "bServerSide", "bDeferRender" ] ); _fnMap( oSettings, oInit, [ "asStripeClasses", "ajax", "fnServerData", "fnFormatNumber", "sServerMethod", "aaSorting", "aaSortingFixed", "aLengthMenu", "sPaginationType", "sAjaxSource", "sAjaxDataProp", "iStateDuration", "sDom", "bSortCellsTop", "iTabIndex", "fnStateLoadCallback", "fnStateSaveCallback", "renderer", "searchDelay", "rowId", [ "iCookieDuration", "iStateDuration" ], // backwards compat [ "oSearch", "oPreviousSearch" ], [ "aoSearchCols", "aoPreSearchCols" ], [ "iDisplayLength", "_iDisplayLength" ] ] ); _fnMap( oSettings.oScroll, oInit, [ [ "sScrollX", "sX" ], [ "sScrollXInner", "sXInner" ], [ "sScrollY", "sY" ], [ "bScrollCollapse", "bCollapse" ] ] ); _fnMap( oSettings.oLanguage, oInit, "fnInfoCallback" ); /* Callback functions which are array driven */ _fnCallbackReg( oSettings, 'aoDrawCallback', oInit.fnDrawCallback, 'user' ); _fnCallbackReg( oSettings, 'aoServerParams', oInit.fnServerParams, 'user' ); _fnCallbackReg( oSettings, 'aoStateSaveParams', oInit.fnStateSaveParams, 'user' ); _fnCallbackReg( oSettings, 'aoStateLoadParams', oInit.fnStateLoadParams, 'user' ); _fnCallbackReg( oSettings, 'aoStateLoaded', oInit.fnStateLoaded, 'user' ); _fnCallbackReg( oSettings, 'aoRowCallback', oInit.fnRowCallback, 'user' ); _fnCallbackReg( oSettings, 'aoRowCreatedCallback', oInit.fnCreatedRow, 'user' ); _fnCallbackReg( oSettings, 'aoHeaderCallback', oInit.fnHeaderCallback, 'user' ); _fnCallbackReg( oSettings, 'aoFooterCallback', oInit.fnFooterCallback, 'user' ); _fnCallbackReg( oSettings, 'aoInitComplete', oInit.fnInitComplete, 'user' ); _fnCallbackReg( oSettings, 'aoPreDrawCallback', oInit.fnPreDrawCallback, 'user' ); oSettings.rowIdFn = _fnGetObjectDataFn( oInit.rowId ); /* Browser support detection */ _fnBrowserDetect( oSettings ); var oClasses = oSettings.oClasses; $.extend( oClasses, DataTable.ext.classes, oInit.oClasses ); $this.addClass( oClasses.sTable ); if ( oSettings.iInitDisplayStart === undefined ) { /* Display start point, taking into account the save saving */ oSettings.iInitDisplayStart = oInit.iDisplayStart; oSettings._iDisplayStart = oInit.iDisplayStart; } if ( oInit.iDeferLoading !== null ) { oSettings.bDeferLoading = true; var tmp = $.isArray( oInit.iDeferLoading ); oSettings._iRecordsDisplay = tmp ? oInit.iDeferLoading[0] : oInit.iDeferLoading; oSettings._iRecordsTotal = tmp ? oInit.iDeferLoading[1] : oInit.iDeferLoading; } /* Language definitions */ var oLanguage = oSettings.oLanguage; $.extend( true, oLanguage, oInit.oLanguage ); if ( oLanguage.sUrl ) { /* Get the language definitions from a file - because this Ajax call makes the language * get async to the remainder of this function we use bInitHandedOff to indicate that * _fnInitialise will be fired by the returned Ajax handler, rather than the constructor */ $.ajax( { dataType: 'json', url: oLanguage.sUrl, success: function ( json ) { _fnLanguageCompat( json ); _fnCamelToHungarian( defaults.oLanguage, json ); $.extend( true, oLanguage, json ); _fnInitialise( oSettings ); }, error: function () { // Error occurred loading language file, continue on as best we can _fnInitialise( oSettings ); } } ); bInitHandedOff = true; } /* * Stripes */ if ( oInit.asStripeClasses === null ) { oSettings.asStripeClasses =[ oClasses.sStripeOdd, oClasses.sStripeEven ]; } /* Remove row stripe classes if they are already on the table row */ var stripeClasses = oSettings.asStripeClasses; var rowOne = $this.children('tbody').find('tr').eq(0); if ( $.inArray( true, $.map( stripeClasses, function(el, i) { return rowOne.hasClass(el); } ) ) !== -1 ) { $('tbody tr', this).removeClass( stripeClasses.join(' ') ); oSettings.asDestroyStripes = stripeClasses.slice(); } /* * Columns * See if we should load columns automatically or use defined ones */ var anThs = []; var aoColumnsInit; var nThead = this.getElementsByTagName('thead'); if ( nThead.length !== 0 ) { _fnDetectHeader( oSettings.aoHeader, nThead[0] ); anThs = _fnGetUniqueThs( oSettings ); } /* If not given a column array, generate one with nulls */ if ( oInit.aoColumns === null ) { aoColumnsInit = []; for ( i=0, iLen=anThs.length ; i<iLen ; i++ ) { aoColumnsInit.push( null ); } } else { aoColumnsInit = oInit.aoColumns; } /* Add the columns */ for ( i=0, iLen=aoColumnsInit.length ; i<iLen ; i++ ) { _fnAddColumn( oSettings, anThs ? anThs[i] : null ); } /* Apply the column definitions */ _fnApplyColumnDefs( oSettings, oInit.aoColumnDefs, aoColumnsInit, function (iCol, oDef) { _fnColumnOptions( oSettings, iCol, oDef ); } ); /* HTML5 attribute detection - build an mData object automatically if the * attributes are found */ if ( rowOne.length ) { var a = function ( cell, name ) { return cell.getAttribute( 'data-'+name ) !== null ? name : null; }; $( rowOne[0] ).children('th, td').each( function (i, cell) { var col = oSettings.aoColumns[i]; if ( col.mData === i ) { var sort = a( cell, 'sort' ) || a( cell, 'order' ); var filter = a( cell, 'filter' ) || a( cell, 'search' ); if ( sort !== null || filter !== null ) { col.mData = { _: i+'.display', sort: sort !== null ? i+'.@data-'+sort : undefined, type: sort !== null ? i+'.@data-'+sort : undefined, filter: filter !== null ? i+'.@data-'+filter : undefined }; _fnColumnOptions( oSettings, i ); } } } ); } var features = oSettings.oFeatures; var loadedInit = function () { /* * Sorting * @todo For modularisation (1.11) this needs to do into a sort start up handler */ // If aaSorting is not defined, then we use the first indicator in asSorting // in case that has been altered, so the default sort reflects that option if ( oInit.aaSorting === undefined ) { var sorting = oSettings.aaSorting; for ( i=0, iLen=sorting.length ; i<iLen ; i++ ) { sorting[i][1] = oSettings.aoColumns[ i ].asSorting[0]; } } /* Do a first pass on the sorting classes (allows any size changes to be taken into * account, and also will apply sorting disabled classes if disabled */ _fnSortingClasses( oSettings ); if ( features.bSort ) { _fnCallbackReg( oSettings, 'aoDrawCallback', function () { if ( oSettings.bSorted ) { var aSort = _fnSortFlatten( oSettings ); var sortedColumns = {}; $.each( aSort, function (i, val) { sortedColumns[ val.src ] = val.dir; } ); _fnCallbackFire( oSettings, null, 'order', [oSettings, aSort, sortedColumns] ); _fnSortAria( oSettings ); } } ); } _fnCallbackReg( oSettings, 'aoDrawCallback', function () { if ( oSettings.bSorted || _fnDataSource( oSettings ) === 'ssp' || features.bDeferRender ) { _fnSortingClasses( oSettings ); } }, 'sc' ); /* * Final init * Cache the header, body and footer as required, creating them if needed */ // Work around for Webkit bug 83867 - store the caption-side before removing from doc var captions = $this.children('caption').each( function () { this._captionSide = $(this).css('caption-side'); } ); var thead = $this.children('thead'); if ( thead.length === 0 ) { thead = $('<thead/>').appendTo($this); } oSettings.nTHead = thead[0]; var tbody = $this.children('tbody'); if ( tbody.length === 0 ) { tbody = $('<tbody/>').appendTo($this); } oSettings.nTBody = tbody[0]; var tfoot = $this.children('tfoot'); if ( tfoot.length === 0 && captions.length > 0 && (oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "") ) { // If we are a scrolling table, and no footer has been given, then we need to create // a tfoot element for the caption element to be appended to tfoot = $('<tfoot/>').appendTo($this); } if ( tfoot.length === 0 || tfoot.children().length === 0 ) { $this.addClass( oClasses.sNoFooter ); } else if ( tfoot.length > 0 ) { oSettings.nTFoot = tfoot[0]; _fnDetectHeader( oSettings.aoFooter, oSettings.nTFoot ); } /* Check if there is data passing into the constructor */ if ( oInit.aaData ) { for ( i=0 ; i<oInit.aaData.length ; i++ ) { _fnAddData( oSettings, oInit.aaData[ i ] ); } } else if ( oSettings.bDeferLoading || _fnDataSource( oSettings ) == 'dom' ) { /* Grab the data from the page - only do this when deferred loading or no Ajax * source since there is no point in reading the DOM data if we are then going * to replace it with Ajax data */ _fnAddTr( oSettings, $(oSettings.nTBody).children('tr') ); } /* Copy the data index array */ oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); /* Initialisation complete - table can be drawn */ oSettings.bInitialised = true; /* Check if we need to initialise the table (it might not have been handed off to the * language processor) */ if ( bInitHandedOff === false ) { _fnInitialise( oSettings ); } }; /* Must be done after everything which can be overridden by the state saving! */ if ( oInit.bStateSave ) { features.bStateSave = true; _fnCallbackReg( oSettings, 'aoDrawCallback', _fnSaveState, 'state_save' ); _fnLoadState( oSettings, oInit, loadedInit ); } else { loadedInit(); } } ); _that = null; return this; }; /* * It is useful to have variables which are scoped locally so only the * DataTables functions can access them and they don't leak into global space. * At the same time these functions are often useful over multiple files in the * core and API, so we list, or at least document, all variables which are used * by DataTables as private variables here. This also ensures that there is no * clashing of variable names and that they can easily referenced for reuse. */ // Defined else where // _selector_run // _selector_opts // _selector_first // _selector_row_indexes var _ext; // DataTable.ext var _Api; // DataTable.Api var _api_register; // DataTable.Api.register var _api_registerPlural; // DataTable.Api.registerPlural var _re_dic = {}; var _re_new_lines = /[\r\n]/g; var _re_html = /<.*?>/g; // This is not strict ISO8601 - Date.parse() is quite lax, although // implementations differ between browsers. var _re_date = /^\d{2,4}[\.\/\-]\d{1,2}[\.\/\-]\d{1,2}([T ]{1}\d{1,2}[:\.]\d{2}([\.:]\d{2})?)?$/; // Escape regular expression special characters var _re_escape_regex = new RegExp( '(\\' + [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '$', '^', '-' ].join('|\\') + ')', 'g' ); // http://en.wikipedia.org/wiki/Foreign_exchange_market // - \u20BD - Russian ruble. // - \u20a9 - South Korean Won // - \u20BA - Turkish Lira // - \u20B9 - Indian Rupee // - R - Brazil (R$) and South Africa // - fr - Swiss Franc // - kr - Swedish krona, Norwegian krone and Danish krone // - \u2009 is thin space and \u202F is narrow no-break space, both used in many // standards as thousands separators. var _re_formatted_numeric = /[',$£€¥%\u2009\u202F\u20BD\u20a9\u20BArfk]/gi; var _empty = function ( d ) { return !d || d === true || d === '-' ? true : false; }; var _intVal = function ( s ) { var integer = parseInt( s, 10 ); return !isNaN(integer) && isFinite(s) ? integer : null; }; // Convert from a formatted number with characters other than `.` as the // decimal place, to a Javascript number var _numToDecimal = function ( num, decimalPoint ) { // Cache created regular expressions for speed as this function is called often if ( ! _re_dic[ decimalPoint ] ) { _re_dic[ decimalPoint ] = new RegExp( _fnEscapeRegex( decimalPoint ), 'g' ); } return typeof num === 'string' && decimalPoint !== '.' ? num.replace( /\./g, '' ).replace( _re_dic[ decimalPoint ], '.' ) : num; }; var _isNumber = function ( d, decimalPoint, formatted ) { var strType = typeof d === 'string'; // If empty return immediately so there must be a number if it is a // formatted string (this stops the string "k", or "kr", etc being detected // as a formatted number for currency if ( _empty( d ) ) { return true; } if ( decimalPoint && strType ) { d = _numToDecimal( d, decimalPoint ); } if ( formatted && strType ) { d = d.replace( _re_formatted_numeric, '' ); } return !isNaN( parseFloat(d) ) && isFinite( d ); }; // A string without HTML in it can be considered to be HTML still var _isHtml = function ( d ) { return _empty( d ) || typeof d === 'string'; }; var _htmlNumeric = function ( d, decimalPoint, formatted ) { if ( _empty( d ) ) { return true; } var html = _isHtml( d ); return ! html ? null : _isNumber( _stripHtml( d ), decimalPoint, formatted ) ? true : null; }; var _pluck = function ( a, prop, prop2 ) { var out = []; var i=0, ien=a.length; // Could have the test in the loop for slightly smaller code, but speed // is essential here if ( prop2 !== undefined ) { for ( ; i<ien ; i++ ) { if ( a[i] && a[i][ prop ] ) { out.push( a[i][ prop ][ prop2 ] ); } } } else { for ( ; i<ien ; i++ ) { if ( a[i] ) { out.push( a[i][ prop ] ); } } } return out; }; // Basically the same as _pluck, but rather than looping over `a` we use `order` // as the indexes to pick from `a` var _pluck_order = function ( a, order, prop, prop2 ) { var out = []; var i=0, ien=order.length; // Could have the test in the loop for slightly smaller code, but speed // is essential here if ( prop2 !== undefined ) { for ( ; i<ien ; i++ ) { if ( a[ order[i] ][ prop ] ) { out.push( a[ order[i] ][ prop ][ prop2 ] ); } } } else { for ( ; i<ien ; i++ ) { out.push( a[ order[i] ][ prop ] ); } } return out; }; var _range = function ( len, start ) { var out = []; var end; if ( start === undefined ) { start = 0; end = len; } else { end = start; start = len; } for ( var i=start ; i<end ; i++ ) { out.push( i ); } return out; }; var _removeEmpty = function ( a ) { var out = []; for ( var i=0, ien=a.length ; i<ien ; i++ ) { if ( a[i] ) { // careful - will remove all falsy values! out.push( a[i] ); } } return out; }; var _stripHtml = function ( d ) { return d.replace( _re_html, '' ); }; /** * Determine if all values in the array are unique. This means we can short * cut the _unique method at the cost of a single loop. A sorted array is used * to easily check the values. * * @param {array} src Source array * @return {boolean} true if all unique, false otherwise * @ignore */ var _areAllUnique = function ( src ) { if ( src.length < 2 ) { return true; } var sorted = src.slice().sort(); var last = sorted[0]; for ( var i=1, ien=sorted.length ; i<ien ; i++ ) { if ( sorted[i] === last ) { return false; } last = sorted[i]; } return true; }; /** * Find the unique elements in a source array. * * @param {array} src Source array * @return {array} Array of unique items * @ignore */ var _unique = function ( src ) { if ( _areAllUnique( src ) ) { return src.slice(); } // A faster unique method is to use object keys to identify used values, // but this doesn't work with arrays or objects, which we must also // consider. See jsperf.com/compare-array-unique-versions/4 for more // information. var out = [], val, i, ien=src.length, j, k=0; again: for ( i=0 ; i<ien ; i++ ) { val = src[i]; for ( j=0 ; j<k ; j++ ) { if ( out[j] === val ) { continue again; } } out.push( val ); k++; } return out; }; /** * DataTables utility methods * * This namespace provides helper methods that DataTables uses internally to * create a DataTable, but which are not exclusively used only for DataTables. * These methods can be used by extension authors to save the duplication of * code. * * @namespace */ DataTable.util = { /** * Throttle the calls to a function. Arguments and context are maintained * for the throttled function. * * @param {function} fn Function to be called * @param {integer} freq Call frequency in mS * @return {function} Wrapped function */ throttle: function ( fn, freq ) { var frequency = freq !== undefined ? freq : 200, last, timer; return function () { var that = this, now = +new Date(), args = arguments; if ( last && now < last + frequency ) { clearTimeout( timer ); timer = setTimeout( function () { last = undefined; fn.apply( that, args ); }, frequency ); } else { last = now; fn.apply( that, args ); } }; }, /** * Escape a string such that it can be used in a regular expression * * @param {string} val string to escape * @returns {string} escaped string */ escapeRegex: function ( val ) { return val.replace( _re_escape_regex, '\\$1' ); } }; /** * Create a mapping object that allows camel case parameters to be looked up * for their Hungarian counterparts. The mapping is stored in a private * parameter called `_hungarianMap` which can be accessed on the source object. * @param {object} o * @memberof DataTable#oApi */ function _fnHungarianMap ( o ) { var hungarian = 'a aa ai ao as b fn i m o s ', match, newKey, map = {}; $.each( o, function (key, val) { match = key.match(/^([^A-Z]+?)([A-Z])/); if ( match && hungarian.indexOf(match[1]+' ') !== -1 ) { newKey = key.replace( match[0], match[2].toLowerCase() ); map[ newKey ] = key; if ( match[1] === 'o' ) { _fnHungarianMap( o[key] ); } } } ); o._hungarianMap = map; } /** * Convert from camel case parameters to Hungarian, based on a Hungarian map * created by _fnHungarianMap. * @param {object} src The model object which holds all parameters that can be * mapped. * @param {object} user The object to convert from camel case to Hungarian. * @param {boolean} force When set to `true`, properties which already have a * Hungarian value in the `user` object will be overwritten. Otherwise they * won't be. * @memberof DataTable#oApi */ function _fnCamelToHungarian ( src, user, force ) { if ( ! src._hungarianMap ) { _fnHungarianMap( src ); } var hungarianKey; $.each( user, function (key, val) { hungarianKey = src._hungarianMap[ key ]; if ( hungarianKey !== undefined && (force || user[hungarianKey] === undefined) ) { // For objects, we need to buzz down into the object to copy parameters if ( hungarianKey.charAt(0) === 'o' ) { // Copy the camelCase options over to the hungarian if ( ! user[ hungarianKey ] ) { user[ hungarianKey ] = {}; } $.extend( true, user[hungarianKey], user[key] ); _fnCamelToHungarian( src[hungarianKey], user[hungarianKey], force ); } else { user[hungarianKey] = user[ key ]; } } } ); } /** * Language compatibility - when certain options are given, and others aren't, we * need to duplicate the values over, in order to provide backwards compatibility * with older language files. * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnLanguageCompat( lang ) { var defaults = DataTable.defaults.oLanguage; var zeroRecords = lang.sZeroRecords; /* Backwards compatibility - if there is no sEmptyTable given, then use the same as * sZeroRecords - assuming that is given. */ if ( ! lang.sEmptyTable && zeroRecords && defaults.sEmptyTable === "No data available in table" ) { _fnMap( lang, lang, 'sZeroRecords', 'sEmptyTable' ); } /* Likewise with loading records */ if ( ! lang.sLoadingRecords && zeroRecords && defaults.sLoadingRecords === "Loading..." ) { _fnMap( lang, lang, 'sZeroRecords', 'sLoadingRecords' ); } // Old parameter name of the thousands separator mapped onto the new if ( lang.sInfoThousands ) { lang.sThousands = lang.sInfoThousands; } var decimal = lang.sDecimal; if ( decimal ) { _addNumericSort( decimal ); } } /** * Map one parameter onto another * @param {object} o Object to map * @param {*} knew The new parameter name * @param {*} old The old parameter name */ var _fnCompatMap = function ( o, knew, old ) { if ( o[ knew ] !== undefined ) { o[ old ] = o[ knew ]; } }; /** * Provide backwards compatibility for the main DT options. Note that the new * options are mapped onto the old parameters, so this is an external interface * change only. * @param {object} init Object to map */ function _fnCompatOpts ( init ) { _fnCompatMap( init, 'ordering', 'bSort' ); _fnCompatMap( init, 'orderMulti', 'bSortMulti' ); _fnCompatMap( init, 'orderClasses', 'bSortClasses' ); _fnCompatMap( init, 'orderCellsTop', 'bSortCellsTop' ); _fnCompatMap( init, 'order', 'aaSorting' ); _fnCompatMap( init, 'orderFixed', 'aaSortingFixed' ); _fnCompatMap( init, 'paging', 'bPaginate' ); _fnCompatMap( init, 'pagingType', 'sPaginationType' ); _fnCompatMap( init, 'pageLength', 'iDisplayLength' ); _fnCompatMap( init, 'searching', 'bFilter' ); // Boolean initialisation of x-scrolling if ( typeof init.sScrollX === 'boolean' ) { init.sScrollX = init.sScrollX ? '100%' : ''; } if ( typeof init.scrollX === 'boolean' ) { init.scrollX = init.scrollX ? '100%' : ''; } // Column search objects are in an array, so it needs to be converted // element by element var searchCols = init.aoSearchCols; if ( searchCols ) { for ( var i=0, ien=searchCols.length ; i<ien ; i++ ) { if ( searchCols[i] ) { _fnCamelToHungarian( DataTable.models.oSearch, searchCols[i] ); } } } } /** * Provide backwards compatibility for column options. Note that the new options * are mapped onto the old parameters, so this is an external interface change * only. * @param {object} init Object to map */ function _fnCompatCols ( init ) { _fnCompatMap( init, 'orderable', 'bSortable' ); _fnCompatMap( init, 'orderData', 'aDataSort' ); _fnCompatMap( init, 'orderSequence', 'asSorting' ); _fnCompatMap( init, 'orderDataType', 'sortDataType' ); // orderData can be given as an integer var dataSort = init.aDataSort; if ( typeof dataSort === 'number' && ! $.isArray( dataSort ) ) { init.aDataSort = [ dataSort ]; } } /** * Browser feature detection for capabilities, quirks * @param {object} settings dataTables settings object * @memberof DataTable#oApi */ function _fnBrowserDetect( settings ) { // We don't need to do this every time DataTables is constructed, the values // calculated are specific to the browser and OS configuration which we // don't expect to change between initialisations if ( ! DataTable.__browser ) { var browser = {}; DataTable.__browser = browser; // Scrolling feature / quirks detection var n = $('<div/>') .css( { position: 'fixed', top: 0, left: $(window).scrollLeft()*-1, // allow for scrolling height: 1, width: 1, overflow: 'hidden' } ) .append( $('<div/>') .css( { position: 'absolute', top: 1, left: 1, width: 100, overflow: 'scroll' } ) .append( $('<div/>') .css( { width: '100%', height: 10 } ) ) ) .appendTo( 'body' ); var outer = n.children(); var inner = outer.children(); // Numbers below, in order, are: // inner.offsetWidth, inner.clientWidth, outer.offsetWidth, outer.clientWidth // // IE6 XP: 100 100 100 83 // IE7 Vista: 100 100 100 83 // IE 8+ Windows: 83 83 100 83 // Evergreen Windows: 83 83 100 83 // Evergreen Mac with scrollbars: 85 85 100 85 // Evergreen Mac without scrollbars: 100 100 100 100 // Get scrollbar width browser.barWidth = outer[0].offsetWidth - outer[0].clientWidth; // IE6/7 will oversize a width 100% element inside a scrolling element, to // include the width of the scrollbar, while other browsers ensure the inner // element is contained without forcing scrolling browser.bScrollOversize = inner[0].offsetWidth === 100 && outer[0].clientWidth !== 100; // In rtl text layout, some browsers (most, but not all) will place the // scrollbar on the left, rather than the right. browser.bScrollbarLeft = Math.round( inner.offset().left ) !== 1; // IE8- don't provide height and width for getBoundingClientRect browser.bBounding = n[0].getBoundingClientRect().width ? true : false; n.remove(); } $.extend( settings.oBrowser, DataTable.__browser ); settings.oScroll.iBarWidth = DataTable.__browser.barWidth; } /** * Array.prototype reduce[Right] method, used for browsers which don't support * JS 1.6. Done this way to reduce code size, since we iterate either way * @param {object} settings dataTables settings object * @memberof DataTable#oApi */ function _fnReduce ( that, fn, init, start, end, inc ) { var i = start, value, isSet = false; if ( init !== undefined ) { value = init; isSet = true; } while ( i !== end ) { if ( ! that.hasOwnProperty(i) ) { continue; } value = isSet ? fn( value, that[i], i, that ) : that[i]; isSet = true; i += inc; } return value; } /** * Add a column to the list used for the table with default values * @param {object} oSettings dataTables settings object * @param {node} nTh The th element for this column * @memberof DataTable#oApi */ function _fnAddColumn( oSettings, nTh ) { // Add column to aoColumns array var oDefaults = DataTable.defaults.column; var iCol = oSettings.aoColumns.length; var oCol = $.extend( {}, DataTable.models.oColumn, oDefaults, { "nTh": nTh ? nTh : document.createElement('th'), "sTitle": oDefaults.sTitle ? oDefaults.sTitle : nTh ? nTh.innerHTML : '', "aDataSort": oDefaults.aDataSort ? oDefaults.aDataSort : [iCol], "mData": oDefaults.mData ? oDefaults.mData : iCol, idx: iCol } ); oSettings.aoColumns.push( oCol ); // Add search object for column specific search. Note that the `searchCols[ iCol ]` // passed into extend can be undefined. This allows the user to give a default // with only some of the parameters defined, and also not give a default var searchCols = oSettings.aoPreSearchCols; searchCols[ iCol ] = $.extend( {}, DataTable.models.oSearch, searchCols[ iCol ] ); // Use the default column options function to initialise classes etc _fnColumnOptions( oSettings, iCol, $(nTh).data() ); } /** * Apply options for a column * @param {object} oSettings dataTables settings object * @param {int} iCol column index to consider * @param {object} oOptions object with sType, bVisible and bSearchable etc * @memberof DataTable#oApi */ function _fnColumnOptions( oSettings, iCol, oOptions ) { var oCol = oSettings.aoColumns[ iCol ]; var oClasses = oSettings.oClasses; var th = $(oCol.nTh); // Try to get width information from the DOM. We can't get it from CSS // as we'd need to parse the CSS stylesheet. `width` option can override if ( ! oCol.sWidthOrig ) { // Width attribute oCol.sWidthOrig = th.attr('width') || null; // Style attribute var t = (th.attr('style') || '').match(/width:\s*(\d+[pxem%]+)/); if ( t ) { oCol.sWidthOrig = t[1]; } } /* User specified column options */ if ( oOptions !== undefined && oOptions !== null ) { // Backwards compatibility _fnCompatCols( oOptions ); // Map camel case parameters to their Hungarian counterparts _fnCamelToHungarian( DataTable.defaults.column, oOptions ); /* Backwards compatibility for mDataProp */ if ( oOptions.mDataProp !== undefined && !oOptions.mData ) { oOptions.mData = oOptions.mDataProp; } if ( oOptions.sType ) { oCol._sManualType = oOptions.sType; } // `class` is a reserved word in Javascript, so we need to provide // the ability to use a valid name for the camel case input if ( oOptions.className && ! oOptions.sClass ) { oOptions.sClass = oOptions.className; } if ( oOptions.sClass ) { th.addClass( oOptions.sClass ); } $.extend( oCol, oOptions ); _fnMap( oCol, oOptions, "sWidth", "sWidthOrig" ); /* iDataSort to be applied (backwards compatibility), but aDataSort will take * priority if defined */ if ( oOptions.iDataSort !== undefined ) { oCol.aDataSort = [ oOptions.iDataSort ]; } _fnMap( oCol, oOptions, "aDataSort" ); } /* Cache the data get and set functions for speed */ var mDataSrc = oCol.mData; var mData = _fnGetObjectDataFn( mDataSrc ); var mRender = oCol.mRender ? _fnGetObjectDataFn( oCol.mRender ) : null; var attrTest = function( src ) { return typeof src === 'string' && src.indexOf('@') !== -1; }; oCol._bAttrSrc = $.isPlainObject( mDataSrc ) && ( attrTest(mDataSrc.sort) || attrTest(mDataSrc.type) || attrTest(mDataSrc.filter) ); oCol._setter = null; oCol.fnGetData = function (rowData, type, meta) { var innerData = mData( rowData, type, undefined, meta ); return mRender && type ? mRender( innerData, type, rowData, meta ) : innerData; }; oCol.fnSetData = function ( rowData, val, meta ) { return _fnSetObjectDataFn( mDataSrc )( rowData, val, meta ); }; // Indicate if DataTables should read DOM data as an object or array // Used in _fnGetRowElements if ( typeof mDataSrc !== 'number' ) { oSettings._rowReadObject = true; } /* Feature sorting overrides column specific when off */ if ( !oSettings.oFeatures.bSort ) { oCol.bSortable = false; th.addClass( oClasses.sSortableNone ); // Have to add class here as order event isn't called } /* Check that the class assignment is correct for sorting */ var bAsc = $.inArray('asc', oCol.asSorting) !== -1; var bDesc = $.inArray('desc', oCol.asSorting) !== -1; if ( !oCol.bSortable || (!bAsc && !bDesc) ) { oCol.sSortingClass = oClasses.sSortableNone; oCol.sSortingClassJUI = ""; } else if ( bAsc && !bDesc ) { oCol.sSortingClass = oClasses.sSortableAsc; oCol.sSortingClassJUI = oClasses.sSortJUIAscAllowed; } else if ( !bAsc && bDesc ) { oCol.sSortingClass = oClasses.sSortableDesc; oCol.sSortingClassJUI = oClasses.sSortJUIDescAllowed; } else { oCol.sSortingClass = oClasses.sSortable; oCol.sSortingClassJUI = oClasses.sSortJUI; } } /** * Adjust the table column widths for new data. Note: you would probably want to * do a redraw after calling this function! * @param {object} settings dataTables settings object * @memberof DataTable#oApi */ function _fnAdjustColumnSizing ( settings ) { /* Not interested in doing column width calculation if auto-width is disabled */ if ( settings.oFeatures.bAutoWidth !== false ) { var columns = settings.aoColumns; _fnCalculateColumnWidths( settings ); for ( var i=0 , iLen=columns.length ; i<iLen ; i++ ) { columns[i].nTh.style.width = columns[i].sWidth; } } var scroll = settings.oScroll; if ( scroll.sY !== '' || scroll.sX !== '') { _fnScrollDraw( settings ); } _fnCallbackFire( settings, null, 'column-sizing', [settings] ); } /** * Covert the index of a visible column to the index in the data array (take account * of hidden columns) * @param {object} oSettings dataTables settings object * @param {int} iMatch Visible column index to lookup * @returns {int} i the data index * @memberof DataTable#oApi */ function _fnVisibleToColumnIndex( oSettings, iMatch ) { var aiVis = _fnGetColumns( oSettings, 'bVisible' ); return typeof aiVis[iMatch] === 'number' ? aiVis[iMatch] : null; } /** * Covert the index of an index in the data array and convert it to the visible * column index (take account of hidden columns) * @param {int} iMatch Column index to lookup * @param {object} oSettings dataTables settings object * @returns {int} i the data index * @memberof DataTable#oApi */ function _fnColumnIndexToVisible( oSettings, iMatch ) { var aiVis = _fnGetColumns( oSettings, 'bVisible' ); var iPos = $.inArray( iMatch, aiVis ); return iPos !== -1 ? iPos : null; } /** * Get the number of visible columns * @param {object} oSettings dataTables settings object * @returns {int} i the number of visible columns * @memberof DataTable#oApi */ function _fnVisbleColumns( oSettings ) { var vis = 0; // No reduce in IE8, use a loop for now $.each( oSettings.aoColumns, function ( i, col ) { if ( col.bVisible && $(col.nTh).css('display') !== 'none' ) { vis++; } } ); return vis; } /** * Get an array of column indexes that match a given property * @param {object} oSettings dataTables settings object * @param {string} sParam Parameter in aoColumns to look for - typically * bVisible or bSearchable * @returns {array} Array of indexes with matched properties * @memberof DataTable#oApi */ function _fnGetColumns( oSettings, sParam ) { var a = []; $.map( oSettings.aoColumns, function(val, i) { if ( val[sParam] ) { a.push( i ); } } ); return a; } /** * Calculate the 'type' of a column * @param {object} settings dataTables settings object * @memberof DataTable#oApi */ function _fnColumnTypes ( settings ) { var columns = settings.aoColumns; var data = settings.aoData; var types = DataTable.ext.type.detect; var i, ien, j, jen, k, ken; var col, cell, detectedType, cache; // For each column, spin over the for ( i=0, ien=columns.length ; i<ien ; i++ ) { col = columns[i]; cache = []; if ( ! col.sType && col._sManualType ) { col.sType = col._sManualType; } else if ( ! col.sType ) { for ( j=0, jen=types.length ; j<jen ; j++ ) { for ( k=0, ken=data.length ; k<ken ; k++ ) { // Use a cache array so we only need to get the type data // from the formatter once (when using multiple detectors) if ( cache[k] === undefined ) { cache[k] = _fnGetCellData( settings, k, i, 'type' ); } detectedType = types[j]( cache[k], settings ); // If null, then this type can't apply to this column, so // rather than testing all cells, break out. There is an // exception for the last type which is `html`. We need to // scan all rows since it is possible to mix string and HTML // types if ( ! detectedType && j !== types.length-1 ) { break; } // Only a single match is needed for html type since it is // bottom of the pile and very similar to string if ( detectedType === 'html' ) { break; } } // Type is valid for all data points in the column - use this // type if ( detectedType ) { col.sType = detectedType; break; } } // Fall back - if no type was detected, always use string if ( ! col.sType ) { col.sType = 'string'; } } } } /** * Take the column definitions and static columns arrays and calculate how * they relate to column indexes. The callback function will then apply the * definition found for a column to a suitable configuration object. * @param {object} oSettings dataTables settings object * @param {array} aoColDefs The aoColumnDefs array that is to be applied * @param {array} aoCols The aoColumns array that defines columns individually * @param {function} fn Callback function - takes two parameters, the calculated * column index and the definition for that column. * @memberof DataTable#oApi */ function _fnApplyColumnDefs( oSettings, aoColDefs, aoCols, fn ) { var i, iLen, j, jLen, k, kLen, def; var columns = oSettings.aoColumns; // Column definitions with aTargets if ( aoColDefs ) { /* Loop over the definitions array - loop in reverse so first instance has priority */ for ( i=aoColDefs.length-1 ; i>=0 ; i-- ) { def = aoColDefs[i]; /* Each definition can target multiple columns, as it is an array */ var aTargets = def.targets !== undefined ? def.targets : def.aTargets; if ( ! $.isArray( aTargets ) ) { aTargets = [ aTargets ]; } for ( j=0, jLen=aTargets.length ; j<jLen ; j++ ) { if ( typeof aTargets[j] === 'number' && aTargets[j] >= 0 ) { /* Add columns that we don't yet know about */ while( columns.length <= aTargets[j] ) { _fnAddColumn( oSettings ); } /* Integer, basic index */ fn( aTargets[j], def ); } else if ( typeof aTargets[j] === 'number' && aTargets[j] < 0 ) { /* Negative integer, right to left column counting */ fn( columns.length+aTargets[j], def ); } else if ( typeof aTargets[j] === 'string' ) { /* Class name matching on TH element */ for ( k=0, kLen=columns.length ; k<kLen ; k++ ) { if ( aTargets[j] == "_all" || $(columns[k].nTh).hasClass( aTargets[j] ) ) { fn( k, def ); } } } } } } // Statically defined columns array if ( aoCols ) { for ( i=0, iLen=aoCols.length ; i<iLen ; i++ ) { fn( i, aoCols[i] ); } } } /** * Add a data array to the table, creating DOM node etc. This is the parallel to * _fnGatherData, but for adding rows from a Javascript source, rather than a * DOM source. * @param {object} oSettings dataTables settings object * @param {array} aData data array to be added * @param {node} [nTr] TR element to add to the table - optional. If not given, * DataTables will create a row automatically * @param {array} [anTds] Array of TD|TH elements for the row - must be given * if nTr is. * @returns {int} >=0 if successful (index of new aoData entry), -1 if failed * @memberof DataTable#oApi */ function _fnAddData ( oSettings, aDataIn, nTr, anTds ) { /* Create the object for storing information about this new row */ var iRow = oSettings.aoData.length; var oData = $.extend( true, {}, DataTable.models.oRow, { src: nTr ? 'dom' : 'data', idx: iRow } ); oData._aData = aDataIn; oSettings.aoData.push( oData ); /* Create the cells */ var nTd, sThisType; var columns = oSettings.aoColumns; // Invalidate the column types as the new data needs to be revalidated for ( var i=0, iLen=columns.length ; i<iLen ; i++ ) { columns[i].sType = null; } /* Add to the display array */ oSettings.aiDisplayMaster.push( iRow ); var id = oSettings.rowIdFn( aDataIn ); if ( id !== undefined ) { oSettings.aIds[ id ] = oData; } /* Create the DOM information, or register it if already present */ if ( nTr || ! oSettings.oFeatures.bDeferRender ) { _fnCreateTr( oSettings, iRow, nTr, anTds ); } return iRow; } /** * Add one or more TR elements to the table. Generally we'd expect to * use this for reading data from a DOM sourced table, but it could be * used for an TR element. Note that if a TR is given, it is used (i.e. * it is not cloned). * @param {object} settings dataTables settings object * @param {array|node|jQuery} trs The TR element(s) to add to the table * @returns {array} Array of indexes for the added rows * @memberof DataTable#oApi */ function _fnAddTr( settings, trs ) { var row; // Allow an individual node to be passed in if ( ! (trs instanceof $) ) { trs = $(trs); } return trs.map( function (i, el) { row = _fnGetRowElements( settings, el ); return _fnAddData( settings, row.data, el, row.cells ); } ); } /** * Take a TR element and convert it to an index in aoData * @param {object} oSettings dataTables settings object * @param {node} n the TR element to find * @returns {int} index if the node is found, null if not * @memberof DataTable#oApi */ function _fnNodeToDataIndex( oSettings, n ) { return (n._DT_RowIndex!==undefined) ? n._DT_RowIndex : null; } /** * Take a TD element and convert it into a column data index (not the visible index) * @param {object} oSettings dataTables settings object * @param {int} iRow The row number the TD/TH can be found in * @param {node} n The TD/TH element to find * @returns {int} index if the node is found, -1 if not * @memberof DataTable#oApi */ function _fnNodeToColumnIndex( oSettings, iRow, n ) { return $.inArray( n, oSettings.aoData[ iRow ].anCells ); } /** * Get the data for a given cell from the internal cache, taking into account data mapping * @param {object} settings dataTables settings object * @param {int} rowIdx aoData row id * @param {int} colIdx Column index * @param {string} type data get type ('display', 'type' 'filter' 'sort') * @returns {*} Cell data * @memberof DataTable#oApi */ function _fnGetCellData( settings, rowIdx, colIdx, type ) { var draw = settings.iDraw; var col = settings.aoColumns[colIdx]; var rowData = settings.aoData[rowIdx]._aData; var defaultContent = col.sDefaultContent; var cellData = col.fnGetData( rowData, type, { settings: settings, row: rowIdx, col: colIdx } ); if ( cellData === undefined ) { if ( settings.iDrawError != draw && defaultContent === null ) { _fnLog( settings, 0, "Requested unknown parameter "+ (typeof col.mData=='function' ? '{function}' : "'"+col.mData+"'")+ " for row "+rowIdx+", column "+colIdx, 4 ); settings.iDrawError = draw; } return defaultContent; } // When the data source is null and a specific data type is requested (i.e. // not the original data), we can use default column data if ( (cellData === rowData || cellData === null) && defaultContent !== null && type !== undefined ) { cellData = defaultContent; } else if ( typeof cellData === 'function' ) { // If the data source is a function, then we run it and use the return, // executing in the scope of the data object (for instances) return cellData.call( rowData ); } if ( cellData === null && type == 'display' ) { return ''; } return cellData; } /** * Set the value for a specific cell, into the internal data cache * @param {object} settings dataTables settings object * @param {int} rowIdx aoData row id * @param {int} colIdx Column index * @param {*} val Value to set * @memberof DataTable#oApi */ function _fnSetCellData( settings, rowIdx, colIdx, val ) { var col = settings.aoColumns[colIdx]; var rowData = settings.aoData[rowIdx]._aData; col.fnSetData( rowData, val, { settings: settings, row: rowIdx, col: colIdx } ); } // Private variable that is used to match action syntax in the data property object var __reArray = /\[.*?\]$/; var __reFn = /\(\)$/; /** * Split string on periods, taking into account escaped periods * @param {string} str String to split * @return {array} Split string */ function _fnSplitObjNotation( str ) { return $.map( str.match(/(\\.|[^\.])+/g) || [''], function ( s ) { return s.replace(/\\\./g, '.'); } ); } /** * Return a function that can be used to get data from a source object, taking * into account the ability to use nested objects as a source * @param {string|int|function} mSource The data source for the object * @returns {function} Data get function * @memberof DataTable#oApi */ function _fnGetObjectDataFn( mSource ) { if ( $.isPlainObject( mSource ) ) { /* Build an object of get functions, and wrap them in a single call */ var o = {}; $.each( mSource, function (key, val) { if ( val ) { o[key] = _fnGetObjectDataFn( val ); } } ); return function (data, type, row, meta) { var t = o[type] || o._; return t !== undefined ? t(data, type, row, meta) : data; }; } else if ( mSource === null ) { /* Give an empty string for rendering / sorting etc */ return function (data) { // type, row and meta also passed, but not used return data; }; } else if ( typeof mSource === 'function' ) { return function (data, type, row, meta) { return mSource( data, type, row, meta ); }; } else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 || mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) ) { /* If there is a . in the source string then the data source is in a * nested object so we loop over the data for each level to get the next * level down. On each loop we test for undefined, and if found immediately * return. This allows entire objects to be missing and sDefaultContent to * be used if defined, rather than throwing an error */ var fetchData = function (data, type, src) { var arrayNotation, funcNotation, out, innerSrc; if ( src !== "" ) { var a = _fnSplitObjNotation( src ); for ( var i=0, iLen=a.length ; i<iLen ; i++ ) { // Check if we are dealing with special notation arrayNotation = a[i].match(__reArray); funcNotation = a[i].match(__reFn); if ( arrayNotation ) { // Array notation a[i] = a[i].replace(__reArray, ''); // Condition allows simply [] to be passed in if ( a[i] !== "" ) { data = data[ a[i] ]; } out = []; // Get the remainder of the nested object to get a.splice( 0, i+1 ); innerSrc = a.join('.'); // Traverse each entry in the array getting the properties requested if ( $.isArray( data ) ) { for ( var j=0, jLen=data.length ; j<jLen ; j++ ) { out.push( fetchData( data[j], type, innerSrc ) ); } } // If a string is given in between the array notation indicators, that // is used to join the strings together, otherwise an array is returned var join = arrayNotation[0].substring(1, arrayNotation[0].length-1); data = (join==="") ? out : out.join(join); // The inner call to fetchData has already traversed through the remainder // of the source requested, so we exit from the loop break; } else if ( funcNotation ) { // Function call a[i] = a[i].replace(__reFn, ''); data = data[ a[i] ](); continue; } if ( data === null || data[ a[i] ] === undefined ) { return undefined; } data = data[ a[i] ]; } } return data; }; return function (data, type) { // row and meta also passed, but not used return fetchData( data, type, mSource ); }; } else { /* Array or flat object mapping */ return function (data, type) { // row and meta also passed, but not used return data[mSource]; }; } } /** * Return a function that can be used to set data from a source object, taking * into account the ability to use nested objects as a source * @param {string|int|function} mSource The data source for the object * @returns {function} Data set function * @memberof DataTable#oApi */ function _fnSetObjectDataFn( mSource ) { if ( $.isPlainObject( mSource ) ) { /* Unlike get, only the underscore (global) option is used for for * setting data since we don't know the type here. This is why an object * option is not documented for `mData` (which is read/write), but it is * for `mRender` which is read only. */ return _fnSetObjectDataFn( mSource._ ); } else if ( mSource === null ) { /* Nothing to do when the data source is null */ return function () {}; } else if ( typeof mSource === 'function' ) { return function (data, val, meta) { mSource( data, 'set', val, meta ); }; } else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 || mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) ) { /* Like the get, we need to get data from a nested object */ var setData = function (data, val, src) { var a = _fnSplitObjNotation( src ), b; var aLast = a[a.length-1]; var arrayNotation, funcNotation, o, innerSrc; for ( var i=0, iLen=a.length-1 ; i<iLen ; i++ ) { // Check if we are dealing with an array notation request arrayNotation = a[i].match(__reArray); funcNotation = a[i].match(__reFn); if ( arrayNotation ) { a[i] = a[i].replace(__reArray, ''); data[ a[i] ] = []; // Get the remainder of the nested object to set so we can recurse b = a.slice(); b.splice( 0, i+1 ); innerSrc = b.join('.'); // Traverse each entry in the array setting the properties requested if ( $.isArray( val ) ) { for ( var j=0, jLen=val.length ; j<jLen ; j++ ) { o = {}; setData( o, val[j], innerSrc ); data[ a[i] ].push( o ); } } else { // We've been asked to save data to an array, but it // isn't array data to be saved. Best that can be done // is to just save the value. data[ a[i] ] = val; } // The inner call to setData has already traversed through the remainder // of the source and has set the data, thus we can exit here return; } else if ( funcNotation ) { // Function call a[i] = a[i].replace(__reFn, ''); data = data[ a[i] ]( val ); } // If the nested object doesn't currently exist - since we are // trying to set the value - create it if ( data[ a[i] ] === null || data[ a[i] ] === undefined ) { data[ a[i] ] = {}; } data = data[ a[i] ]; } // Last item in the input - i.e, the actual set if ( aLast.match(__reFn ) ) { // Function call data = data[ aLast.replace(__reFn, '') ]( val ); } else { // If array notation is used, we just want to strip it and use the property name // and assign the value. If it isn't used, then we get the result we want anyway data[ aLast.replace(__reArray, '') ] = val; } }; return function (data, val) { // meta is also passed in, but not used return setData( data, val, mSource ); }; } else { /* Array or flat object mapping */ return function (data, val) { // meta is also passed in, but not used data[mSource] = val; }; } } /** * Return an array with the full table data * @param {object} oSettings dataTables settings object * @returns array {array} aData Master data array * @memberof DataTable#oApi */ function _fnGetDataMaster ( settings ) { return _pluck( settings.aoData, '_aData' ); } /** * Nuke the table * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnClearTable( settings ) { settings.aoData.length = 0; settings.aiDisplayMaster.length = 0; settings.aiDisplay.length = 0; settings.aIds = {}; } /** * Take an array of integers (index array) and remove a target integer (value - not * the key!) * @param {array} a Index array to target * @param {int} iTarget value to find * @memberof DataTable#oApi */ function _fnDeleteIndex( a, iTarget, splice ) { var iTargetIndex = -1; for ( var i=0, iLen=a.length ; i<iLen ; i++ ) { if ( a[i] == iTarget ) { iTargetIndex = i; } else if ( a[i] > iTarget ) { a[i]--; } } if ( iTargetIndex != -1 && splice === undefined ) { a.splice( iTargetIndex, 1 ); } } /** * Mark cached data as invalid such that a re-read of the data will occur when * the cached data is next requested. Also update from the data source object. * * @param {object} settings DataTables settings object * @param {int} rowIdx Row index to invalidate * @param {string} [src] Source to invalidate from: undefined, 'auto', 'dom' * or 'data' * @param {int} [colIdx] Column index to invalidate. If undefined the whole * row will be invalidated * @memberof DataTable#oApi * * @todo For the modularisation of v1.11 this will need to become a callback, so * the sort and filter methods can subscribe to it. That will required * initialisation options for sorting, which is why it is not already baked in */ function _fnInvalidate( settings, rowIdx, src, colIdx ) { var row = settings.aoData[ rowIdx ]; var i, ien; var cellWrite = function ( cell, col ) { // This is very frustrating, but in IE if you just write directly // to innerHTML, and elements that are overwritten are GC'ed, // even if there is a reference to them elsewhere while ( cell.childNodes.length ) { cell.removeChild( cell.firstChild ); } cell.innerHTML = _fnGetCellData( settings, rowIdx, col, 'display' ); }; // Are we reading last data from DOM or the data object? if ( src === 'dom' || ((! src || src === 'auto') && row.src === 'dom') ) { // Read the data from the DOM row._aData = _fnGetRowElements( settings, row, colIdx, colIdx === undefined ? undefined : row._aData ) .data; } else { // Reading from data object, update the DOM var cells = row.anCells; if ( cells ) { if ( colIdx !== undefined ) { cellWrite( cells[colIdx], colIdx ); } else { for ( i=0, ien=cells.length ; i<ien ; i++ ) { cellWrite( cells[i], i ); } } } } // For both row and cell invalidation, the cached data for sorting and // filtering is nulled out row._aSortData = null; row._aFilterData = null; // Invalidate the type for a specific column (if given) or all columns since // the data might have changed var cols = settings.aoColumns; if ( colIdx !== undefined ) { cols[ colIdx ].sType = null; } else { for ( i=0, ien=cols.length ; i<ien ; i++ ) { cols[i].sType = null; } // Update DataTables special `DT_*` attributes for the row _fnRowAttributes( settings, row ); } } /** * Build a data source object from an HTML row, reading the contents of the * cells that are in the row. * * @param {object} settings DataTables settings object * @param {node|object} TR element from which to read data or existing row * object from which to re-read the data from the cells * @param {int} [colIdx] Optional column index * @param {array|object} [d] Data source object. If `colIdx` is given then this * parameter should also be given and will be used to write the data into. * Only the column in question will be written * @returns {object} Object with two parameters: `data` the data read, in * document order, and `cells` and array of nodes (they can be useful to the * caller, so rather than needing a second traversal to get them, just return * them from here). * @memberof DataTable#oApi */ function _fnGetRowElements( settings, row, colIdx, d ) { var tds = [], td = row.firstChild, name, col, o, i=0, contents, columns = settings.aoColumns, objectRead = settings._rowReadObject; // Allow the data object to be passed in, or construct d = d !== undefined ? d : objectRead ? {} : []; var attr = function ( str, td ) { if ( typeof str === 'string' ) { var idx = str.indexOf('@'); if ( idx !== -1 ) { var attr = str.substring( idx+1 ); var setter = _fnSetObjectDataFn( str ); setter( d, td.getAttribute( attr ) ); } } }; // Read data from a cell and store into the data object var cellProcess = function ( cell ) { if ( colIdx === undefined || colIdx === i ) { col = columns[i]; contents = $.trim(cell.innerHTML); if ( col && col._bAttrSrc ) { var setter = _fnSetObjectDataFn( col.mData._ ); setter( d, contents ); attr( col.mData.sort, cell ); attr( col.mData.type, cell ); attr( col.mData.filter, cell ); } else { // Depending on the `data` option for the columns the data can // be read to either an object or an array. if ( objectRead ) { if ( ! col._setter ) { // Cache the setter function col._setter = _fnSetObjectDataFn( col.mData ); } col._setter( d, contents ); } else { d[i] = contents; } } } i++; }; if ( td ) { // `tr` element was passed in while ( td ) { name = td.nodeName.toUpperCase(); if ( name == "TD" || name == "TH" ) { cellProcess( td ); tds.push( td ); } td = td.nextSibling; } } else { // Existing row object passed in tds = row.anCells; for ( var j=0, jen=tds.length ; j<jen ; j++ ) { cellProcess( tds[j] ); } } // Read the ID from the DOM if present var rowNode = row.firstChild ? row : row.nTr; if ( rowNode ) { var id = rowNode.getAttribute( 'id' ); if ( id ) { _fnSetObjectDataFn( settings.rowId )( d, id ); } } return { data: d, cells: tds }; } /** * Create a new TR element (and it's TD children) for a row * @param {object} oSettings dataTables settings object * @param {int} iRow Row to consider * @param {node} [nTrIn] TR element to add to the table - optional. If not given, * DataTables will create a row automatically * @param {array} [anTds] Array of TD|TH elements for the row - must be given * if nTr is. * @memberof DataTable#oApi */ function _fnCreateTr ( oSettings, iRow, nTrIn, anTds ) { var row = oSettings.aoData[iRow], rowData = row._aData, cells = [], nTr, nTd, oCol, i, iLen; if ( row.nTr === null ) { nTr = nTrIn || document.createElement('tr'); row.nTr = nTr; row.anCells = cells; /* Use a private property on the node to allow reserve mapping from the node * to the aoData array for fast look up */ nTr._DT_RowIndex = iRow; /* Special parameters can be given by the data source to be used on the row */ _fnRowAttributes( oSettings, row ); /* Process each column */ for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { oCol = oSettings.aoColumns[i]; nTd = nTrIn ? anTds[i] : document.createElement( oCol.sCellType ); nTd._DT_CellIndex = { row: iRow, column: i }; cells.push( nTd ); // Need to create the HTML if new, or if a rendering function is defined if ( (!nTrIn || oCol.mRender || oCol.mData !== i) && (!$.isPlainObject(oCol.mData) || oCol.mData._ !== i+'.display') ) { nTd.innerHTML = _fnGetCellData( oSettings, iRow, i, 'display' ); } /* Add user defined class */ if ( oCol.sClass ) { nTd.className += ' '+oCol.sClass; } // Visibility - add or remove as required if ( oCol.bVisible && ! nTrIn ) { nTr.appendChild( nTd ); } else if ( ! oCol.bVisible && nTrIn ) { nTd.parentNode.removeChild( nTd ); } if ( oCol.fnCreatedCell ) { oCol.fnCreatedCell.call( oSettings.oInstance, nTd, _fnGetCellData( oSettings, iRow, i ), rowData, iRow, i ); } } _fnCallbackFire( oSettings, 'aoRowCreatedCallback', null, [nTr, rowData, iRow] ); } // Remove once webkit bug 131819 and Chromium bug 365619 have been resolved // and deployed row.nTr.setAttribute( 'role', 'row' ); } /** * Add attributes to a row based on the special `DT_*` parameters in a data * source object. * @param {object} settings DataTables settings object * @param {object} DataTables row object for the row to be modified * @memberof DataTable#oApi */ function _fnRowAttributes( settings, row ) { var tr = row.nTr; var data = row._aData; if ( tr ) { var id = settings.rowIdFn( data ); if ( id ) { tr.id = id; } if ( data.DT_RowClass ) { // Remove any classes added by DT_RowClass before var a = data.DT_RowClass.split(' '); row.__rowc = row.__rowc ? _unique( row.__rowc.concat( a ) ) : a; $(tr) .removeClass( row.__rowc.join(' ') ) .addClass( data.DT_RowClass ); } if ( data.DT_RowAttr ) { $(tr).attr( data.DT_RowAttr ); } if ( data.DT_RowData ) { $(tr).data( data.DT_RowData ); } } } /** * Create the HTML header for the table * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnBuildHead( oSettings ) { var i, ien, cell, row, column; var thead = oSettings.nTHead; var tfoot = oSettings.nTFoot; var createHeader = $('th, td', thead).length === 0; var classes = oSettings.oClasses; var columns = oSettings.aoColumns; if ( createHeader ) { row = $('<tr/>').appendTo( thead ); } for ( i=0, ien=columns.length ; i<ien ; i++ ) { column = columns[i]; cell = $( column.nTh ).addClass( column.sClass ); if ( createHeader ) { cell.appendTo( row ); } // 1.11 move into sorting if ( oSettings.oFeatures.bSort ) { cell.addClass( column.sSortingClass ); if ( column.bSortable !== false ) { cell .attr( 'tabindex', oSettings.iTabIndex ) .attr( 'aria-controls', oSettings.sTableId ); _fnSortAttachListener( oSettings, column.nTh, i ); } } if ( column.sTitle != cell[0].innerHTML ) { cell.html( column.sTitle ); } _fnRenderer( oSettings, 'header' )( oSettings, cell, column, classes ); } if ( createHeader ) { _fnDetectHeader( oSettings.aoHeader, thead ); } /* ARIA role for the rows */ $(thead).find('>tr').attr('role', 'row'); /* Deal with the footer - add classes if required */ $(thead).find('>tr>th, >tr>td').addClass( classes.sHeaderTH ); $(tfoot).find('>tr>th, >tr>td').addClass( classes.sFooterTH ); // Cache the footer cells. Note that we only take the cells from the first // row in the footer. If there is more than one row the user wants to // interact with, they need to use the table().foot() method. Note also this // allows cells to be used for multiple columns using colspan if ( tfoot !== null ) { var cells = oSettings.aoFooter[0]; for ( i=0, ien=cells.length ; i<ien ; i++ ) { column = columns[i]; column.nTf = cells[i].cell; if ( column.sClass ) { $(column.nTf).addClass( column.sClass ); } } } } /** * Draw the header (or footer) element based on the column visibility states. The * methodology here is to use the layout array from _fnDetectHeader, modified for * the instantaneous column visibility, to construct the new layout. The grid is * traversed over cell at a time in a rows x columns grid fashion, although each * cell insert can cover multiple elements in the grid - which is tracks using the * aApplied array. Cell inserts in the grid will only occur where there isn't * already a cell in that position. * @param {object} oSettings dataTables settings object * @param array {objects} aoSource Layout array from _fnDetectHeader * @param {boolean} [bIncludeHidden=false] If true then include the hidden columns in the calc, * @memberof DataTable#oApi */ function _fnDrawHead( oSettings, aoSource, bIncludeHidden ) { var i, iLen, j, jLen, k, kLen, n, nLocalTr; var aoLocal = []; var aApplied = []; var iColumns = oSettings.aoColumns.length; var iRowspan, iColspan; if ( ! aoSource ) { return; } if ( bIncludeHidden === undefined ) { bIncludeHidden = false; } /* Make a copy of the master layout array, but without the visible columns in it */ for ( i=0, iLen=aoSource.length ; i<iLen ; i++ ) { aoLocal[i] = aoSource[i].slice(); aoLocal[i].nTr = aoSource[i].nTr; /* Remove any columns which are currently hidden */ for ( j=iColumns-1 ; j>=0 ; j-- ) { if ( !oSettings.aoColumns[j].bVisible && !bIncludeHidden ) { aoLocal[i].splice( j, 1 ); } } /* Prep the applied array - it needs an element for each row */ aApplied.push( [] ); } for ( i=0, iLen=aoLocal.length ; i<iLen ; i++ ) { nLocalTr = aoLocal[i].nTr; /* All cells are going to be replaced, so empty out the row */ if ( nLocalTr ) { while( (n = nLocalTr.firstChild) ) { nLocalTr.removeChild( n ); } } for ( j=0, jLen=aoLocal[i].length ; j<jLen ; j++ ) { iRowspan = 1; iColspan = 1; /* Check to see if there is already a cell (row/colspan) covering our target * insert point. If there is, then there is nothing to do. */ if ( aApplied[i][j] === undefined ) { nLocalTr.appendChild( aoLocal[i][j].cell ); aApplied[i][j] = 1; /* Expand the cell to cover as many rows as needed */ while ( aoLocal[i+iRowspan] !== undefined && aoLocal[i][j].cell == aoLocal[i+iRowspan][j].cell ) { aApplied[i+iRowspan][j] = 1; iRowspan++; } /* Expand the cell to cover as many columns as needed */ while ( aoLocal[i][j+iColspan] !== undefined && aoLocal[i][j].cell == aoLocal[i][j+iColspan].cell ) { /* Must update the applied array over the rows for the columns */ for ( k=0 ; k<iRowspan ; k++ ) { aApplied[i+k][j+iColspan] = 1; } iColspan++; } /* Do the actual expansion in the DOM */ $(aoLocal[i][j].cell) .attr('rowspan', iRowspan) .attr('colspan', iColspan); } } } } /** * Insert the required TR nodes into the table for display * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnDraw( oSettings ) { /* Provide a pre-callback function which can be used to cancel the draw is false is returned */ var aPreDraw = _fnCallbackFire( oSettings, 'aoPreDrawCallback', 'preDraw', [oSettings] ); if ( $.inArray( false, aPreDraw ) !== -1 ) { _fnProcessingDisplay( oSettings, false ); return; } var i, iLen, n; var anRows = []; var iRowCount = 0; var asStripeClasses = oSettings.asStripeClasses; var iStripes = asStripeClasses.length; var iOpenRows = oSettings.aoOpenRows.length; var oLang = oSettings.oLanguage; var iInitDisplayStart = oSettings.iInitDisplayStart; var bServerSide = _fnDataSource( oSettings ) == 'ssp'; var aiDisplay = oSettings.aiDisplay; oSettings.bDrawing = true; /* Check and see if we have an initial draw position from state saving */ if ( iInitDisplayStart !== undefined && iInitDisplayStart !== -1 ) { oSettings._iDisplayStart = bServerSide ? iInitDisplayStart : iInitDisplayStart >= oSettings.fnRecordsDisplay() ? 0 : iInitDisplayStart; oSettings.iInitDisplayStart = -1; } var iDisplayStart = oSettings._iDisplayStart; var iDisplayEnd = oSettings.fnDisplayEnd(); /* Server-side processing draw intercept */ if ( oSettings.bDeferLoading ) { oSettings.bDeferLoading = false; oSettings.iDraw++; _fnProcessingDisplay( oSettings, false ); } else if ( !bServerSide ) { oSettings.iDraw++; } else if ( !oSettings.bDestroying && !_fnAjaxUpdate( oSettings ) ) { return; } if ( aiDisplay.length !== 0 ) { var iStart = bServerSide ? 0 : iDisplayStart; var iEnd = bServerSide ? oSettings.aoData.length : iDisplayEnd; for ( var j=iStart ; j<iEnd ; j++ ) { var iDataIndex = aiDisplay[j]; var aoData = oSettings.aoData[ iDataIndex ]; if ( aoData.nTr === null ) { _fnCreateTr( oSettings, iDataIndex ); } var nRow = aoData.nTr; /* Remove the old striping classes and then add the new one */ if ( iStripes !== 0 ) { var sStripe = asStripeClasses[ iRowCount % iStripes ]; if ( aoData._sRowStripe != sStripe ) { $(nRow).removeClass( aoData._sRowStripe ).addClass( sStripe ); aoData._sRowStripe = sStripe; } } // Row callback functions - might want to manipulate the row // iRowCount and j are not currently documented. Are they at all // useful? _fnCallbackFire( oSettings, 'aoRowCallback', null, [nRow, aoData._aData, iRowCount, j] ); anRows.push( nRow ); iRowCount++; } } else { /* Table is empty - create a row with an empty message in it */ var sZero = oLang.sZeroRecords; if ( oSettings.iDraw == 1 && _fnDataSource( oSettings ) == 'ajax' ) { sZero = oLang.sLoadingRecords; } else if ( oLang.sEmptyTable && oSettings.fnRecordsTotal() === 0 ) { sZero = oLang.sEmptyTable; } anRows[ 0 ] = $( '<tr/>', { 'class': iStripes ? asStripeClasses[0] : '' } ) .append( $('<td />', { 'valign': 'top', 'colSpan': _fnVisbleColumns( oSettings ), 'class': oSettings.oClasses.sRowEmpty } ).html( sZero ) )[0]; } /* Header and footer callbacks */ _fnCallbackFire( oSettings, 'aoHeaderCallback', 'header', [ $(oSettings.nTHead).children('tr')[0], _fnGetDataMaster( oSettings ), iDisplayStart, iDisplayEnd, aiDisplay ] ); _fnCallbackFire( oSettings, 'aoFooterCallback', 'footer', [ $(oSettings.nTFoot).children('tr')[0], _fnGetDataMaster( oSettings ), iDisplayStart, iDisplayEnd, aiDisplay ] ); var body = $(oSettings.nTBody); body.children().detach(); body.append( $(anRows) ); /* Call all required callback functions for the end of a draw */ _fnCallbackFire( oSettings, 'aoDrawCallback', 'draw', [oSettings] ); /* Draw is complete, sorting and filtering must be as well */ oSettings.bSorted = false; oSettings.bFiltered = false; oSettings.bDrawing = false; } /** * Redraw the table - taking account of the various features which are enabled * @param {object} oSettings dataTables settings object * @param {boolean} [holdPosition] Keep the current paging position. By default * the paging is reset to the first page * @memberof DataTable#oApi */ function _fnReDraw( settings, holdPosition ) { var features = settings.oFeatures, sort = features.bSort, filter = features.bFilter; if ( sort ) { _fnSort( settings ); } if ( filter ) { _fnFilterComplete( settings, settings.oPreviousSearch ); } else { // No filtering, so we want to just use the display master settings.aiDisplay = settings.aiDisplayMaster.slice(); } if ( holdPosition !== true ) { settings._iDisplayStart = 0; } // Let any modules know about the draw hold position state (used by // scrolling internally) settings._drawHold = holdPosition; _fnDraw( settings ); settings._drawHold = false; } /** * Add the options to the page HTML for the table * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnAddOptionsHtml ( oSettings ) { var classes = oSettings.oClasses; var table = $(oSettings.nTable); var holding = $('<div/>').insertBefore( table ); // Holding element for speed var features = oSettings.oFeatures; // All DataTables are wrapped in a div var insert = $('<div/>', { id: oSettings.sTableId+'_wrapper', 'class': classes.sWrapper + (oSettings.nTFoot ? '' : ' '+classes.sNoFooter) } ); oSettings.nHolding = holding[0]; oSettings.nTableWrapper = insert[0]; oSettings.nTableReinsertBefore = oSettings.nTable.nextSibling; /* Loop over the user set positioning and place the elements as needed */ var aDom = oSettings.sDom.split(''); var featureNode, cOption, nNewNode, cNext, sAttr, j; for ( var i=0 ; i<aDom.length ; i++ ) { featureNode = null; cOption = aDom[i]; if ( cOption == '<' ) { /* New container div */ nNewNode = $('<div/>')[0]; /* Check to see if we should append an id and/or a class name to the container */ cNext = aDom[i+1]; if ( cNext == "'" || cNext == '"' ) { sAttr = ""; j = 2; while ( aDom[i+j] != cNext ) { sAttr += aDom[i+j]; j++; } /* Replace jQuery UI constants @todo depreciated */ if ( sAttr == "H" ) { sAttr = classes.sJUIHeader; } else if ( sAttr == "F" ) { sAttr = classes.sJUIFooter; } /* The attribute can be in the format of "#id.class", "#id" or "class" This logic * breaks the string into parts and applies them as needed */ if ( sAttr.indexOf('.') != -1 ) { var aSplit = sAttr.split('.'); nNewNode.id = aSplit[0].substr(1, aSplit[0].length-1); nNewNode.className = aSplit[1]; } else if ( sAttr.charAt(0) == "#" ) { nNewNode.id = sAttr.substr(1, sAttr.length-1); } else { nNewNode.className = sAttr; } i += j; /* Move along the position array */ } insert.append( nNewNode ); insert = $(nNewNode); } else if ( cOption == '>' ) { /* End container div */ insert = insert.parent(); } // @todo Move options into their own plugins? else if ( cOption == 'l' && features.bPaginate && features.bLengthChange ) { /* Length */ featureNode = _fnFeatureHtmlLength( oSettings ); } else if ( cOption == 'f' && features.bFilter ) { /* Filter */ featureNode = _fnFeatureHtmlFilter( oSettings ); } else if ( cOption == 'r' && features.bProcessing ) { /* pRocessing */ featureNode = _fnFeatureHtmlProcessing( oSettings ); } else if ( cOption == 't' ) { /* Table */ featureNode = _fnFeatureHtmlTable( oSettings ); } else if ( cOption == 'i' && features.bInfo ) { /* Info */ featureNode = _fnFeatureHtmlInfo( oSettings ); } else if ( cOption == 'p' && features.bPaginate ) { /* Pagination */ featureNode = _fnFeatureHtmlPaginate( oSettings ); } else if ( DataTable.ext.feature.length !== 0 ) { /* Plug-in features */ var aoFeatures = DataTable.ext.feature; for ( var k=0, kLen=aoFeatures.length ; k<kLen ; k++ ) { if ( cOption == aoFeatures[k].cFeature ) { featureNode = aoFeatures[k].fnInit( oSettings ); break; } } } /* Add to the 2D features array */ if ( featureNode ) { var aanFeatures = oSettings.aanFeatures; if ( ! aanFeatures[cOption] ) { aanFeatures[cOption] = []; } aanFeatures[cOption].push( featureNode ); insert.append( featureNode ); } } /* Built our DOM structure - replace the holding div with what we want */ holding.replaceWith( insert ); oSettings.nHolding = null; } /** * Use the DOM source to create up an array of header cells. The idea here is to * create a layout grid (array) of rows x columns, which contains a reference * to the cell that that point in the grid (regardless of col/rowspan), such that * any column / row could be removed and the new grid constructed * @param array {object} aLayout Array to store the calculated layout in * @param {node} nThead The header/footer element for the table * @memberof DataTable#oApi */ function _fnDetectHeader ( aLayout, nThead ) { var nTrs = $(nThead).children('tr'); var nTr, nCell; var i, k, l, iLen, jLen, iColShifted, iColumn, iColspan, iRowspan; var bUnique; var fnShiftCol = function ( a, i, j ) { var k = a[i]; while ( k[j] ) { j++; } return j; }; aLayout.splice( 0, aLayout.length ); /* We know how many rows there are in the layout - so prep it */ for ( i=0, iLen=nTrs.length ; i<iLen ; i++ ) { aLayout.push( [] ); } /* Calculate a layout array */ for ( i=0, iLen=nTrs.length ; i<iLen ; i++ ) { nTr = nTrs[i]; iColumn = 0; /* For every cell in the row... */ nCell = nTr.firstChild; while ( nCell ) { if ( nCell.nodeName.toUpperCase() == "TD" || nCell.nodeName.toUpperCase() == "TH" ) { /* Get the col and rowspan attributes from the DOM and sanitise them */ iColspan = nCell.getAttribute('colspan') * 1; iRowspan = nCell.getAttribute('rowspan') * 1; iColspan = (!iColspan || iColspan===0 || iColspan===1) ? 1 : iColspan; iRowspan = (!iRowspan || iRowspan===0 || iRowspan===1) ? 1 : iRowspan; /* There might be colspan cells already in this row, so shift our target * accordingly */ iColShifted = fnShiftCol( aLayout, i, iColumn ); /* Cache calculation for unique columns */ bUnique = iColspan === 1 ? true : false; /* If there is col / rowspan, copy the information into the layout grid */ for ( l=0 ; l<iColspan ; l++ ) { for ( k=0 ; k<iRowspan ; k++ ) { aLayout[i+k][iColShifted+l] = { "cell": nCell, "unique": bUnique }; aLayout[i+k].nTr = nTr; } } } nCell = nCell.nextSibling; } } } /** * Get an array of unique th elements, one for each column * @param {object} oSettings dataTables settings object * @param {node} nHeader automatically detect the layout from this node - optional * @param {array} aLayout thead/tfoot layout from _fnDetectHeader - optional * @returns array {node} aReturn list of unique th's * @memberof DataTable#oApi */ function _fnGetUniqueThs ( oSettings, nHeader, aLayout ) { var aReturn = []; if ( !aLayout ) { aLayout = oSettings.aoHeader; if ( nHeader ) { aLayout = []; _fnDetectHeader( aLayout, nHeader ); } } for ( var i=0, iLen=aLayout.length ; i<iLen ; i++ ) { for ( var j=0, jLen=aLayout[i].length ; j<jLen ; j++ ) { if ( aLayout[i][j].unique && (!aReturn[j] || !oSettings.bSortCellsTop) ) { aReturn[j] = aLayout[i][j].cell; } } } return aReturn; } /** * Create an Ajax call based on the table's settings, taking into account that * parameters can have multiple forms, and backwards compatibility. * * @param {object} oSettings dataTables settings object * @param {array} data Data to send to the server, required by * DataTables - may be augmented by developer callbacks * @param {function} fn Callback function to run when data is obtained */ function _fnBuildAjax( oSettings, data, fn ) { // Compatibility with 1.9-, allow fnServerData and event to manipulate _fnCallbackFire( oSettings, 'aoServerParams', 'serverParams', [data] ); // Convert to object based for 1.10+ if using the old array scheme which can // come from server-side processing or serverParams if ( data && $.isArray(data) ) { var tmp = {}; var rbracket = /(.*?)\[\]$/; $.each( data, function (key, val) { var match = val.name.match(rbracket); if ( match ) { // Support for arrays var name = match[0]; if ( ! tmp[ name ] ) { tmp[ name ] = []; } tmp[ name ].push( val.value ); } else { tmp[val.name] = val.value; } } ); data = tmp; } var ajaxData; var ajax = oSettings.ajax; var instance = oSettings.oInstance; var callback = function ( json ) { _fnCallbackFire( oSettings, null, 'xhr', [oSettings, json, oSettings.jqXHR] ); fn( json ); }; if ( $.isPlainObject( ajax ) && ajax.data ) { ajaxData = ajax.data; var newData = $.isFunction( ajaxData ) ? ajaxData( data, oSettings ) : // fn can manipulate data or return ajaxData; // an object object or array to merge // If the function returned something, use that alone data = $.isFunction( ajaxData ) && newData ? newData : $.extend( true, data, newData ); // Remove the data property as we've resolved it already and don't want // jQuery to do it again (it is restored at the end of the function) delete ajax.data; } var baseAjax = { "data": data, "success": function (json) { var error = json.error || json.sError; if ( error ) { _fnLog( oSettings, 0, error ); } oSettings.json = json; callback( json ); }, "dataType": "json", "cache": false, "type": oSettings.sServerMethod, "error": function (xhr, error, thrown) { var ret = _fnCallbackFire( oSettings, null, 'xhr', [oSettings, null, oSettings.jqXHR] ); if ( $.inArray( true, ret ) === -1 ) { if ( error == "parsererror" ) { _fnLog( oSettings, 0, 'Invalid JSON response', 1 ); } else if ( xhr.readyState === 4 ) { _fnLog( oSettings, 0, 'Ajax error', 7 ); } } _fnProcessingDisplay( oSettings, false ); } }; // Store the data submitted for the API oSettings.oAjaxData = data; // Allow plug-ins and external processes to modify the data _fnCallbackFire( oSettings, null, 'preXhr', [oSettings, data] ); if ( oSettings.fnServerData ) { // DataTables 1.9- compatibility oSettings.fnServerData.call( instance, oSettings.sAjaxSource, $.map( data, function (val, key) { // Need to convert back to 1.9 trad format return { name: key, value: val }; } ), callback, oSettings ); } else if ( oSettings.sAjaxSource || typeof ajax === 'string' ) { // DataTables 1.9- compatibility oSettings.jqXHR = $.ajax( $.extend( baseAjax, { url: ajax || oSettings.sAjaxSource } ) ); } else if ( $.isFunction( ajax ) ) { // Is a function - let the caller define what needs to be done oSettings.jqXHR = ajax.call( instance, data, callback, oSettings ); } else { // Object to extend the base settings oSettings.jqXHR = $.ajax( $.extend( baseAjax, ajax ) ); // Restore for next time around ajax.data = ajaxData; } } /** * Update the table using an Ajax call * @param {object} settings dataTables settings object * @returns {boolean} Block the table drawing or not * @memberof DataTable#oApi */ function _fnAjaxUpdate( settings ) { if ( settings.bAjaxDataGet ) { settings.iDraw++; _fnProcessingDisplay( settings, true ); _fnBuildAjax( settings, _fnAjaxParameters( settings ), function(json) { _fnAjaxUpdateDraw( settings, json ); } ); return false; } return true; } /** * Build up the parameters in an object needed for a server-side processing * request. Note that this is basically done twice, is different ways - a modern * method which is used by default in DataTables 1.10 which uses objects and * arrays, or the 1.9- method with is name / value pairs. 1.9 method is used if * the sAjaxSource option is used in the initialisation, or the legacyAjax * option is set. * @param {object} oSettings dataTables settings object * @returns {bool} block the table drawing or not * @memberof DataTable#oApi */ function _fnAjaxParameters( settings ) { var columns = settings.aoColumns, columnCount = columns.length, features = settings.oFeatures, preSearch = settings.oPreviousSearch, preColSearch = settings.aoPreSearchCols, i, data = [], dataProp, column, columnSearch, sort = _fnSortFlatten( settings ), displayStart = settings._iDisplayStart, displayLength = features.bPaginate !== false ? settings._iDisplayLength : -1; var param = function ( name, value ) { data.push( { 'name': name, 'value': value } ); }; // DataTables 1.9- compatible method param( 'sEcho', settings.iDraw ); param( 'iColumns', columnCount ); param( 'sColumns', _pluck( columns, 'sName' ).join(',') ); param( 'iDisplayStart', displayStart ); param( 'iDisplayLength', displayLength ); // DataTables 1.10+ method var d = { draw: settings.iDraw, columns: [], order: [], start: displayStart, length: displayLength, search: { value: preSearch.sSearch, regex: preSearch.bRegex } }; for ( i=0 ; i<columnCount ; i++ ) { column = columns[i]; columnSearch = preColSearch[i]; dataProp = typeof column.mData=="function" ? 'function' : column.mData ; d.columns.push( { data: dataProp, name: column.sName, searchable: column.bSearchable, orderable: column.bSortable, search: { value: columnSearch.sSearch, regex: columnSearch.bRegex } } ); param( "mDataProp_"+i, dataProp ); if ( features.bFilter ) { param( 'sSearch_'+i, columnSearch.sSearch ); param( 'bRegex_'+i, columnSearch.bRegex ); param( 'bSearchable_'+i, column.bSearchable ); } if ( features.bSort ) { param( 'bSortable_'+i, column.bSortable ); } } if ( features.bFilter ) { param( 'sSearch', preSearch.sSearch ); param( 'bRegex', preSearch.bRegex ); } if ( features.bSort ) { $.each( sort, function ( i, val ) { d.order.push( { column: val.col, dir: val.dir } ); param( 'iSortCol_'+i, val.col ); param( 'sSortDir_'+i, val.dir ); } ); param( 'iSortingCols', sort.length ); } // If the legacy.ajax parameter is null, then we automatically decide which // form to use, based on sAjaxSource var legacy = DataTable.ext.legacy.ajax; if ( legacy === null ) { return settings.sAjaxSource ? data : d; } // Otherwise, if legacy has been specified then we use that to decide on the // form return legacy ? data : d; } /** * Data the data from the server (nuking the old) and redraw the table * @param {object} oSettings dataTables settings object * @param {object} json json data return from the server. * @param {string} json.sEcho Tracking flag for DataTables to match requests * @param {int} json.iTotalRecords Number of records in the data set, not accounting for filtering * @param {int} json.iTotalDisplayRecords Number of records in the data set, accounting for filtering * @param {array} json.aaData The data to display on this page * @param {string} [json.sColumns] Column ordering (sName, comma separated) * @memberof DataTable#oApi */ function _fnAjaxUpdateDraw ( settings, json ) { // v1.10 uses camelCase variables, while 1.9 uses Hungarian notation. // Support both var compat = function ( old, modern ) { return json[old] !== undefined ? json[old] : json[modern]; }; var data = _fnAjaxDataSrc( settings, json ); var draw = compat( 'sEcho', 'draw' ); var recordsTotal = compat( 'iTotalRecords', 'recordsTotal' ); var recordsFiltered = compat( 'iTotalDisplayRecords', 'recordsFiltered' ); if ( draw ) { // Protect against out of sequence returns if ( draw*1 < settings.iDraw ) { return; } settings.iDraw = draw * 1; } _fnClearTable( settings ); settings._iRecordsTotal = parseInt(recordsTotal, 10); settings._iRecordsDisplay = parseInt(recordsFiltered, 10); for ( var i=0, ien=data.length ; i<ien ; i++ ) { _fnAddData( settings, data[i] ); } settings.aiDisplay = settings.aiDisplayMaster.slice(); settings.bAjaxDataGet = false; _fnDraw( settings ); if ( ! settings._bInitComplete ) { _fnInitComplete( settings, json ); } settings.bAjaxDataGet = true; _fnProcessingDisplay( settings, false ); } /** * Get the data from the JSON data source to use for drawing a table. Using * `_fnGetObjectDataFn` allows the data to be sourced from a property of the * source object, or from a processing function. * @param {object} oSettings dataTables settings object * @param {object} json Data source object / array from the server * @return {array} Array of data to use */ function _fnAjaxDataSrc ( oSettings, json ) { var dataSrc = $.isPlainObject( oSettings.ajax ) && oSettings.ajax.dataSrc !== undefined ? oSettings.ajax.dataSrc : oSettings.sAjaxDataProp; // Compatibility with 1.9-. // Compatibility with 1.9-. In order to read from aaData, check if the // default has been changed, if not, check for aaData if ( dataSrc === 'data' ) { return json.aaData || json[dataSrc]; } return dataSrc !== "" ? _fnGetObjectDataFn( dataSrc )( json ) : json; } /** * Generate the node required for filtering text * @returns {node} Filter control element * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnFeatureHtmlFilter ( settings ) { var classes = settings.oClasses; var tableId = settings.sTableId; var language = settings.oLanguage; var previousSearch = settings.oPreviousSearch; var features = settings.aanFeatures; var input = '<input type="search" class="'+classes.sFilterInput+'"/>'; var str = language.sSearch; str = str.match(/_INPUT_/) ? str.replace('_INPUT_', input) : str+input; var filter = $('<div/>', { 'id': ! features.f ? tableId+'_filter' : null, 'class': classes.sFilter } ) .append( $('<p/>' ).append( str ) ); var searchFn = function() { /* Update all other filter input elements for the new display */ var n = features.f; var val = !this.value ? "" : this.value; // mental IE8 fix :-( /* Now do the filter */ if ( val != previousSearch.sSearch ) { _fnFilterComplete( settings, { "sSearch": val, "bRegex": previousSearch.bRegex, "bSmart": previousSearch.bSmart , "bCaseInsensitive": previousSearch.bCaseInsensitive } ); // Need to redraw, without resorting settings._iDisplayStart = 0; _fnDraw( settings ); } }; var searchDelay = settings.searchDelay !== null ? settings.searchDelay : _fnDataSource( settings ) === 'ssp' ? 400 : 0; var jqFilter = $('input', filter) .val( previousSearch.sSearch ) .attr( 'placeholder', language.sSearchPlaceholder ) .on( 'keyup.DT search.DT input.DT paste.DT cut.DT', searchDelay ? _fnThrottle( searchFn, searchDelay ) : searchFn ) .on( 'keypress.DT', function(e) { /* Prevent form submission */ if ( e.keyCode == 13 ) { return false; } } ) .attr('aria-controls', tableId); // Update the input elements whenever the table is filtered $(settings.nTable).on( 'search.dt.DT', function ( ev, s ) { if ( settings === s ) { // IE9 throws an 'unknown error' if document.activeElement is used // inside an iframe or frame... try { if ( jqFilter[0] !== document.activeElement ) { jqFilter.val( previousSearch.sSearch ); } } catch ( e ) {} } } ); return filter[0]; } /** * Filter the table using both the global filter and column based filtering * @param {object} oSettings dataTables settings object * @param {object} oSearch search information * @param {int} [iForce] force a research of the master array (1) or not (undefined or 0) * @memberof DataTable#oApi */ function _fnFilterComplete ( oSettings, oInput, iForce ) { var oPrevSearch = oSettings.oPreviousSearch; var aoPrevSearch = oSettings.aoPreSearchCols; var fnSaveFilter = function ( oFilter ) { /* Save the filtering values */ oPrevSearch.sSearch = oFilter.sSearch; oPrevSearch.bRegex = oFilter.bRegex; oPrevSearch.bSmart = oFilter.bSmart; oPrevSearch.bCaseInsensitive = oFilter.bCaseInsensitive; }; var fnRegex = function ( o ) { // Backwards compatibility with the bEscapeRegex option return o.bEscapeRegex !== undefined ? !o.bEscapeRegex : o.bRegex; }; // Resolve any column types that are unknown due to addition or invalidation // @todo As per sort - can this be moved into an event handler? _fnColumnTypes( oSettings ); /* In server-side processing all filtering is done by the server, so no point hanging around here */ if ( _fnDataSource( oSettings ) != 'ssp' ) { /* Global filter */ _fnFilter( oSettings, oInput.sSearch, iForce, fnRegex(oInput), oInput.bSmart, oInput.bCaseInsensitive ); fnSaveFilter( oInput ); /* Now do the individual column filter */ for ( var i=0 ; i<aoPrevSearch.length ; i++ ) { _fnFilterColumn( oSettings, aoPrevSearch[i].sSearch, i, fnRegex(aoPrevSearch[i]), aoPrevSearch[i].bSmart, aoPrevSearch[i].bCaseInsensitive ); } /* Custom filtering */ _fnFilterCustom( oSettings ); } else { fnSaveFilter( oInput ); } /* Tell the draw function we have been filtering */ oSettings.bFiltered = true; _fnCallbackFire( oSettings, null, 'search', [oSettings] ); } /** * Apply custom filtering functions * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnFilterCustom( settings ) { var filters = DataTable.ext.search; var displayRows = settings.aiDisplay; var row, rowIdx; for ( var i=0, ien=filters.length ; i<ien ; i++ ) { var rows = []; // Loop over each row and see if it should be included for ( var j=0, jen=displayRows.length ; j<jen ; j++ ) { rowIdx = displayRows[ j ]; row = settings.aoData[ rowIdx ]; if ( filters[i]( settings, row._aFilterData, rowIdx, row._aData, j ) ) { rows.push( rowIdx ); } } // So the array reference doesn't break set the results into the // existing array displayRows.length = 0; $.merge( displayRows, rows ); } } /** * Filter the table on a per-column basis * @param {object} oSettings dataTables settings object * @param {string} sInput string to filter on * @param {int} iColumn column to filter * @param {bool} bRegex treat search string as a regular expression or not * @param {bool} bSmart use smart filtering or not * @param {bool} bCaseInsensitive Do case insenstive matching or not * @memberof DataTable#oApi */ function _fnFilterColumn ( settings, searchStr, colIdx, regex, smart, caseInsensitive ) { if ( searchStr === '' ) { return; } var data; var out = []; var display = settings.aiDisplay; var rpSearch = _fnFilterCreateSearch( searchStr, regex, smart, caseInsensitive ); for ( var i=0 ; i<display.length ; i++ ) { data = settings.aoData[ display[i] ]._aFilterData[ colIdx ]; if ( rpSearch.test( data ) ) { out.push( display[i] ); } } settings.aiDisplay = out; } /** * Filter the data table based on user input and draw the table * @param {object} settings dataTables settings object * @param {string} input string to filter on * @param {int} force optional - force a research of the master array (1) or not (undefined or 0) * @param {bool} regex treat as a regular expression or not * @param {bool} smart perform smart filtering or not * @param {bool} caseInsensitive Do case insenstive matching or not * @memberof DataTable#oApi */ function _fnFilter( settings, input, force, regex, smart, caseInsensitive ) { var rpSearch = _fnFilterCreateSearch( input, regex, smart, caseInsensitive ); var prevSearch = settings.oPreviousSearch.sSearch; var displayMaster = settings.aiDisplayMaster; var display, invalidated, i; var filtered = []; // Need to take account of custom filtering functions - always filter if ( DataTable.ext.search.length !== 0 ) { force = true; } // Check if any of the rows were invalidated invalidated = _fnFilterData( settings ); // If the input is blank - we just want the full data set if ( input.length <= 0 ) { settings.aiDisplay = displayMaster.slice(); } else { // New search - start from the master array if ( invalidated || force || prevSearch.length > input.length || input.indexOf(prevSearch) !== 0 || settings.bSorted // On resort, the display master needs to be // re-filtered since indexes will have changed ) { settings.aiDisplay = displayMaster.slice(); } // Search the display array display = settings.aiDisplay; for ( i=0 ; i<display.length ; i++ ) { if ( rpSearch.test( settings.aoData[ display[i] ]._sFilterRow ) ) { filtered.push( display[i] ); } } settings.aiDisplay = filtered; } } /** * Build a regular expression object suitable for searching a table * @param {string} sSearch string to search for * @param {bool} bRegex treat as a regular expression or not * @param {bool} bSmart perform smart filtering or not * @param {bool} bCaseInsensitive Do case insensitive matching or not * @returns {RegExp} constructed object * @memberof DataTable#oApi */ function _fnFilterCreateSearch( search, regex, smart, caseInsensitive ) { search = regex ? search : _fnEscapeRegex( search ); if ( smart ) { /* For smart filtering we want to allow the search to work regardless of * word order. We also want double quoted text to be preserved, so word * order is important - a la google. So this is what we want to * generate: * * ^(?=.*?\bone\b)(?=.*?\btwo three\b)(?=.*?\bfour\b).*$ */ var a = $.map( search.match( /"[^"]+"|[^ ]+/g ) || [''], function ( word ) { if ( word.charAt(0) === '"' ) { var m = word.match( /^"(.*)"$/ ); word = m ? m[1] : word; } return word.replace('"', ''); } ); search = '^(?=.*?'+a.join( ')(?=.*?' )+').*$'; } return new RegExp( search, caseInsensitive ? 'i' : '' ); } /** * Escape a string such that it can be used in a regular expression * @param {string} sVal string to escape * @returns {string} escaped string * @memberof DataTable#oApi */ var _fnEscapeRegex = DataTable.util.escapeRegex; var __filter_div = $('<div>')[0]; var __filter_div_textContent = __filter_div.textContent !== undefined; // Update the filtering data for each row if needed (by invalidation or first run) function _fnFilterData ( settings ) { var columns = settings.aoColumns; var column; var i, j, ien, jen, filterData, cellData, row; var fomatters = DataTable.ext.type.search; var wasInvalidated = false; for ( i=0, ien=settings.aoData.length ; i<ien ; i++ ) { row = settings.aoData[i]; if ( ! row._aFilterData ) { filterData = []; for ( j=0, jen=columns.length ; j<jen ; j++ ) { column = columns[j]; if ( column.bSearchable ) { cellData = _fnGetCellData( settings, i, j, 'filter' ); if ( fomatters[ column.sType ] ) { cellData = fomatters[ column.sType ]( cellData ); } // Search in DataTables 1.10 is string based. In 1.11 this // should be altered to also allow strict type checking. if ( cellData === null ) { cellData = ''; } if ( typeof cellData !== 'string' && cellData.toString ) { cellData = cellData.toString(); } } else { cellData = ''; } // If it looks like there is an HTML entity in the string, // attempt to decode it so sorting works as expected. Note that // we could use a single line of jQuery to do this, but the DOM // method used here is much faster http://jsperf.com/html-decode if ( cellData.indexOf && cellData.indexOf('&') !== -1 ) { __filter_div.innerHTML = cellData; cellData = __filter_div_textContent ? __filter_div.textContent : __filter_div.innerText; } if ( cellData.replace ) { cellData = cellData.replace(/[\r\n]/g, ''); } filterData.push( cellData ); } row._aFilterData = filterData; row._sFilterRow = filterData.join(' '); wasInvalidated = true; } } return wasInvalidated; } /** * Convert from the internal Hungarian notation to camelCase for external * interaction * @param {object} obj Object to convert * @returns {object} Inverted object * @memberof DataTable#oApi */ function _fnSearchToCamel ( obj ) { return { search: obj.sSearch, smart: obj.bSmart, regex: obj.bRegex, caseInsensitive: obj.bCaseInsensitive }; } /** * Convert from camelCase notation to the internal Hungarian. We could use the * Hungarian convert function here, but this is cleaner * @param {object} obj Object to convert * @returns {object} Inverted object * @memberof DataTable#oApi */ function _fnSearchToHung ( obj ) { return { sSearch: obj.search, bSmart: obj.smart, bRegex: obj.regex, bCaseInsensitive: obj.caseInsensitive }; } /** * Generate the node required for the info display * @param {object} oSettings dataTables settings object * @returns {node} Information element * @memberof DataTable#oApi */ function _fnFeatureHtmlInfo ( settings ) { var tid = settings.sTableId, nodes = settings.aanFeatures.i, n = $('<div/>', { 'class': settings.oClasses.sInfo, 'id': ! nodes ? tid+'_info' : null } ); if ( ! nodes ) { // Update display on each draw settings.aoDrawCallback.push( { "fn": _fnUpdateInfo, "sName": "information" } ); n .attr( 'role', 'status' ) .attr( 'aria-live', 'polite' ); // Table is described by our info div $(settings.nTable).attr( 'aria-describedby', tid+'_info' ); } return n[0]; } /** * Update the information elements in the display * @param {object} settings dataTables settings object * @memberof DataTable#oApi */ function _fnUpdateInfo ( settings ) { /* Show information about the table */ var nodes = settings.aanFeatures.i; if ( nodes.length === 0 ) { return; } var lang = settings.oLanguage, start = settings._iDisplayStart+1, end = settings.fnDisplayEnd(), max = settings.fnRecordsTotal(), total = settings.fnRecordsDisplay(), out = total ? lang.sInfo : lang.sInfoEmpty; if ( total !== max ) { /* Record set after filtering */ out += ' ' + lang.sInfoFiltered; } // Convert the macros out += lang.sInfoPostFix; out = _fnInfoMacros( settings, out ); var callback = lang.fnInfoCallback; if ( callback !== null ) { out = callback.call( settings.oInstance, settings, start, end, max, total, out ); } $(nodes).html( out ); } function _fnInfoMacros ( settings, str ) { // When infinite scrolling, we are always starting at 1. _iDisplayStart is used only // internally var formatter = settings.fnFormatNumber, start = settings._iDisplayStart+1, len = settings._iDisplayLength, vis = settings.fnRecordsDisplay(), all = len === -1; return str. replace(/_START_/g, formatter.call( settings, start ) ). replace(/_END_/g, formatter.call( settings, settings.fnDisplayEnd() ) ). replace(/_MAX_/g, formatter.call( settings, settings.fnRecordsTotal() ) ). replace(/_TOTAL_/g, formatter.call( settings, vis ) ). replace(/_PAGE_/g, formatter.call( settings, all ? 1 : Math.ceil( start / len ) ) ). replace(/_PAGES_/g, formatter.call( settings, all ? 1 : Math.ceil( vis / len ) ) ); } /** * Draw the table for the first time, adding all required features * @param {object} settings dataTables settings object * @memberof DataTable#oApi */ function _fnInitialise ( settings ) { var i, iLen, iAjaxStart=settings.iInitDisplayStart; var columns = settings.aoColumns, column; var features = settings.oFeatures; var deferLoading = settings.bDeferLoading; // value modified by the draw /* Ensure that the table data is fully initialised */ if ( ! settings.bInitialised ) { setTimeout( function(){ _fnInitialise( settings ); }, 200 ); return; } /* Show the display HTML options */ _fnAddOptionsHtml( settings ); /* Build and draw the header / footer for the table */ _fnBuildHead( settings ); _fnDrawHead( settings, settings.aoHeader ); _fnDrawHead( settings, settings.aoFooter ); /* Okay to show that something is going on now */ _fnProcessingDisplay( settings, true ); /* Calculate sizes for columns */ if ( features.bAutoWidth ) { _fnCalculateColumnWidths( settings ); } for ( i=0, iLen=columns.length ; i<iLen ; i++ ) { column = columns[i]; if ( column.sWidth ) { column.nTh.style.width = _fnStringToCss( column.sWidth ); } } _fnCallbackFire( settings, null, 'preInit', [settings] ); // If there is default sorting required - let's do it. The sort function // will do the drawing for us. Otherwise we draw the table regardless of the // Ajax source - this allows the table to look initialised for Ajax sourcing // data (show 'loading' message possibly) _fnReDraw( settings ); // Server-side processing init complete is done by _fnAjaxUpdateDraw var dataSrc = _fnDataSource( settings ); if ( dataSrc != 'ssp' || deferLoading ) { // if there is an ajax source load the data if ( dataSrc == 'ajax' ) { _fnBuildAjax( settings, [], function(json) { var aData = _fnAjaxDataSrc( settings, json ); // Got the data - add it to the table for ( i=0 ; i<aData.length ; i++ ) { _fnAddData( settings, aData[i] ); } // Reset the init display for cookie saving. We've already done // a filter, and therefore cleared it before. So we need to make // it appear 'fresh' settings.iInitDisplayStart = iAjaxStart; _fnReDraw( settings ); _fnProcessingDisplay( settings, false ); _fnInitComplete( settings, json ); }, settings ); } else { _fnProcessingDisplay( settings, false ); _fnInitComplete( settings ); } } } /** * Draw the table for the first time, adding all required features * @param {object} oSettings dataTables settings object * @param {object} [json] JSON from the server that completed the table, if using Ajax source * with client-side processing (optional) * @memberof DataTable#oApi */ function _fnInitComplete ( settings, json ) { settings._bInitComplete = true; // When data was added after the initialisation (data or Ajax) we need to // calculate the column sizing if ( json || settings.oInit.aaData ) { _fnAdjustColumnSizing( settings ); } _fnCallbackFire( settings, null, 'plugin-init', [settings, json] ); _fnCallbackFire( settings, 'aoInitComplete', 'init', [settings, json] ); } function _fnLengthChange ( settings, val ) { var len = parseInt( val, 10 ); settings._iDisplayLength = len; _fnLengthOverflow( settings ); // Fire length change event _fnCallbackFire( settings, null, 'length', [settings, len] ); } /** * Generate the node required for user display length changing * @param {object} settings dataTables settings object * @returns {node} Display length feature node * @memberof DataTable#oApi */ function _fnFeatureHtmlLength ( settings ) { var classes = settings.oClasses, tableId = settings.sTableId, menu = settings.aLengthMenu, d2 = $.isArray( menu[0] ), lengths = d2 ? menu[0] : menu, language = d2 ? menu[1] : menu; var select = $('<select/>', { 'name': tableId+'_length', 'aria-controls': tableId, 'class': classes.sLengthSelect } ); for ( var i=0, ien=lengths.length ; i<ien ; i++ ) { select[0][ i ] = new Option( typeof language[i] === 'number' ? settings.fnFormatNumber( language[i] ) : language[i], lengths[i] ); } var div = $('<div><p/></div>').addClass( classes.sLength ); if ( ! settings.aanFeatures.l ) { div[0].id = tableId+'_length'; } div.children().append( settings.oLanguage.sLengthMenu.replace( '_MENU_', select[0].outerHTML ) ); // Can't use `select` variable as user might provide their own and the // reference is broken by the use of outerHTML $('select', div) .val( settings._iDisplayLength ) .on( 'change.DT', function(e) { _fnLengthChange( settings, $(this).val() ); _fnDraw( settings ); } ); // Update node value whenever anything changes the table's length $(settings.nTable).on( 'length.dt.DT', function (e, s, len) { if ( settings === s ) { $('select', div).val( len ); } } ); return div[0]; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Note that most of the paging logic is done in * DataTable.ext.pager */ /** * Generate the node required for default pagination * @param {object} oSettings dataTables settings object * @returns {node} Pagination feature node * @memberof DataTable#oApi */ function _fnFeatureHtmlPaginate ( settings ) { var type = settings.sPaginationType, plugin = DataTable.ext.pager[ type ], modern = typeof plugin === 'function', redraw = function( settings ) { _fnDraw( settings ); }, node = $('<div/>').addClass( settings.oClasses.sPaging + type )[0], features = settings.aanFeatures; if ( ! modern ) { plugin.fnInit( settings, node, redraw ); } /* Add a draw callback for the pagination on first instance, to update the paging display */ if ( ! features.p ) { node.id = settings.sTableId+'_paginate'; settings.aoDrawCallback.push( { "fn": function( settings ) { if ( modern ) { var start = settings._iDisplayStart, len = settings._iDisplayLength, visRecords = settings.fnRecordsDisplay(), all = len === -1, page = all ? 0 : Math.ceil( start / len ), pages = all ? 1 : Math.ceil( visRecords / len ), buttons = plugin(page, pages), i, ien; for ( i=0, ien=features.p.length ; i<ien ; i++ ) { _fnRenderer( settings, 'pageButton' )( settings, features.p[i], i, buttons, page, pages ); } } else { plugin.fnUpdate( settings, redraw ); } }, "sName": "pagination" } ); } return node; } /** * Alter the display settings to change the page * @param {object} settings DataTables settings object * @param {string|int} action Paging action to take: "first", "previous", * "next" or "last" or page number to jump to (integer) * @param [bool] redraw Automatically draw the update or not * @returns {bool} true page has changed, false - no change * @memberof DataTable#oApi */ function _fnPageChange ( settings, action, redraw ) { var start = settings._iDisplayStart, len = settings._iDisplayLength, records = settings.fnRecordsDisplay(); if ( records === 0 || len === -1 ) { start = 0; } else if ( typeof action === "number" ) { start = action * len; if ( start > records ) { start = 0; } } else if ( action == "first" ) { start = 0; } else if ( action == "previous" ) { start = len >= 0 ? start - len : 0; if ( start < 0 ) { start = 0; } } else if ( action == "next" ) { if ( start + len < records ) { start += len; } } else if ( action == "last" ) { start = Math.floor( (records-1) / len) * len; } else { _fnLog( settings, 0, "Unknown paging action: "+action, 5 ); } var changed = settings._iDisplayStart !== start; settings._iDisplayStart = start; if ( changed ) { _fnCallbackFire( settings, null, 'page', [settings] ); if ( redraw ) { _fnDraw( settings ); } } return changed; } /** * Generate the node required for the processing node * @param {object} settings dataTables settings object * @returns {node} Processing element * @memberof DataTable#oApi */ function _fnFeatureHtmlProcessing ( settings ) { return $('<div/>', { 'id': ! settings.aanFeatures.r ? settings.sTableId+'_processing' : null, 'class': settings.oClasses.sProcessing } ) .html( settings.oLanguage.sProcessing ) .insertBefore( settings.nTable )[0]; } /** * Display or hide the processing indicator * @param {object} settings dataTables settings object * @param {bool} show Show the processing indicator (true) or not (false) * @memberof DataTable#oApi */ function _fnProcessingDisplay ( settings, show ) { if ( settings.oFeatures.bProcessing ) { $(settings.aanFeatures.r).css( 'display', show ? 'block' : 'none' ); } _fnCallbackFire( settings, null, 'processing', [settings, show] ); } /** * Add any control elements for the table - specifically scrolling * @param {object} settings dataTables settings object * @returns {node} Node to add to the DOM * @memberof DataTable#oApi */ function _fnFeatureHtmlTable ( settings ) { var table = $(settings.nTable); // Add the ARIA grid role to the table table.attr( 'role', 'grid' ); // Scrolling from here on in var scroll = settings.oScroll; if ( scroll.sX === '' && scroll.sY === '' ) { return settings.nTable; } var scrollX = scroll.sX; var scrollY = scroll.sY; var classes = settings.oClasses; var caption = table.children('caption'); var captionSide = caption.length ? caption[0]._captionSide : null; var headerClone = $( table[0].cloneNode(false) ); var footerClone = $( table[0].cloneNode(false) ); var footer = table.children('tfoot'); var _div = '<div/>'; var size = function ( s ) { return !s ? null : _fnStringToCss( s ); }; if ( ! footer.length ) { footer = null; } /* * The HTML structure that we want to generate in this function is: * div - scroller * div - scroll head * div - scroll head inner * table - scroll head table * thead - thead * div - scroll body * table - table (master table) * thead - thead clone for sizing * tbody - tbody * div - scroll foot * div - scroll foot inner * table - scroll foot table * tfoot - tfoot */ var scroller = $( _div, { 'class': classes.sScrollWrapper } ) .append( $(_div, { 'class': classes.sScrollHead } ) .css( { overflow: 'hidden', position: 'relative', border: 0, width: scrollX ? size(scrollX) : '100%' } ) .append( $(_div, { 'class': classes.sScrollHeadInner } ) .css( { 'box-sizing': 'content-box', width: scroll.sXInner || '100%' } ) .append( headerClone .removeAttr('id') .css( 'margin-left', 0 ) .append( captionSide === 'top' ? caption : null ) .append( table.children('thead') ) ) ) ) .append( $(_div, { 'class': classes.sScrollBody } ) .css( { position: 'relative', overflow: 'auto', width: size( scrollX ) } ) .append( table ) ); if ( footer ) { scroller.append( $(_div, { 'class': classes.sScrollFoot } ) .css( { overflow: 'hidden', border: 0, width: scrollX ? size(scrollX) : '100%' } ) .append( $(_div, { 'class': classes.sScrollFootInner } ) .append( footerClone .removeAttr('id') .css( 'margin-left', 0 ) .append( captionSide === 'bottom' ? caption : null ) .append( table.children('tfoot') ) ) ) ); } var children = scroller.children(); var scrollHead = children[0]; var scrollBody = children[1]; var scrollFoot = footer ? children[2] : null; // When the body is scrolled, then we also want to scroll the headers if ( scrollX ) { $(scrollBody).on( 'scroll.DT', function (e) { var scrollLeft = this.scrollLeft; scrollHead.scrollLeft = scrollLeft; if ( footer ) { scrollFoot.scrollLeft = scrollLeft; } } ); } $(scrollBody).css( scrollY && scroll.bCollapse ? 'max-height' : 'height', scrollY ); settings.nScrollHead = scrollHead; settings.nScrollBody = scrollBody; settings.nScrollFoot = scrollFoot; // On redraw - align columns settings.aoDrawCallback.push( { "fn": _fnScrollDraw, "sName": "scrolling" } ); return scroller[0]; } /** * Update the header, footer and body tables for resizing - i.e. column * alignment. * * Welcome to the most horrible function DataTables. The process that this * function follows is basically: * 1. Re-create the table inside the scrolling div * 2. Take live measurements from the DOM * 3. Apply the measurements to align the columns * 4. Clean up * * @param {object} settings dataTables settings object * @memberof DataTable#oApi */ function _fnScrollDraw ( settings ) { // Given that this is such a monster function, a lot of variables are use // to try and keep the minimised size as small as possible var scroll = settings.oScroll, scrollX = scroll.sX, scrollXInner = scroll.sXInner, scrollY = scroll.sY, barWidth = scroll.iBarWidth, divHeader = $(settings.nScrollHead), divHeaderStyle = divHeader[0].style, divHeaderInner = divHeader.children('div'), divHeaderInnerStyle = divHeaderInner[0].style, divHeaderTable = divHeaderInner.children('table'), divBodyEl = settings.nScrollBody, divBody = $(divBodyEl), divBodyStyle = divBodyEl.style, divFooter = $(settings.nScrollFoot), divFooterInner = divFooter.children('div'), divFooterTable = divFooterInner.children('table'), header = $(settings.nTHead), table = $(settings.nTable), tableEl = table[0], tableStyle = tableEl.style, footer = settings.nTFoot ? $(settings.nTFoot) : null, browser = settings.oBrowser, ie67 = browser.bScrollOversize, dtHeaderCells = _pluck( settings.aoColumns, 'nTh' ), headerTrgEls, footerTrgEls, headerSrcEls, footerSrcEls, headerCopy, footerCopy, headerWidths=[], footerWidths=[], headerContent=[], footerContent=[], idx, correction, sanityWidth, zeroOut = function(nSizer) { var style = nSizer.style; style.paddingTop = "0"; style.paddingBottom = "0"; style.borderTopWidth = "0"; style.borderBottomWidth = "0"; style.height = 0; }; // If the scrollbar visibility has changed from the last draw, we need to // adjust the column sizes as the table width will have changed to account // for the scrollbar var scrollBarVis = divBodyEl.scrollHeight > divBodyEl.clientHeight; if ( settings.scrollBarVis !== scrollBarVis && settings.scrollBarVis !== undefined ) { settings.scrollBarVis = scrollBarVis; _fnAdjustColumnSizing( settings ); return; // adjust column sizing will call this function again } else { settings.scrollBarVis = scrollBarVis; } /* * 1. Re-create the table inside the scrolling div */ // Remove the old minimised thead and tfoot elements in the inner table table.children('thead, tfoot').remove(); if ( footer ) { footerCopy = footer.clone().prependTo( table ); footerTrgEls = footer.find('tr'); // the original tfoot is in its own table and must be sized footerSrcEls = footerCopy.find('tr'); } // Clone the current header and footer elements and then place it into the inner table headerCopy = header.clone().prependTo( table ); headerTrgEls = header.find('tr'); // original header is in its own table headerSrcEls = headerCopy.find('tr'); headerCopy.find('th, td').removeAttr('tabindex'); /* * 2. Take live measurements from the DOM - do not alter the DOM itself! */ // Remove old sizing and apply the calculated column widths // Get the unique column headers in the newly created (cloned) header. We want to apply the // calculated sizes to this header if ( ! scrollX ) { divBodyStyle.width = '100%'; divHeader[0].style.width = '100%'; } $.each( _fnGetUniqueThs( settings, headerCopy ), function ( i, el ) { idx = _fnVisibleToColumnIndex( settings, i ); el.style.width = settings.aoColumns[idx].sWidth; } ); if ( footer ) { _fnApplyToChildren( function(n) { n.style.width = ""; }, footerSrcEls ); } // Size the table as a whole sanityWidth = table.outerWidth(); if ( scrollX === "" ) { // No x scrolling tableStyle.width = "100%"; // IE7 will make the width of the table when 100% include the scrollbar // - which is shouldn't. When there is a scrollbar we need to take this // into account. if ( ie67 && (table.find('tbody').height() > divBodyEl.offsetHeight || divBody.css('overflow-y') == "scroll") ) { tableStyle.width = _fnStringToCss( table.outerWidth() - barWidth); } // Recalculate the sanity width sanityWidth = table.outerWidth(); } else if ( scrollXInner !== "" ) { // legacy x scroll inner has been given - use it tableStyle.width = _fnStringToCss(scrollXInner); // Recalculate the sanity width sanityWidth = table.outerWidth(); } // Hidden header should have zero height, so remove padding and borders. Then // set the width based on the real headers // Apply all styles in one pass _fnApplyToChildren( zeroOut, headerSrcEls ); // Read all widths in next pass _fnApplyToChildren( function(nSizer) { headerContent.push( nSizer.innerHTML ); headerWidths.push( _fnStringToCss( $(nSizer).css('width') ) ); }, headerSrcEls ); // Apply all widths in final pass _fnApplyToChildren( function(nToSize, i) { // Only apply widths to the DataTables detected header cells - this // prevents complex headers from having contradictory sizes applied if ( $.inArray( nToSize, dtHeaderCells ) !== -1 ) { nToSize.style.width = headerWidths[i]; } }, headerTrgEls ); $(headerSrcEls).height(0); /* Same again with the footer if we have one */ if ( footer ) { _fnApplyToChildren( zeroOut, footerSrcEls ); _fnApplyToChildren( function(nSizer) { footerContent.push( nSizer.innerHTML ); footerWidths.push( _fnStringToCss( $(nSizer).css('width') ) ); }, footerSrcEls ); _fnApplyToChildren( function(nToSize, i) { nToSize.style.width = footerWidths[i]; }, footerTrgEls ); $(footerSrcEls).height(0); } /* * 3. Apply the measurements */ // "Hide" the header and footer that we used for the sizing. We need to keep // the content of the cell so that the width applied to the header and body // both match, but we want to hide it completely. We want to also fix their // width to what they currently are _fnApplyToChildren( function(nSizer, i) { nSizer.innerHTML = '<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+headerContent[i]+'</div>'; nSizer.style.width = headerWidths[i]; }, headerSrcEls ); if ( footer ) { _fnApplyToChildren( function(nSizer, i) { nSizer.innerHTML = '<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+footerContent[i]+'</div>'; nSizer.style.width = footerWidths[i]; }, footerSrcEls ); } // Sanity check that the table is of a sensible width. If not then we are going to get // misalignment - try to prevent this by not allowing the table to shrink below its min width if ( table.outerWidth() < sanityWidth ) { // The min width depends upon if we have a vertical scrollbar visible or not */ correction = ((divBodyEl.scrollHeight > divBodyEl.offsetHeight || divBody.css('overflow-y') == "scroll")) ? sanityWidth+barWidth : sanityWidth; // IE6/7 are a law unto themselves... if ( ie67 && (divBodyEl.scrollHeight > divBodyEl.offsetHeight || divBody.css('overflow-y') == "scroll") ) { tableStyle.width = _fnStringToCss( correction-barWidth ); } // And give the user a warning that we've stopped the table getting too small if ( scrollX === "" || scrollXInner !== "" ) { _fnLog( settings, 1, 'Possible column misalignment', 6 ); } } else { correction = '100%'; } // Apply to the container elements divBodyStyle.width = _fnStringToCss( correction ); divHeaderStyle.width = _fnStringToCss( correction ); if ( footer ) { settings.nScrollFoot.style.width = _fnStringToCss( correction ); } /* * 4. Clean up */ if ( ! scrollY ) { /* IE7< puts a vertical scrollbar in place (when it shouldn't be) due to subtracting * the scrollbar height from the visible display, rather than adding it on. We need to * set the height in order to sort this. Don't want to do it in any other browsers. */ if ( ie67 ) { divBodyStyle.height = _fnStringToCss( tableEl.offsetHeight+barWidth ); } } /* Finally set the width's of the header and footer tables */ var iOuterWidth = table.outerWidth(); divHeaderTable[0].style.width = _fnStringToCss( iOuterWidth ); divHeaderInnerStyle.width = _fnStringToCss( iOuterWidth ); // Figure out if there are scrollbar present - if so then we need a the header and footer to // provide a bit more space to allow "overflow" scrolling (i.e. past the scrollbar) var bScrolling = table.height() > divBodyEl.clientHeight || divBody.css('overflow-y') == "scroll"; var padding = 'padding' + (browser.bScrollbarLeft ? 'Left' : 'Right' ); divHeaderInnerStyle[ padding ] = bScrolling ? barWidth+"px" : "0px"; if ( footer ) { divFooterTable[0].style.width = _fnStringToCss( iOuterWidth ); divFooterInner[0].style.width = _fnStringToCss( iOuterWidth ); divFooterInner[0].style[padding] = bScrolling ? barWidth+"px" : "0px"; } // Correct DOM ordering for colgroup - comes before the thead table.children('colgroup').insertBefore( table.children('thead') ); /* Adjust the position of the header in case we loose the y-scrollbar */ divBody.scroll(); // If sorting or filtering has occurred, jump the scrolling back to the top // only if we aren't holding the position if ( (settings.bSorted || settings.bFiltered) && ! settings._drawHold ) { divBodyEl.scrollTop = 0; } } /** * Apply a given function to the display child nodes of an element array (typically * TD children of TR rows * @param {function} fn Method to apply to the objects * @param array {nodes} an1 List of elements to look through for display children * @param array {nodes} an2 Another list (identical structure to the first) - optional * @memberof DataTable#oApi */ function _fnApplyToChildren( fn, an1, an2 ) { var index=0, i=0, iLen=an1.length; var nNode1, nNode2; while ( i < iLen ) { nNode1 = an1[i].firstChild; nNode2 = an2 ? an2[i].firstChild : null; while ( nNode1 ) { if ( nNode1.nodeType === 1 ) { if ( an2 ) { fn( nNode1, nNode2, index ); } else { fn( nNode1, index ); } index++; } nNode1 = nNode1.nextSibling; nNode2 = an2 ? nNode2.nextSibling : null; } i++; } } var __re_html_remove = /<.*?>/g; /** * Calculate the width of columns for the table * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnCalculateColumnWidths ( oSettings ) { var table = oSettings.nTable, columns = oSettings.aoColumns, scroll = oSettings.oScroll, scrollY = scroll.sY, scrollX = scroll.sX, scrollXInner = scroll.sXInner, columnCount = columns.length, visibleColumns = _fnGetColumns( oSettings, 'bVisible' ), headerCells = $('th', oSettings.nTHead), tableWidthAttr = table.getAttribute('width'), // from DOM element tableContainer = table.parentNode, userInputs = false, i, column, columnIdx, width, outerWidth, browser = oSettings.oBrowser, ie67 = browser.bScrollOversize; var styleWidth = table.style.width; if ( styleWidth && styleWidth.indexOf('%') !== -1 ) { tableWidthAttr = styleWidth; } /* Convert any user input sizes into pixel sizes */ for ( i=0 ; i<visibleColumns.length ; i++ ) { column = columns[ visibleColumns[i] ]; if ( column.sWidth !== null ) { column.sWidth = _fnConvertToWidth( column.sWidthOrig, tableContainer ); userInputs = true; } } /* If the number of columns in the DOM equals the number that we have to * process in DataTables, then we can use the offsets that are created by * the web- browser. No custom sizes can be set in order for this to happen, * nor scrolling used */ if ( ie67 || ! userInputs && ! scrollX && ! scrollY && columnCount == _fnVisbleColumns( oSettings ) && columnCount == headerCells.length ) { for ( i=0 ; i<columnCount ; i++ ) { var colIdx = _fnVisibleToColumnIndex( oSettings, i ); if ( colIdx !== null ) { columns[ colIdx ].sWidth = _fnStringToCss( headerCells.eq(i).width() ); } } } else { // Otherwise construct a single row, worst case, table with the widest // node in the data, assign any user defined widths, then insert it into // the DOM and allow the browser to do all the hard work of calculating // table widths var tmpTable = $(table).clone() // don't use cloneNode - IE8 will remove events on the main table .css( 'visibility', 'hidden' ) .removeAttr( 'id' ); // Clean up the table body tmpTable.find('tbody tr').remove(); var tr = $('<tr/>').appendTo( tmpTable.find('tbody') ); // Clone the table header and footer - we can't use the header / footer // from the cloned table, since if scrolling is active, the table's // real header and footer are contained in different table tags tmpTable.find('thead, tfoot').remove(); tmpTable .append( $(oSettings.nTHead).clone() ) .append( $(oSettings.nTFoot).clone() ); // Remove any assigned widths from the footer (from scrolling) tmpTable.find('tfoot th, tfoot td').css('width', ''); // Apply custom sizing to the cloned header headerCells = _fnGetUniqueThs( oSettings, tmpTable.find('thead')[0] ); for ( i=0 ; i<visibleColumns.length ; i++ ) { column = columns[ visibleColumns[i] ]; headerCells[i].style.width = column.sWidthOrig !== null && column.sWidthOrig !== '' ? _fnStringToCss( column.sWidthOrig ) : ''; // For scrollX we need to force the column width otherwise the // browser will collapse it. If this width is smaller than the // width the column requires, then it will have no effect if ( column.sWidthOrig && scrollX ) { $( headerCells[i] ).append( $('<div/>').css( { width: column.sWidthOrig, margin: 0, padding: 0, border: 0, height: 1 } ) ); } } // Find the widest cell for each column and put it into the table if ( oSettings.aoData.length ) { for ( i=0 ; i<visibleColumns.length ; i++ ) { columnIdx = visibleColumns[i]; column = columns[ columnIdx ]; $( _fnGetWidestNode( oSettings, columnIdx ) ) .clone( false ) .append( column.sContentPadding ) .appendTo( tr ); } } // Tidy the temporary table - remove name attributes so there aren't // duplicated in the dom (radio elements for example) $('[name]', tmpTable).removeAttr('name'); // Table has been built, attach to the document so we can work with it. // A holding element is used, positioned at the top of the container // with minimal height, so it has no effect on if the container scrolls // or not. Otherwise it might trigger scrolling when it actually isn't // needed var holder = $('<div/>').css( scrollX || scrollY ? { position: 'absolute', top: 0, left: 0, height: 1, right: 0, overflow: 'hidden' } : {} ) .append( tmpTable ) .appendTo( tableContainer ); // When scrolling (X or Y) we want to set the width of the table as // appropriate. However, when not scrolling leave the table width as it // is. This results in slightly different, but I think correct behaviour if ( scrollX && scrollXInner ) { tmpTable.width( scrollXInner ); } else if ( scrollX ) { tmpTable.css( 'width', 'auto' ); tmpTable.removeAttr('width'); // If there is no width attribute or style, then allow the table to // collapse if ( tmpTable.width() < tableContainer.clientWidth && tableWidthAttr ) { tmpTable.width( tableContainer.clientWidth ); } } else if ( scrollY ) { tmpTable.width( tableContainer.clientWidth ); } else if ( tableWidthAttr ) { tmpTable.width( tableWidthAttr ); } // Get the width of each column in the constructed table - we need to // know the inner width (so it can be assigned to the other table's // cells) and the outer width so we can calculate the full width of the // table. This is safe since DataTables requires a unique cell for each // column, but if ever a header can span multiple columns, this will // need to be modified. var total = 0; for ( i=0 ; i<visibleColumns.length ; i++ ) { var cell = $(headerCells[i]); var border = cell.outerWidth() - cell.width(); // Use getBounding... where possible (not IE8-) because it can give // sub-pixel accuracy, which we then want to round up! var bounding = browser.bBounding ? Math.ceil( headerCells[i].getBoundingClientRect().width ) : cell.outerWidth(); // Total is tracked to remove any sub-pixel errors as the outerWidth // of the table might not equal the total given here (IE!). total += bounding; // Width for each column to use columns[ visibleColumns[i] ].sWidth = _fnStringToCss( bounding - border ); } table.style.width = _fnStringToCss( total ); // Finished with the table - ditch it holder.remove(); } // If there is a width attr, we want to attach an event listener which // allows the table sizing to automatically adjust when the window is // resized. Use the width attr rather than CSS, since we can't know if the // CSS is a relative value or absolute - DOM read is always px. if ( tableWidthAttr ) { table.style.width = _fnStringToCss( tableWidthAttr ); } if ( (tableWidthAttr || scrollX) && ! oSettings._reszEvt ) { var bindResize = function () { $(window).on('resize.DT-'+oSettings.sInstance, _fnThrottle( function () { _fnAdjustColumnSizing( oSettings ); } ) ); }; // IE6/7 will crash if we bind a resize event handler on page load. // To be removed in 1.11 which drops IE6/7 support if ( ie67 ) { setTimeout( bindResize, 1000 ); } else { bindResize(); } oSettings._reszEvt = true; } } /** * Throttle the calls to a function. Arguments and context are maintained for * the throttled function * @param {function} fn Function to be called * @param {int} [freq=200] call frequency in mS * @returns {function} wrapped function * @memberof DataTable#oApi */ var _fnThrottle = DataTable.util.throttle; /** * Convert a CSS unit width to pixels (e.g. 2em) * @param {string} width width to be converted * @param {node} parent parent to get the with for (required for relative widths) - optional * @returns {int} width in pixels * @memberof DataTable#oApi */ function _fnConvertToWidth ( width, parent ) { if ( ! width ) { return 0; } var n = $('<div/>') .css( 'width', _fnStringToCss( width ) ) .appendTo( parent || document.body ); var val = n[0].offsetWidth; n.remove(); return val; } /** * Get the widest node * @param {object} settings dataTables settings object * @param {int} colIdx column of interest * @returns {node} widest table node * @memberof DataTable#oApi */ function _fnGetWidestNode( settings, colIdx ) { var idx = _fnGetMaxLenString( settings, colIdx ); if ( idx < 0 ) { return null; } var data = settings.aoData[ idx ]; return ! data.nTr ? // Might not have been created when deferred rendering $('<td/>').html( _fnGetCellData( settings, idx, colIdx, 'display' ) )[0] : data.anCells[ colIdx ]; } /** * Get the maximum strlen for each data column * @param {object} settings dataTables settings object * @param {int} colIdx column of interest * @returns {string} max string length for each column * @memberof DataTable#oApi */ function _fnGetMaxLenString( settings, colIdx ) { var s, max=-1, maxIdx = -1; for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) { s = _fnGetCellData( settings, i, colIdx, 'display' )+''; s = s.replace( __re_html_remove, '' ); s = s.replace( /&nbsp;/g, ' ' ); if ( s.length > max ) { max = s.length; maxIdx = i; } } return maxIdx; } /** * Append a CSS unit (only if required) to a string * @param {string} value to css-ify * @returns {string} value with css unit * @memberof DataTable#oApi */ function _fnStringToCss( s ) { if ( s === null ) { return '0px'; } if ( typeof s == 'number' ) { return s < 0 ? '0px' : s+'px'; } // Check it has a unit character already return s.match(/\d$/) ? s+'px' : s; } function _fnSortFlatten ( settings ) { var i, iLen, k, kLen, aSort = [], aiOrig = [], aoColumns = settings.aoColumns, aDataSort, iCol, sType, srcCol, fixed = settings.aaSortingFixed, fixedObj = $.isPlainObject( fixed ), nestedSort = [], add = function ( a ) { if ( a.length && ! $.isArray( a[0] ) ) { // 1D array nestedSort.push( a ); } else { // 2D array $.merge( nestedSort, a ); } }; // Build the sort array, with pre-fix and post-fix options if they have been // specified if ( $.isArray( fixed ) ) { add( fixed ); } if ( fixedObj && fixed.pre ) { add( fixed.pre ); } add( settings.aaSorting ); if (fixedObj && fixed.post ) { add( fixed.post ); } for ( i=0 ; i<nestedSort.length ; i++ ) { srcCol = nestedSort[i][0]; aDataSort = aoColumns[ srcCol ].aDataSort; for ( k=0, kLen=aDataSort.length ; k<kLen ; k++ ) { iCol = aDataSort[k]; sType = aoColumns[ iCol ].sType || 'string'; if ( nestedSort[i]._idx === undefined ) { nestedSort[i]._idx = $.inArray( nestedSort[i][1], aoColumns[iCol].asSorting ); } aSort.push( { src: srcCol, col: iCol, dir: nestedSort[i][1], index: nestedSort[i]._idx, type: sType, formatter: DataTable.ext.type.order[ sType+"-pre" ] } ); } } return aSort; } /** * Change the order of the table * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi * @todo This really needs split up! */ function _fnSort ( oSettings ) { var i, ien, iLen, j, jLen, k, kLen, sDataType, nTh, aiOrig = [], oExtSort = DataTable.ext.type.order, aoData = oSettings.aoData, aoColumns = oSettings.aoColumns, aDataSort, data, iCol, sType, oSort, formatters = 0, sortCol, displayMaster = oSettings.aiDisplayMaster, aSort; // Resolve any column types that are unknown due to addition or invalidation // @todo Can this be moved into a 'data-ready' handler which is called when // data is going to be used in the table? _fnColumnTypes( oSettings ); aSort = _fnSortFlatten( oSettings ); for ( i=0, ien=aSort.length ; i<ien ; i++ ) { sortCol = aSort[i]; // Track if we can use the fast sort algorithm if ( sortCol.formatter ) { formatters++; } // Load the data needed for the sort, for each cell _fnSortData( oSettings, sortCol.col ); } /* No sorting required if server-side or no sorting array */ if ( _fnDataSource( oSettings ) != 'ssp' && aSort.length !== 0 ) { // Create a value - key array of the current row positions such that we can use their // current position during the sort, if values match, in order to perform stable sorting for ( i=0, iLen=displayMaster.length ; i<iLen ; i++ ) { aiOrig[ displayMaster[i] ] = i; } /* Do the sort - here we want multi-column sorting based on a given data source (column) * and sorting function (from oSort) in a certain direction. It's reasonably complex to * follow on it's own, but this is what we want (example two column sorting): * fnLocalSorting = function(a,b){ * var iTest; * iTest = oSort['string-asc']('data11', 'data12'); * if (iTest !== 0) * return iTest; * iTest = oSort['numeric-desc']('data21', 'data22'); * if (iTest !== 0) * return iTest; * return oSort['numeric-asc']( aiOrig[a], aiOrig[b] ); * } * Basically we have a test for each sorting column, if the data in that column is equal, * test the next column. If all columns match, then we use a numeric sort on the row * positions in the original data array to provide a stable sort. * * Note - I know it seems excessive to have two sorting methods, but the first is around * 15% faster, so the second is only maintained for backwards compatibility with sorting * methods which do not have a pre-sort formatting function. */ if ( formatters === aSort.length ) { // All sort types have formatting functions displayMaster.sort( function ( a, b ) { var x, y, k, test, sort, len=aSort.length, dataA = aoData[a]._aSortData, dataB = aoData[b]._aSortData; for ( k=0 ; k<len ; k++ ) { sort = aSort[k]; x = dataA[ sort.col ]; y = dataB[ sort.col ]; test = x<y ? -1 : x>y ? 1 : 0; if ( test !== 0 ) { return sort.dir === 'asc' ? test : -test; } } x = aiOrig[a]; y = aiOrig[b]; return x<y ? -1 : x>y ? 1 : 0; } ); } else { // Depreciated - remove in 1.11 (providing a plug-in option) // Not all sort types have formatting methods, so we have to call their sorting // methods. displayMaster.sort( function ( a, b ) { var x, y, k, l, test, sort, fn, len=aSort.length, dataA = aoData[a]._aSortData, dataB = aoData[b]._aSortData; for ( k=0 ; k<len ; k++ ) { sort = aSort[k]; x = dataA[ sort.col ]; y = dataB[ sort.col ]; fn = oExtSort[ sort.type+"-"+sort.dir ] || oExtSort[ "string-"+sort.dir ]; test = fn( x, y ); if ( test !== 0 ) { return test; } } x = aiOrig[a]; y = aiOrig[b]; return x<y ? -1 : x>y ? 1 : 0; } ); } } /* Tell the draw function that we have sorted the data */ oSettings.bSorted = true; } function _fnSortAria ( settings ) { var label; var nextSort; var columns = settings.aoColumns; var aSort = _fnSortFlatten( settings ); var oAria = settings.oLanguage.oAria; // ARIA attributes - need to loop all columns, to update all (removing old // attributes as needed) for ( var i=0, iLen=columns.length ; i<iLen ; i++ ) { var col = columns[i]; var asSorting = col.asSorting; var sTitle = col.sTitle.replace( /<.*?>/g, "" ); var th = col.nTh; // IE7 is throwing an error when setting these properties with jQuery's // attr() and removeAttr() methods... th.removeAttribute('aria-sort'); /* In ARIA only the first sorting column can be marked as sorting - no multi-sort option */ if ( col.bSortable ) { if ( aSort.length > 0 && aSort[0].col == i ) { th.setAttribute('aria-sort', aSort[0].dir=="asc" ? "ascending" : "descending" ); nextSort = asSorting[ aSort[0].index+1 ] || asSorting[0]; } else { nextSort = asSorting[0]; } label = sTitle + ( nextSort === "asc" ? oAria.sSortAscending : oAria.sSortDescending ); } else { label = sTitle; } th.setAttribute('aria-label', label); } } /** * Function to run on user sort request * @param {object} settings dataTables settings object * @param {node} attachTo node to attach the handler to * @param {int} colIdx column sorting index * @param {boolean} [append=false] Append the requested sort to the existing * sort if true (i.e. multi-column sort) * @param {function} [callback] callback function * @memberof DataTable#oApi */ function _fnSortListener ( settings, colIdx, append, callback ) { var col = settings.aoColumns[ colIdx ]; var sorting = settings.aaSorting; var asSorting = col.asSorting; var nextSortIdx; var next = function ( a, overflow ) { var idx = a._idx; if ( idx === undefined ) { idx = $.inArray( a[1], asSorting ); } return idx+1 < asSorting.length ? idx+1 : overflow ? null : 0; }; // Convert to 2D array if needed if ( typeof sorting[0] === 'number' ) { sorting = settings.aaSorting = [ sorting ]; } // If appending the sort then we are multi-column sorting if ( append && settings.oFeatures.bSortMulti ) { // Are we already doing some kind of sort on this column? var sortIdx = $.inArray( colIdx, _pluck(sorting, '0') ); if ( sortIdx !== -1 ) { // Yes, modify the sort nextSortIdx = next( sorting[sortIdx], true ); if ( nextSortIdx === null && sorting.length === 1 ) { nextSortIdx = 0; // can't remove sorting completely } if ( nextSortIdx === null ) { sorting.splice( sortIdx, 1 ); } else { sorting[sortIdx][1] = asSorting[ nextSortIdx ]; sorting[sortIdx]._idx = nextSortIdx; } } else { // No sort on this column yet sorting.push( [ colIdx, asSorting[0], 0 ] ); sorting[sorting.length-1]._idx = 0; } } else if ( sorting.length && sorting[0][0] == colIdx ) { // Single column - already sorting on this column, modify the sort nextSortIdx = next( sorting[0] ); sorting.length = 1; sorting[0][1] = asSorting[ nextSortIdx ]; sorting[0]._idx = nextSortIdx; } else { // Single column - sort only on this column sorting.length = 0; sorting.push( [ colIdx, asSorting[0] ] ); sorting[0]._idx = 0; } // Run the sort by calling a full redraw _fnReDraw( settings ); // callback used for async user interaction if ( typeof callback == 'function' ) { callback( settings ); } } /** * Attach a sort handler (click) to a node * @param {object} settings dataTables settings object * @param {node} attachTo node to attach the handler to * @param {int} colIdx column sorting index * @param {function} [callback] callback function * @memberof DataTable#oApi */ function _fnSortAttachListener ( settings, attachTo, colIdx, callback ) { var col = settings.aoColumns[ colIdx ]; _fnBindAction( attachTo, {}, function (e) { /* If the column is not sortable - don't to anything */ if ( col.bSortable === false ) { return; } // If processing is enabled use a timeout to allow the processing // display to be shown - otherwise to it synchronously if ( settings.oFeatures.bProcessing ) { _fnProcessingDisplay( settings, true ); setTimeout( function() { _fnSortListener( settings, colIdx, e.shiftKey, callback ); // In server-side processing, the draw callback will remove the // processing display if ( _fnDataSource( settings ) !== 'ssp' ) { _fnProcessingDisplay( settings, false ); } }, 0 ); } else { _fnSortListener( settings, colIdx, e.shiftKey, callback ); } } ); } /** * Set the sorting classes on table's body, Note: it is safe to call this function * when bSort and bSortClasses are false * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnSortingClasses( settings ) { var oldSort = settings.aLastSort; var sortClass = settings.oClasses.sSortColumn; var sort = _fnSortFlatten( settings ); var features = settings.oFeatures; var i, ien, colIdx; if ( features.bSort && features.bSortClasses ) { // Remove old sorting classes for ( i=0, ien=oldSort.length ; i<ien ; i++ ) { colIdx = oldSort[i].src; // Remove column sorting $( _pluck( settings.aoData, 'anCells', colIdx ) ) .removeClass( sortClass + (i<2 ? i+1 : 3) ); } // Add new column sorting for ( i=0, ien=sort.length ; i<ien ; i++ ) { colIdx = sort[i].src; $( _pluck( settings.aoData, 'anCells', colIdx ) ) .addClass( sortClass + (i<2 ? i+1 : 3) ); } } settings.aLastSort = sort; } // Get the data to sort a column, be it from cache, fresh (populating the // cache), or from a sort formatter function _fnSortData( settings, idx ) { // Custom sorting function - provided by the sort data type var column = settings.aoColumns[ idx ]; var customSort = DataTable.ext.order[ column.sSortDataType ]; var customData; if ( customSort ) { customData = customSort.call( settings.oInstance, settings, idx, _fnColumnIndexToVisible( settings, idx ) ); } // Use / populate cache var row, cellData; var formatter = DataTable.ext.type.order[ column.sType+"-pre" ]; for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) { row = settings.aoData[i]; if ( ! row._aSortData ) { row._aSortData = []; } if ( ! row._aSortData[idx] || customSort ) { cellData = customSort ? customData[i] : // If there was a custom sort function, use data from there _fnGetCellData( settings, i, idx, 'sort' ); row._aSortData[ idx ] = formatter ? formatter( cellData ) : cellData; } } } /** * Save the state of a table * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnSaveState ( settings ) { if ( !settings.oFeatures.bStateSave || settings.bDestroying ) { return; } /* Store the interesting variables */ var state = { time: +new Date(), start: settings._iDisplayStart, length: settings._iDisplayLength, order: $.extend( true, [], settings.aaSorting ), search: _fnSearchToCamel( settings.oPreviousSearch ), columns: $.map( settings.aoColumns, function ( col, i ) { return { visible: col.bVisible, search: _fnSearchToCamel( settings.aoPreSearchCols[i] ) }; } ) }; _fnCallbackFire( settings, "aoStateSaveParams", 'stateSaveParams', [settings, state] ); settings.oSavedState = state; settings.fnStateSaveCallback.call( settings.oInstance, settings, state ); } /** * Attempt to load a saved table state * @param {object} oSettings dataTables settings object * @param {object} oInit DataTables init object so we can override settings * @param {function} callback Callback to execute when the state has been loaded * @memberof DataTable#oApi */ function _fnLoadState ( settings, oInit, callback ) { var i, ien; var columns = settings.aoColumns; var loaded = function ( s ) { if ( ! s || ! s.time ) { callback(); return; } // Allow custom and plug-in manipulation functions to alter the saved data set and // cancelling of loading by returning false var abStateLoad = _fnCallbackFire( settings, 'aoStateLoadParams', 'stateLoadParams', [settings, s] ); if ( $.inArray( false, abStateLoad ) !== -1 ) { callback(); return; } // Reject old data var duration = settings.iStateDuration; if ( duration > 0 && s.time < +new Date() - (duration*1000) ) { callback(); return; } // Number of columns have changed - all bets are off, no restore of settings if ( s.columns && columns.length !== s.columns.length ) { callback(); return; } // Store the saved state so it might be accessed at any time settings.oLoadedState = $.extend( true, {}, s ); // Restore key features - todo - for 1.11 this needs to be done by // subscribed events if ( s.start !== undefined ) { settings._iDisplayStart = s.start; settings.iInitDisplayStart = s.start; } if ( s.length !== undefined ) { settings._iDisplayLength = s.length; } // Order if ( s.order !== undefined ) { settings.aaSorting = []; $.each( s.order, function ( i, col ) { settings.aaSorting.push( col[0] >= columns.length ? [ 0, col[1] ] : col ); } ); } // Search if ( s.search !== undefined ) { $.extend( settings.oPreviousSearch, _fnSearchToHung( s.search ) ); } // Columns // if ( s.columns ) { for ( i=0, ien=s.columns.length ; i<ien ; i++ ) { var col = s.columns[i]; // Visibility if ( col.visible !== undefined ) { columns[i].bVisible = col.visible; } // Search if ( col.search !== undefined ) { $.extend( settings.aoPreSearchCols[i], _fnSearchToHung( col.search ) ); } } } _fnCallbackFire( settings, 'aoStateLoaded', 'stateLoaded', [settings, s] ); callback(); } if ( ! settings.oFeatures.bStateSave ) { callback(); return; } var state = settings.fnStateLoadCallback.call( settings.oInstance, settings, loaded ); if ( state !== undefined ) { loaded( state ); } // otherwise, wait for the loaded callback to be executed } /** * Return the settings object for a particular table * @param {node} table table we are using as a dataTable * @returns {object} Settings object - or null if not found * @memberof DataTable#oApi */ function _fnSettingsFromNode ( table ) { var settings = DataTable.settings; var idx = $.inArray( table, _pluck( settings, 'nTable' ) ); return idx !== -1 ? settings[ idx ] : null; } /** * Log an error message * @param {object} settings dataTables settings object * @param {int} level log error messages, or display them to the user * @param {string} msg error message * @param {int} tn Technical note id to get more information about the error. * @memberof DataTable#oApi */ function _fnLog( settings, level, msg, tn ) { msg = 'DataTables warning: '+ (settings ? 'table id='+settings.sTableId+' - ' : '')+msg; if ( tn ) { msg += '. For more information about this error, please see '+ 'http://datatables.net/tn/'+tn; } if ( ! level ) { // Backwards compatibility pre 1.10 var ext = DataTable.ext; var type = ext.sErrMode || ext.errMode; if ( settings ) { _fnCallbackFire( settings, null, 'error', [ settings, tn, msg ] ); } /* if ( type == 'alert' ) { alert( msg ); }*/ else if ( type == 'throw' ) { throw new Error(msg); } else if ( typeof type == 'function' ) { type( settings, tn, msg ); } } else if ( window.console && console.log ) { console.log( msg ); } } /** * See if a property is defined on one object, if so assign it to the other object * @param {object} ret target object * @param {object} src source object * @param {string} name property * @param {string} [mappedName] name to map too - optional, name used if not given * @memberof DataTable#oApi */ function _fnMap( ret, src, name, mappedName ) { if ( $.isArray( name ) ) { $.each( name, function (i, val) { if ( $.isArray( val ) ) { _fnMap( ret, src, val[0], val[1] ); } else { _fnMap( ret, src, val ); } } ); return; } if ( mappedName === undefined ) { mappedName = name; } if ( src[name] !== undefined ) { ret[mappedName] = src[name]; } } /** * Extend objects - very similar to jQuery.extend, but deep copy objects, and * shallow copy arrays. The reason we need to do this, is that we don't want to * deep copy array init values (such as aaSorting) since the dev wouldn't be * able to override them, but we do want to deep copy arrays. * @param {object} out Object to extend * @param {object} extender Object from which the properties will be applied to * out * @param {boolean} breakRefs If true, then arrays will be sliced to take an * independent copy with the exception of the `data` or `aaData` parameters * if they are present. This is so you can pass in a collection to * DataTables and have that used as your data source without breaking the * references * @returns {object} out Reference, just for convenience - out === the return. * @memberof DataTable#oApi * @todo This doesn't take account of arrays inside the deep copied objects. */ function _fnExtend( out, extender, breakRefs ) { var val; for ( var prop in extender ) { if ( extender.hasOwnProperty(prop) ) { val = extender[prop]; if ( $.isPlainObject( val ) ) { if ( ! $.isPlainObject( out[prop] ) ) { out[prop] = {}; } $.extend( true, out[prop], val ); } else if ( breakRefs && prop !== 'data' && prop !== 'aaData' && $.isArray(val) ) { out[prop] = val.slice(); } else { out[prop] = val; } } } return out; } /** * Bind an event handers to allow a click or return key to activate the callback. * This is good for accessibility since a return on the keyboard will have the * same effect as a click, if the element has focus. * @param {element} n Element to bind the action to * @param {object} oData Data object to pass to the triggered function * @param {function} fn Callback function for when the event is triggered * @memberof DataTable#oApi */ function _fnBindAction( n, oData, fn ) { $(n) .on( 'click.DT', oData, function (e) { n.blur(); // Remove focus outline for mouse users fn(e); } ) .on( 'keypress.DT', oData, function (e){ if ( e.which === 13 ) { e.preventDefault(); fn(e); } } ) .on( 'selectstart.DT', function () { /* Take the brutal approach to cancelling text selection */ return false; } ); } /** * Register a callback function. Easily allows a callback function to be added to * an array store of callback functions that can then all be called together. * @param {object} oSettings dataTables settings object * @param {string} sStore Name of the array storage for the callbacks in oSettings * @param {function} fn Function to be called back * @param {string} sName Identifying name for the callback (i.e. a label) * @memberof DataTable#oApi */ function _fnCallbackReg( oSettings, sStore, fn, sName ) { if ( fn ) { oSettings[sStore].push( { "fn": fn, "sName": sName } ); } } /** * Fire callback functions and trigger events. Note that the loop over the * callback array store is done backwards! Further note that you do not want to * fire off triggers in time sensitive applications (for example cell creation) * as its slow. * @param {object} settings dataTables settings object * @param {string} callbackArr Name of the array storage for the callbacks in * oSettings * @param {string} eventName Name of the jQuery custom event to trigger. If * null no trigger is fired * @param {array} args Array of arguments to pass to the callback function / * trigger * @memberof DataTable#oApi */ function _fnCallbackFire( settings, callbackArr, eventName, args ) { var ret = []; if ( callbackArr ) { ret = $.map( settings[callbackArr].slice().reverse(), function (val, i) { return val.fn.apply( settings.oInstance, args ); } ); } if ( eventName !== null ) { var e = $.Event( eventName+'.dt' ); $(settings.nTable).trigger( e, args ); ret.push( e.result ); } return ret; } function _fnLengthOverflow ( settings ) { var start = settings._iDisplayStart, end = settings.fnDisplayEnd(), len = settings._iDisplayLength; /* If we have space to show extra rows (backing up from the end point - then do so */ if ( start >= end ) { start = end - len; } // Keep the start record on the current page start -= (start % len); if ( len === -1 || start < 0 ) { start = 0; } settings._iDisplayStart = start; } function _fnRenderer( settings, type ) { var renderer = settings.renderer; var host = DataTable.ext.renderer[type]; if ( $.isPlainObject( renderer ) && renderer[type] ) { // Specific renderer for this type. If available use it, otherwise use // the default. return host[renderer[type]] || host._; } else if ( typeof renderer === 'string' ) { // Common renderer - if there is one available for this type use it, // otherwise use the default return host[renderer] || host._; } // Use the default return host._; } /** * Detect the data source being used for the table. Used to simplify the code * a little (ajax) and to make it compress a little smaller. * * @param {object} settings dataTables settings object * @returns {string} Data source * @memberof DataTable#oApi */ function _fnDataSource ( settings ) { if ( settings.oFeatures.bServerSide ) { return 'ssp'; } else if ( settings.ajax || settings.sAjaxSource ) { return 'ajax'; } return 'dom'; } /** * Computed structure of the DataTables API, defined by the options passed to * `DataTable.Api.register()` when building the API. * * The structure is built in order to speed creation and extension of the Api * objects since the extensions are effectively pre-parsed. * * The array is an array of objects with the following structure, where this * base array represents the Api prototype base: * * [ * { * name: 'data' -- string - Property name * val: function () {}, -- function - Api method (or undefined if just an object * methodExt: [ ... ], -- array - Array of Api object definitions to extend the method result * propExt: [ ... ] -- array - Array of Api object definitions to extend the property * }, * { * name: 'row' * val: {}, * methodExt: [ ... ], * propExt: [ * { * name: 'data' * val: function () {}, * methodExt: [ ... ], * propExt: [ ... ] * }, * ... * ] * } * ] * * @type {Array} * @ignore */ var __apiStruct = []; /** * `Array.prototype` reference. * * @type object * @ignore */ var __arrayProto = Array.prototype; /** * Abstraction for `context` parameter of the `Api` constructor to allow it to * take several different forms for ease of use. * * Each of the input parameter types will be converted to a DataTables settings * object where possible. * * @param {string|node|jQuery|object} mixed DataTable identifier. Can be one * of: * * * `string` - jQuery selector. Any DataTables' matching the given selector * with be found and used. * * `node` - `TABLE` node which has already been formed into a DataTable. * * `jQuery` - A jQuery object of `TABLE` nodes. * * `object` - DataTables settings object * * `DataTables.Api` - API instance * @return {array|null} Matching DataTables settings objects. `null` or * `undefined` is returned if no matching DataTable is found. * @ignore */ var _toSettings = function ( mixed ) { var idx, jq; var settings = DataTable.settings; var tables = $.map( settings, function (el, i) { return el.nTable; } ); if ( ! mixed ) { return []; } else if ( mixed.nTable && mixed.oApi ) { // DataTables settings object return [ mixed ]; } else if ( mixed.nodeName && mixed.nodeName.toLowerCase() === 'table' ) { // Table node idx = $.inArray( mixed, tables ); return idx !== -1 ? [ settings[idx] ] : null; } else if ( mixed && typeof mixed.settings === 'function' ) { return mixed.settings().toArray(); } else if ( typeof mixed === 'string' ) { // jQuery selector jq = $(mixed); } else if ( mixed instanceof $ ) { // jQuery object (also DataTables instance) jq = mixed; } if ( jq ) { return jq.map( function(i) { idx = $.inArray( this, tables ); return idx !== -1 ? settings[idx] : null; } ).toArray(); } }; /** * DataTables API class - used to control and interface with one or more * DataTables enhanced tables. * * The API class is heavily based on jQuery, presenting a chainable interface * that you can use to interact with tables. Each instance of the API class has * a "context" - i.e. the tables that it will operate on. This could be a single * table, all tables on a page or a sub-set thereof. * * Additionally the API is designed to allow you to easily work with the data in * the tables, retrieving and manipulating it as required. This is done by * presenting the API class as an array like interface. The contents of the * array depend upon the actions requested by each method (for example * `rows().nodes()` will return an array of nodes, while `rows().data()` will * return an array of objects or arrays depending upon your table's * configuration). The API object has a number of array like methods (`push`, * `pop`, `reverse` etc) as well as additional helper methods (`each`, `pluck`, * `unique` etc) to assist your working with the data held in a table. * * Most methods (those which return an Api instance) are chainable, which means * the return from a method call also has all of the methods available that the * top level object had. For example, these two calls are equivalent: * * // Not chained * api.row.add( {...} ); * api.draw(); * * // Chained * api.row.add( {...} ).draw(); * * @class DataTable.Api * @param {array|object|string|jQuery} context DataTable identifier. This is * used to define which DataTables enhanced tables this API will operate on. * Can be one of: * * * `string` - jQuery selector. Any DataTables' matching the given selector * with be found and used. * * `node` - `TABLE` node which has already been formed into a DataTable. * * `jQuery` - A jQuery object of `TABLE` nodes. * * `object` - DataTables settings object * @param {array} [data] Data to initialise the Api instance with. * * @example * // Direct initialisation during DataTables construction * var api = $('#example').DataTable(); * * @example * // Initialisation using a DataTables jQuery object * var api = $('#example').dataTable().api(); * * @example * // Initialisation as a constructor * var api = new $.fn.DataTable.Api( 'table.dataTable' ); */ _Api = function ( context, data ) { if ( ! (this instanceof _Api) ) { return new _Api( context, data ); } var settings = []; var ctxSettings = function ( o ) { var a = _toSettings( o ); if ( a ) { settings = settings.concat( a ); } }; if ( $.isArray( context ) ) { for ( var i=0, ien=context.length ; i<ien ; i++ ) { ctxSettings( context[i] ); } } else { ctxSettings( context ); } // Remove duplicates this.context = _unique( settings ); // Initial data if ( data ) { $.merge( this, data ); } // selector this.selector = { rows: null, cols: null, opts: null }; _Api.extend( this, this, __apiStruct ); }; DataTable.Api = _Api; // Don't destroy the existing prototype, just extend it. Required for jQuery 2's // isPlainObject. $.extend( _Api.prototype, { any: function () { return this.count() !== 0; }, concat: __arrayProto.concat, context: [], // array of table settings objects count: function () { return this.flatten().length; }, each: function ( fn ) { for ( var i=0, ien=this.length ; i<ien; i++ ) { fn.call( this, this[i], i, this ); } return this; }, eq: function ( idx ) { var ctx = this.context; return ctx.length > idx ? new _Api( ctx[idx], this[idx] ) : null; }, filter: function ( fn ) { var a = []; if ( __arrayProto.filter ) { a = __arrayProto.filter.call( this, fn, this ); } else { // Compatibility for browsers without EMCA-252-5 (JS 1.6) for ( var i=0, ien=this.length ; i<ien ; i++ ) { if ( fn.call( this, this[i], i, this ) ) { a.push( this[i] ); } } } return new _Api( this.context, a ); }, flatten: function () { var a = []; return new _Api( this.context, a.concat.apply( a, this.toArray() ) ); }, join: __arrayProto.join, indexOf: __arrayProto.indexOf || function (obj, start) { for ( var i=(start || 0), ien=this.length ; i<ien ; i++ ) { if ( this[i] === obj ) { return i; } } return -1; }, iterator: function ( flatten, type, fn, alwaysNew ) { var a = [], ret, i, ien, j, jen, context = this.context, rows, items, item, selector = this.selector; // Argument shifting if ( typeof flatten === 'string' ) { alwaysNew = fn; fn = type; type = flatten; flatten = false; } for ( i=0, ien=context.length ; i<ien ; i++ ) { var apiInst = new _Api( context[i] ); if ( type === 'table' ) { ret = fn.call( apiInst, context[i], i ); if ( ret !== undefined ) { a.push( ret ); } } else if ( type === 'columns' || type === 'rows' ) { // this has same length as context - one entry for each table ret = fn.call( apiInst, context[i], this[i], i ); if ( ret !== undefined ) { a.push( ret ); } } else if ( type === 'column' || type === 'column-rows' || type === 'row' || type === 'cell' ) { // columns and rows share the same structure. // 'this' is an array of column indexes for each context items = this[i]; if ( type === 'column-rows' ) { rows = _selector_row_indexes( context[i], selector.opts ); } for ( j=0, jen=items.length ; j<jen ; j++ ) { item = items[j]; if ( type === 'cell' ) { ret = fn.call( apiInst, context[i], item.row, item.column, i, j ); } else { ret = fn.call( apiInst, context[i], item, i, j, rows ); } if ( ret !== undefined ) { a.push( ret ); } } } } if ( a.length || alwaysNew ) { var api = new _Api( context, flatten ? a.concat.apply( [], a ) : a ); var apiSelector = api.selector; apiSelector.rows = selector.rows; apiSelector.cols = selector.cols; apiSelector.opts = selector.opts; return api; } return this; }, lastIndexOf: __arrayProto.lastIndexOf || function (obj, start) { // Bit cheeky... return this.indexOf.apply( this.toArray.reverse(), arguments ); }, length: 0, map: function ( fn ) { var a = []; if ( __arrayProto.map ) { a = __arrayProto.map.call( this, fn, this ); } else { // Compatibility for browsers without EMCA-252-5 (JS 1.6) for ( var i=0, ien=this.length ; i<ien ; i++ ) { a.push( fn.call( this, this[i], i ) ); } } return new _Api( this.context, a ); }, pluck: function ( prop ) { return this.map( function ( el ) { return el[ prop ]; } ); }, pop: __arrayProto.pop, push: __arrayProto.push, // Does not return an API instance reduce: __arrayProto.reduce || function ( fn, init ) { return _fnReduce( this, fn, init, 0, this.length, 1 ); }, reduceRight: __arrayProto.reduceRight || function ( fn, init ) { return _fnReduce( this, fn, init, this.length-1, -1, -1 ); }, reverse: __arrayProto.reverse, // Object with rows, columns and opts selector: null, shift: __arrayProto.shift, slice: function () { return new _Api( this.context, this ); }, sort: __arrayProto.sort, // ? name - order? splice: __arrayProto.splice, toArray: function () { return __arrayProto.slice.call( this ); }, to$: function () { return $( this ); }, toJQuery: function () { return $( this ); }, unique: function () { return new _Api( this.context, _unique(this) ); }, unshift: __arrayProto.unshift } ); _Api.extend = function ( scope, obj, ext ) { // Only extend API instances and static properties of the API if ( ! ext.length || ! obj || ( ! (obj instanceof _Api) && ! obj.__dt_wrapper ) ) { return; } var i, ien, j, jen, struct, inner, methodScoping = function ( scope, fn, struc ) { return function () { var ret = fn.apply( scope, arguments ); // Method extension _Api.extend( ret, ret, struc.methodExt ); return ret; }; }; for ( i=0, ien=ext.length ; i<ien ; i++ ) { struct = ext[i]; // Value obj[ struct.name ] = typeof struct.val === 'function' ? methodScoping( scope, struct.val, struct ) : $.isPlainObject( struct.val ) ? {} : struct.val; obj[ struct.name ].__dt_wrapper = true; // Property extension _Api.extend( scope, obj[ struct.name ], struct.propExt ); } }; // @todo - Is there need for an augment function? // _Api.augment = function ( inst, name ) // { // // Find src object in the structure from the name // var parts = name.split('.'); // _Api.extend( inst, obj ); // }; // [ // { // name: 'data' -- string - Property name // val: function () {}, -- function - Api method (or undefined if just an object // methodExt: [ ... ], -- array - Array of Api object definitions to extend the method result // propExt: [ ... ] -- array - Array of Api object definitions to extend the property // }, // { // name: 'row' // val: {}, // methodExt: [ ... ], // propExt: [ // { // name: 'data' // val: function () {}, // methodExt: [ ... ], // propExt: [ ... ] // }, // ... // ] // } // ] _Api.register = _api_register = function ( name, val ) { if ( $.isArray( name ) ) { for ( var j=0, jen=name.length ; j<jen ; j++ ) { _Api.register( name[j], val ); } return; } var i, ien, heir = name.split('.'), struct = __apiStruct, key, method; var find = function ( src, name ) { for ( var i=0, ien=src.length ; i<ien ; i++ ) { if ( src[i].name === name ) { return src[i]; } } return null; }; for ( i=0, ien=heir.length ; i<ien ; i++ ) { method = heir[i].indexOf('()') !== -1; key = method ? heir[i].replace('()', '') : heir[i]; var src = find( struct, key ); if ( ! src ) { src = { name: key, val: {}, methodExt: [], propExt: [] }; struct.push( src ); } if ( i === ien-1 ) { src.val = val; } else { struct = method ? src.methodExt : src.propExt; } } }; _Api.registerPlural = _api_registerPlural = function ( pluralName, singularName, val ) { _Api.register( pluralName, val ); _Api.register( singularName, function () { var ret = val.apply( this, arguments ); if ( ret === this ) { // Returned item is the API instance that was passed in, return it return this; } else if ( ret instanceof _Api ) { // New API instance returned, want the value from the first item // in the returned array for the singular result. return ret.length ? $.isArray( ret[0] ) ? new _Api( ret.context, ret[0] ) : // Array results are 'enhanced' ret[0] : undefined; } // Non-API return - just fire it back return ret; } ); }; /** * Selector for HTML tables. Apply the given selector to the give array of * DataTables settings objects. * * @param {string|integer} [selector] jQuery selector string or integer * @param {array} Array of DataTables settings objects to be filtered * @return {array} * @ignore */ var __table_selector = function ( selector, a ) { // Integer is used to pick out a table by index if ( typeof selector === 'number' ) { return [ a[ selector ] ]; } // Perform a jQuery selector on the table nodes var nodes = $.map( a, function (el, i) { return el.nTable; } ); return $(nodes) .filter( selector ) .map( function (i) { // Need to translate back from the table node to the settings var idx = $.inArray( this, nodes ); return a[ idx ]; } ) .toArray(); }; /** * Context selector for the API's context (i.e. the tables the API instance * refers to. * * @name DataTable.Api#tables * @param {string|integer} [selector] Selector to pick which tables the iterator * should operate on. If not given, all tables in the current context are * used. This can be given as a jQuery selector (for example `':gt(0)'`) to * select multiple tables or as an integer to select a single table. * @returns {DataTable.Api} Returns a new API instance if a selector is given. */ _api_register( 'tables()', function ( selector ) { // A new instance is created if there was a selector specified return selector ? new _Api( __table_selector( selector, this.context ) ) : this; } ); _api_register( 'table()', function ( selector ) { var tables = this.tables( selector ); var ctx = tables.context; // Truncate to the first matched table return ctx.length ? new _Api( ctx[0] ) : tables; } ); _api_registerPlural( 'tables().nodes()', 'table().node()' , function () { return this.iterator( 'table', function ( ctx ) { return ctx.nTable; }, 1 ); } ); _api_registerPlural( 'tables().body()', 'table().body()' , function () { return this.iterator( 'table', function ( ctx ) { return ctx.nTBody; }, 1 ); } ); _api_registerPlural( 'tables().header()', 'table().header()' , function () { return this.iterator( 'table', function ( ctx ) { return ctx.nTHead; }, 1 ); } ); _api_registerPlural( 'tables().footer()', 'table().footer()' , function () { return this.iterator( 'table', function ( ctx ) { return ctx.nTFoot; }, 1 ); } ); _api_registerPlural( 'tables().containers()', 'table().container()' , function () { return this.iterator( 'table', function ( ctx ) { return ctx.nTableWrapper; }, 1 ); } ); /** * Redraw the tables in the current context. */ _api_register( 'draw()', function ( paging ) { return this.iterator( 'table', function ( settings ) { if ( paging === 'page' ) { _fnDraw( settings ); } else { if ( typeof paging === 'string' ) { paging = paging === 'full-hold' ? false : true; } _fnReDraw( settings, paging===false ); } } ); } ); /** * Get the current page index. * * @return {integer} Current page index (zero based) *//** * Set the current page. * * Note that if you attempt to show a page which does not exist, DataTables will * not throw an error, but rather reset the paging. * * @param {integer|string} action The paging action to take. This can be one of: * * `integer` - The page index to jump to * * `string` - An action to take: * * `first` - Jump to first page. * * `next` - Jump to the next page * * `previous` - Jump to previous page * * `last` - Jump to the last page. * @returns {DataTables.Api} this */ _api_register( 'page()', function ( action ) { if ( action === undefined ) { return this.page.info().page; // not an expensive call } // else, have an action to take on all tables return this.iterator( 'table', function ( settings ) { _fnPageChange( settings, action ); } ); } ); /** * Paging information for the first table in the current context. * * If you require paging information for another table, use the `table()` method * with a suitable selector. * * @return {object} Object with the following properties set: * * `page` - Current page index (zero based - i.e. the first page is `0`) * * `pages` - Total number of pages * * `start` - Display index for the first record shown on the current page * * `end` - Display index for the last record shown on the current page * * `length` - Display length (number of records). Note that generally `start * + length = end`, but this is not always true, for example if there are * only 2 records to show on the final page, with a length of 10. * * `recordsTotal` - Full data set length * * `recordsDisplay` - Data set length once the current filtering criterion * are applied. */ _api_register( 'page.info()', function ( action ) { if ( this.context.length === 0 ) { return undefined; } var settings = this.context[0], start = settings._iDisplayStart, len = settings.oFeatures.bPaginate ? settings._iDisplayLength : -1, visRecords = settings.fnRecordsDisplay(), all = len === -1; return { "page": all ? 0 : Math.floor( start / len ), "pages": all ? 1 : Math.ceil( visRecords / len ), "start": start, "end": settings.fnDisplayEnd(), "length": len, "recordsTotal": settings.fnRecordsTotal(), "recordsDisplay": visRecords, "serverSide": _fnDataSource( settings ) === 'ssp' }; } ); /** * Get the current page length. * * @return {integer} Current page length. Note `-1` indicates that all records * are to be shown. *//** * Set the current page length. * * @param {integer} Page length to set. Use `-1` to show all records. * @returns {DataTables.Api} this */ _api_register( 'page.len()', function ( len ) { // Note that we can't call this function 'length()' because `length` // is a Javascript property of functions which defines how many arguments // the function expects. if ( len === undefined ) { return this.context.length !== 0 ? this.context[0]._iDisplayLength : undefined; } // else, set the page length return this.iterator( 'table', function ( settings ) { _fnLengthChange( settings, len ); } ); } ); var __reload = function ( settings, holdPosition, callback ) { // Use the draw event to trigger a callback if ( callback ) { var api = new _Api( settings ); api.one( 'draw', function () { callback( api.ajax.json() ); } ); } if ( _fnDataSource( settings ) == 'ssp' ) { _fnReDraw( settings, holdPosition ); } else { _fnProcessingDisplay( settings, true ); // Cancel an existing request var xhr = settings.jqXHR; if ( xhr && xhr.readyState !== 4 ) { xhr.abort(); } // Trigger xhr _fnBuildAjax( settings, [], function( json ) { _fnClearTable( settings ); var data = _fnAjaxDataSrc( settings, json ); for ( var i=0, ien=data.length ; i<ien ; i++ ) { _fnAddData( settings, data[i] ); } _fnReDraw( settings, holdPosition ); _fnProcessingDisplay( settings, false ); } ); } }; /** * Get the JSON response from the last Ajax request that DataTables made to the * server. Note that this returns the JSON from the first table in the current * context. * * @return {object} JSON received from the server. */ _api_register( 'ajax.json()', function () { var ctx = this.context; if ( ctx.length > 0 ) { return ctx[0].json; } // else return undefined; } ); /** * Get the data submitted in the last Ajax request */ _api_register( 'ajax.params()', function () { var ctx = this.context; if ( ctx.length > 0 ) { return ctx[0].oAjaxData; } // else return undefined; } ); /** * Reload tables from the Ajax data source. Note that this function will * automatically re-draw the table when the remote data has been loaded. * * @param {boolean} [reset=true] Reset (default) or hold the current paging * position. A full re-sort and re-filter is performed when this method is * called, which is why the pagination reset is the default action. * @returns {DataTables.Api} this */ _api_register( 'ajax.reload()', function ( callback, resetPaging ) { return this.iterator( 'table', function (settings) { __reload( settings, resetPaging===false, callback ); } ); } ); /** * Get the current Ajax URL. Note that this returns the URL from the first * table in the current context. * * @return {string} Current Ajax source URL *//** * Set the Ajax URL. Note that this will set the URL for all tables in the * current context. * * @param {string} url URL to set. * @returns {DataTables.Api} this */ _api_register( 'ajax.url()', function ( url ) { var ctx = this.context; if ( url === undefined ) { // get if ( ctx.length === 0 ) { return undefined; } ctx = ctx[0]; return ctx.ajax ? $.isPlainObject( ctx.ajax ) ? ctx.ajax.url : ctx.ajax : ctx.sAjaxSource; } // set return this.iterator( 'table', function ( settings ) { if ( $.isPlainObject( settings.ajax ) ) { settings.ajax.url = url; } else { settings.ajax = url; } // No need to consider sAjaxSource here since DataTables gives priority // to `ajax` over `sAjaxSource`. So setting `ajax` here, renders any // value of `sAjaxSource` redundant. } ); } ); /** * Load data from the newly set Ajax URL. Note that this method is only * available when `ajax.url()` is used to set a URL. Additionally, this method * has the same effect as calling `ajax.reload()` but is provided for * convenience when setting a new URL. Like `ajax.reload()` it will * automatically redraw the table once the remote data has been loaded. * * @returns {DataTables.Api} this */ _api_register( 'ajax.url().load()', function ( callback, resetPaging ) { // Same as a reload, but makes sense to present it for easy access after a // url change return this.iterator( 'table', function ( ctx ) { __reload( ctx, resetPaging===false, callback ); } ); } ); var _selector_run = function ( type, selector, selectFn, settings, opts ) { var out = [], res, a, i, ien, j, jen, selectorType = typeof selector; // Can't just check for isArray here, as an API or jQuery instance might be // given with their array like look if ( ! selector || selectorType === 'string' || selectorType === 'function' || selector.length === undefined ) { selector = [ selector ]; } for ( i=0, ien=selector.length ; i<ien ; i++ ) { // Only split on simple strings - complex expressions will be jQuery selectors a = selector[i] && selector[i].split && ! selector[i].match(/[\[\(:]/) ? selector[i].split(',') : [ selector[i] ]; for ( j=0, jen=a.length ; j<jen ; j++ ) { res = selectFn( typeof a[j] === 'string' ? $.trim(a[j]) : a[j] ); if ( res && res.length ) { out = out.concat( res ); } } } // selector extensions var ext = _ext.selector[ type ]; if ( ext.length ) { for ( i=0, ien=ext.length ; i<ien ; i++ ) { out = ext[i]( settings, opts, out ); } } return _unique( out ); }; var _selector_opts = function ( opts ) { if ( ! opts ) { opts = {}; } // Backwards compatibility for 1.9- which used the terminology filter rather // than search if ( opts.filter && opts.search === undefined ) { opts.search = opts.filter; } return $.extend( { search: 'none', order: 'current', page: 'all' }, opts ); }; var _selector_first = function ( inst ) { // Reduce the API instance to the first item found for ( var i=0, ien=inst.length ; i<ien ; i++ ) { if ( inst[i].length > 0 ) { // Assign the first element to the first item in the instance // and truncate the instance and context inst[0] = inst[i]; inst[0].length = 1; inst.length = 1; inst.context = [ inst.context[i] ]; return inst; } } // Not found - return an empty instance inst.length = 0; return inst; }; var _selector_row_indexes = function ( settings, opts ) { var i, ien, tmp, a=[], displayFiltered = settings.aiDisplay, displayMaster = settings.aiDisplayMaster; var search = opts.search, // none, applied, removed order = opts.order, // applied, current, index (original - compatibility with 1.9) page = opts.page; // all, current if ( _fnDataSource( settings ) == 'ssp' ) { // In server-side processing mode, most options are irrelevant since // rows not shown don't exist and the index order is the applied order // Removed is a special case - for consistency just return an empty // array return search === 'removed' ? [] : _range( 0, displayMaster.length ); } else if ( page == 'current' ) { // Current page implies that order=current and fitler=applied, since it is // fairly senseless otherwise, regardless of what order and search actually // are for ( i=settings._iDisplayStart, ien=settings.fnDisplayEnd() ; i<ien ; i++ ) { a.push( displayFiltered[i] ); } } else if ( order == 'current' || order == 'applied' ) { a = search == 'none' ? displayMaster.slice() : // no search search == 'applied' ? displayFiltered.slice() : // applied search $.map( displayMaster, function (el, i) { // removed search return $.inArray( el, displayFiltered ) === -1 ? el : null; } ); } else if ( order == 'index' || order == 'original' ) { for ( i=0, ien=settings.aoData.length ; i<ien ; i++ ) { if ( search == 'none' ) { a.push( i ); } else { // applied | removed tmp = $.inArray( i, displayFiltered ); if ((tmp === -1 && search == 'removed') || (tmp >= 0 && search == 'applied') ) { a.push( i ); } } } } return a; }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Rows * * {} - no selector - use all available rows * {integer} - row aoData index * {node} - TR node * {string} - jQuery selector to apply to the TR elements * {array} - jQuery array of nodes, or simply an array of TR nodes * */ var __row_selector = function ( settings, selector, opts ) { var rows; var run = function ( sel ) { var selInt = _intVal( sel ); var i, ien; // Short cut - selector is a number and no options provided (default is // all records, so no need to check if the index is in there, since it // must be - dev error if the index doesn't exist). if ( selInt !== null && ! opts ) { return [ selInt ]; } if ( ! rows ) { rows = _selector_row_indexes( settings, opts ); } if ( selInt !== null && $.inArray( selInt, rows ) !== -1 ) { // Selector - integer return [ selInt ]; } else if ( sel === null || sel === undefined || sel === '' ) { // Selector - none return rows; } // Selector - function if ( typeof sel === 'function' ) { return $.map( rows, function (idx) { var row = settings.aoData[ idx ]; return sel( idx, row._aData, row.nTr ) ? idx : null; } ); } // Get nodes in the order from the `rows` array with null values removed var nodes = _removeEmpty( _pluck_order( settings.aoData, rows, 'nTr' ) ); // Selector - node if ( sel.nodeName ) { if ( sel._DT_RowIndex !== undefined ) { return [ sel._DT_RowIndex ]; // Property added by DT for fast lookup } else if ( sel._DT_CellIndex ) { return [ sel._DT_CellIndex.row ]; } else { var host = $(sel).closest('*[data-dt-row]'); return host.length ? [ host.data('dt-row') ] : []; } } // ID selector. Want to always be able to select rows by id, regardless // of if the tr element has been created or not, so can't rely upon // jQuery here - hence a custom implementation. This does not match // Sizzle's fast selector or HTML4 - in HTML5 the ID can be anything, // but to select it using a CSS selector engine (like Sizzle or // querySelect) it would need to need to be escaped for some characters. // DataTables simplifies this for row selectors since you can select // only a row. A # indicates an id any anything that follows is the id - // unescaped. if ( typeof sel === 'string' && sel.charAt(0) === '#' ) { // get row index from id var rowObj = settings.aIds[ sel.replace( /^#/, '' ) ]; if ( rowObj !== undefined ) { return [ rowObj.idx ]; } // need to fall through to jQuery in case there is DOM id that // matches } // Selector - jQuery selector string, array of nodes or jQuery object/ // As jQuery's .filter() allows jQuery objects to be passed in filter, // it also allows arrays, so this will cope with all three options return $(nodes) .filter( sel ) .map( function () { return this._DT_RowIndex; } ) .toArray(); }; return _selector_run( 'row', selector, run, settings, opts ); }; _api_register( 'rows()', function ( selector, opts ) { // argument shifting if ( selector === undefined ) { selector = ''; } else if ( $.isPlainObject( selector ) ) { opts = selector; selector = ''; } opts = _selector_opts( opts ); var inst = this.iterator( 'table', function ( settings ) { return __row_selector( settings, selector, opts ); }, 1 ); // Want argument shifting here and in __row_selector? inst.selector.rows = selector; inst.selector.opts = opts; return inst; } ); _api_register( 'rows().nodes()', function () { return this.iterator( 'row', function ( settings, row ) { return settings.aoData[ row ].nTr || undefined; }, 1 ); } ); _api_register( 'rows().data()', function () { return this.iterator( true, 'rows', function ( settings, rows ) { return _pluck_order( settings.aoData, rows, '_aData' ); }, 1 ); } ); _api_registerPlural( 'rows().cache()', 'row().cache()', function ( type ) { return this.iterator( 'row', function ( settings, row ) { var r = settings.aoData[ row ]; return type === 'search' ? r._aFilterData : r._aSortData; }, 1 ); } ); _api_registerPlural( 'rows().invalidate()', 'row().invalidate()', function ( src ) { return this.iterator( 'row', function ( settings, row ) { _fnInvalidate( settings, row, src ); } ); } ); _api_registerPlural( 'rows().indexes()', 'row().index()', function () { return this.iterator( 'row', function ( settings, row ) { return row; }, 1 ); } ); _api_registerPlural( 'rows().ids()', 'row().id()', function ( hash ) { var a = []; var context = this.context; // `iterator` will drop undefined values, but in this case we want them for ( var i=0, ien=context.length ; i<ien ; i++ ) { for ( var j=0, jen=this[i].length ; j<jen ; j++ ) { var id = context[i].rowIdFn( context[i].aoData[ this[i][j] ]._aData ); a.push( (hash === true ? '#' : '' )+ id ); } } return new _Api( context, a ); } ); _api_registerPlural( 'rows().remove()', 'row().remove()', function () { var that = this; this.iterator( 'row', function ( settings, row, thatIdx ) { var data = settings.aoData; var rowData = data[ row ]; var i, ien, j, jen; var loopRow, loopCells; data.splice( row, 1 ); // Update the cached indexes for ( i=0, ien=data.length ; i<ien ; i++ ) { loopRow = data[i]; loopCells = loopRow.anCells; // Rows if ( loopRow.nTr !== null ) { loopRow.nTr._DT_RowIndex = i; } // Cells if ( loopCells !== null ) { for ( j=0, jen=loopCells.length ; j<jen ; j++ ) { loopCells[j]._DT_CellIndex.row = i; } } } // Delete from the display arrays _fnDeleteIndex( settings.aiDisplayMaster, row ); _fnDeleteIndex( settings.aiDisplay, row ); _fnDeleteIndex( that[ thatIdx ], row, false ); // maintain local indexes // For server-side processing tables - subtract the deleted row from the count if ( settings._iRecordsDisplay > 0 ) { settings._iRecordsDisplay--; } // Check for an 'overflow' they case for displaying the table _fnLengthOverflow( settings ); // Remove the row's ID reference if there is one var id = settings.rowIdFn( rowData._aData ); if ( id !== undefined ) { delete settings.aIds[ id ]; } } ); this.iterator( 'table', function ( settings ) { for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) { settings.aoData[i].idx = i; } } ); return this; } ); _api_register( 'rows.add()', function ( rows ) { var newRows = this.iterator( 'table', function ( settings ) { var row, i, ien; var out = []; for ( i=0, ien=rows.length ; i<ien ; i++ ) { row = rows[i]; if ( row.nodeName && row.nodeName.toUpperCase() === 'TR' ) { out.push( _fnAddTr( settings, row )[0] ); } else { out.push( _fnAddData( settings, row ) ); } } return out; }, 1 ); // Return an Api.rows() extended instance, so rows().nodes() etc can be used var modRows = this.rows( -1 ); modRows.pop(); $.merge( modRows, newRows ); return modRows; } ); /** * */ _api_register( 'row()', function ( selector, opts ) { return _selector_first( this.rows( selector, opts ) ); } ); _api_register( 'row().data()', function ( data ) { var ctx = this.context; if ( data === undefined ) { // Get return ctx.length && this.length ? ctx[0].aoData[ this[0] ]._aData : undefined; } // Set ctx[0].aoData[ this[0] ]._aData = data; // Automatically invalidate _fnInvalidate( ctx[0], this[0], 'data' ); return this; } ); _api_register( 'row().node()', function () { var ctx = this.context; return ctx.length && this.length ? ctx[0].aoData[ this[0] ].nTr || null : null; } ); _api_register( 'row.add()', function ( row ) { // Allow a jQuery object to be passed in - only a single row is added from // it though - the first element in the set if ( row instanceof $ && row.length ) { row = row[0]; } var rows = this.iterator( 'table', function ( settings ) { if ( row.nodeName && row.nodeName.toUpperCase() === 'TR' ) { return _fnAddTr( settings, row )[0]; } return _fnAddData( settings, row ); } ); // Return an Api.rows() extended instance, with the newly added row selected return this.row( rows[0] ); } ); var __details_add = function ( ctx, row, data, klass ) { // Convert to array of TR elements var rows = []; var addRow = function ( r, k ) { // Recursion to allow for arrays of jQuery objects if ( $.isArray( r ) || r instanceof $ ) { for ( var i=0, ien=r.length ; i<ien ; i++ ) { addRow( r[i], k ); } return; } // If we get a TR element, then just add it directly - up to the dev // to add the correct number of columns etc if ( r.nodeName && r.nodeName.toLowerCase() === 'tr' ) { rows.push( r ); } else { // Otherwise create a row with a wrapper var created = $('<tr><td/></tr>').addClass( k ); $('td', created) .addClass( k ) .html( r ) [0].colSpan = _fnVisbleColumns( ctx ); rows.push( created[0] ); } }; addRow( data, klass ); if ( row._details ) { row._details.detach(); } row._details = $(rows); // If the children were already shown, that state should be retained if ( row._detailsShow ) { row._details.insertAfter( row.nTr ); } }; var __details_remove = function ( api, idx ) { var ctx = api.context; if ( ctx.length ) { var row = ctx[0].aoData[ idx !== undefined ? idx : api[0] ]; if ( row && row._details ) { row._details.remove(); row._detailsShow = undefined; row._details = undefined; } } }; var __details_display = function ( api, show ) { var ctx = api.context; if ( ctx.length && api.length ) { var row = ctx[0].aoData[ api[0] ]; if ( row._details ) { row._detailsShow = show; if ( show ) { row._details.insertAfter( row.nTr ); } else { row._details.detach(); } __details_events( ctx[0] ); } } }; var __details_events = function ( settings ) { var api = new _Api( settings ); var namespace = '.dt.DT_details'; var drawEvent = 'draw'+namespace; var colvisEvent = 'column-visibility'+namespace; var destroyEvent = 'destroy'+namespace; var data = settings.aoData; api.off( drawEvent +' '+ colvisEvent +' '+ destroyEvent ); if ( _pluck( data, '_details' ).length > 0 ) { // On each draw, insert the required elements into the document api.on( drawEvent, function ( e, ctx ) { if ( settings !== ctx ) { return; } api.rows( {page:'current'} ).eq(0).each( function (idx) { // Internal data grab var row = data[ idx ]; if ( row._detailsShow ) { row._details.insertAfter( row.nTr ); } } ); } ); // Column visibility change - update the colspan api.on( colvisEvent, function ( e, ctx, idx, vis ) { if ( settings !== ctx ) { return; } // Update the colspan for the details rows (note, only if it already has // a colspan) var row, visible = _fnVisbleColumns( ctx ); for ( var i=0, ien=data.length ; i<ien ; i++ ) { row = data[i]; if ( row._details ) { row._details.children('td[colspan]').attr('colspan', visible ); } } } ); // Table destroyed - nuke any child rows api.on( destroyEvent, function ( e, ctx ) { if ( settings !== ctx ) { return; } for ( var i=0, ien=data.length ; i<ien ; i++ ) { if ( data[i]._details ) { __details_remove( api, i ); } } } ); } }; // Strings for the method names to help minification var _emp = ''; var _child_obj = _emp+'row().child'; var _child_mth = _child_obj+'()'; // data can be: // tr // string // jQuery or array of any of the above _api_register( _child_mth, function ( data, klass ) { var ctx = this.context; if ( data === undefined ) { // get return ctx.length && this.length ? ctx[0].aoData[ this[0] ]._details : undefined; } else if ( data === true ) { // show this.child.show(); } else if ( data === false ) { // remove __details_remove( this ); } else if ( ctx.length && this.length ) { // set __details_add( ctx[0], ctx[0].aoData[ this[0] ], data, klass ); } return this; } ); _api_register( [ _child_obj+'.show()', _child_mth+'.show()' // only when `child()` was called with parameters (without ], function ( show ) { // it returns an object and this method is not executed) __details_display( this, true ); return this; } ); _api_register( [ _child_obj+'.hide()', _child_mth+'.hide()' // only when `child()` was called with parameters (without ], function () { // it returns an object and this method is not executed) __details_display( this, false ); return this; } ); _api_register( [ _child_obj+'.remove()', _child_mth+'.remove()' // only when `child()` was called with parameters (without ], function () { // it returns an object and this method is not executed) __details_remove( this ); return this; } ); _api_register( _child_obj+'.isShown()', function () { var ctx = this.context; if ( ctx.length && this.length ) { // _detailsShown as false or undefined will fall through to return false return ctx[0].aoData[ this[0] ]._detailsShow || false; } return false; } ); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Columns * * {integer} - column index (>=0 count from left, <0 count from right) * "{integer}:visIdx" - visible column index (i.e. translate to column index) (>=0 count from left, <0 count from right) * "{integer}:visible" - alias for {integer}:visIdx (>=0 count from left, <0 count from right) * "{string}:name" - column name * "{string}" - jQuery selector on column header nodes * */ // can be an array of these items, comma separated list, or an array of comma // separated lists var __re_column_selector = /^([^:]+):(name|visIdx|visible)$/; // r1 and r2 are redundant - but it means that the parameters match for the // iterator callback in columns().data() var __columnData = function ( settings, column, r1, r2, rows ) { var a = []; for ( var row=0, ien=rows.length ; row<ien ; row++ ) { a.push( _fnGetCellData( settings, rows[row], column ) ); } return a; }; var __column_selector = function ( settings, selector, opts ) { var columns = settings.aoColumns, names = _pluck( columns, 'sName' ), nodes = _pluck( columns, 'nTh' ); var run = function ( s ) { var selInt = _intVal( s ); // Selector - all if ( s === '' ) { return _range( columns.length ); } // Selector - index if ( selInt !== null ) { return [ selInt >= 0 ? selInt : // Count from left columns.length + selInt // Count from right (+ because its a negative value) ]; } // Selector = function if ( typeof s === 'function' ) { var rows = _selector_row_indexes( settings, opts ); return $.map( columns, function (col, idx) { return s( idx, __columnData( settings, idx, 0, 0, rows ), nodes[ idx ] ) ? idx : null; } ); } // jQuery or string selector var match = typeof s === 'string' ? s.match( __re_column_selector ) : ''; if ( match ) { switch( match[2] ) { case 'visIdx': case 'visible': var idx = parseInt( match[1], 10 ); // Visible index given, convert to column index if ( idx < 0 ) { // Counting from the right var visColumns = $.map( columns, function (col,i) { return col.bVisible ? i : null; } ); return [ visColumns[ visColumns.length + idx ] ]; } // Counting from the left return [ _fnVisibleToColumnIndex( settings, idx ) ]; case 'name': // match by name. `names` is column index complete and in order return $.map( names, function (name, i) { return name === match[1] ? i : null; } ); default: return []; } } // Cell in the table body if ( s.nodeName && s._DT_CellIndex ) { return [ s._DT_CellIndex.column ]; } // jQuery selector on the TH elements for the columns var jqResult = $( nodes ) .filter( s ) .map( function () { return $.inArray( this, nodes ); // `nodes` is column index complete and in order } ) .toArray(); if ( jqResult.length || ! s.nodeName ) { return jqResult; } // Otherwise a node which might have a `dt-column` data attribute, or be // a child or such an element var host = $(s).closest('*[data-dt-column]'); return host.length ? [ host.data('dt-column') ] : []; }; return _selector_run( 'column', selector, run, settings, opts ); }; var __setColumnVis = function ( settings, column, vis ) { var cols = settings.aoColumns, col = cols[ column ], data = settings.aoData, row, cells, i, ien, tr; // Get if ( vis === undefined ) { return col.bVisible; } // Set // No change if ( col.bVisible === vis ) { return; } if ( vis ) { // Insert column // Need to decide if we should use appendChild or insertBefore var insertBefore = $.inArray( true, _pluck(cols, 'bVisible'), column+1 ); for ( i=0, ien=data.length ; i<ien ; i++ ) { tr = data[i].nTr; cells = data[i].anCells; if ( tr ) { // insertBefore can act like appendChild if 2nd arg is null tr.insertBefore( cells[ column ], cells[ insertBefore ] || null ); } } } else { // Remove column $( _pluck( settings.aoData, 'anCells', column ) ).detach(); } // Common actions col.bVisible = vis; _fnDrawHead( settings, settings.aoHeader ); _fnDrawHead( settings, settings.aoFooter ); _fnSaveState( settings ); }; _api_register( 'columns()', function ( selector, opts ) { // argument shifting if ( selector === undefined ) { selector = ''; } else if ( $.isPlainObject( selector ) ) { opts = selector; selector = ''; } opts = _selector_opts( opts ); var inst = this.iterator( 'table', function ( settings ) { return __column_selector( settings, selector, opts ); }, 1 ); // Want argument shifting here and in _row_selector? inst.selector.cols = selector; inst.selector.opts = opts; return inst; } ); _api_registerPlural( 'columns().header()', 'column().header()', function ( selector, opts ) { return this.iterator( 'column', function ( settings, column ) { return settings.aoColumns[column].nTh; }, 1 ); } ); _api_registerPlural( 'columns().footer()', 'column().footer()', function ( selector, opts ) { return this.iterator( 'column', function ( settings, column ) { return settings.aoColumns[column].nTf; }, 1 ); } ); _api_registerPlural( 'columns().data()', 'column().data()', function () { return this.iterator( 'column-rows', __columnData, 1 ); } ); _api_registerPlural( 'columns().dataSrc()', 'column().dataSrc()', function () { return this.iterator( 'column', function ( settings, column ) { return settings.aoColumns[column].mData; }, 1 ); } ); _api_registerPlural( 'columns().cache()', 'column().cache()', function ( type ) { return this.iterator( 'column-rows', function ( settings, column, i, j, rows ) { return _pluck_order( settings.aoData, rows, type === 'search' ? '_aFilterData' : '_aSortData', column ); }, 1 ); } ); _api_registerPlural( 'columns().nodes()', 'column().nodes()', function () { return this.iterator( 'column-rows', function ( settings, column, i, j, rows ) { return _pluck_order( settings.aoData, rows, 'anCells', column ) ; }, 1 ); } ); _api_registerPlural( 'columns().visible()', 'column().visible()', function ( vis, calc ) { var ret = this.iterator( 'column', function ( settings, column ) { if ( vis === undefined ) { return settings.aoColumns[ column ].bVisible; } // else __setColumnVis( settings, column, vis ); } ); // Group the column visibility changes if ( vis !== undefined ) { // Second loop once the first is done for events this.iterator( 'column', function ( settings, column ) { _fnCallbackFire( settings, null, 'column-visibility', [settings, column, vis, calc] ); } ); if ( calc === undefined || calc ) { this.columns.adjust(); } } return ret; } ); _api_registerPlural( 'columns().indexes()', 'column().index()', function ( type ) { return this.iterator( 'column', function ( settings, column ) { return type === 'visible' ? _fnColumnIndexToVisible( settings, column ) : column; }, 1 ); } ); _api_register( 'columns.adjust()', function () { return this.iterator( 'table', function ( settings ) { _fnAdjustColumnSizing( settings ); }, 1 ); } ); _api_register( 'column.index()', function ( type, idx ) { if ( this.context.length !== 0 ) { var ctx = this.context[0]; if ( type === 'fromVisible' || type === 'toData' ) { return _fnVisibleToColumnIndex( ctx, idx ); } else if ( type === 'fromData' || type === 'toVisible' ) { return _fnColumnIndexToVisible( ctx, idx ); } } } ); _api_register( 'column()', function ( selector, opts ) { return _selector_first( this.columns( selector, opts ) ); } ); var __cell_selector = function ( settings, selector, opts ) { var data = settings.aoData; var rows = _selector_row_indexes( settings, opts ); var cells = _removeEmpty( _pluck_order( data, rows, 'anCells' ) ); var allCells = $( [].concat.apply([], cells) ); var row; var columns = settings.aoColumns.length; var a, i, ien, j, o, host; var run = function ( s ) { var fnSelector = typeof s === 'function'; if ( s === null || s === undefined || fnSelector ) { // All cells and function selectors a = []; for ( i=0, ien=rows.length ; i<ien ; i++ ) { row = rows[i]; for ( j=0 ; j<columns ; j++ ) { o = { row: row, column: j }; if ( fnSelector ) { // Selector - function host = data[ row ]; if ( s( o, _fnGetCellData(settings, row, j), host.anCells ? host.anCells[j] : null ) ) { a.push( o ); } } else { // Selector - all a.push( o ); } } } return a; } // Selector - index if ( $.isPlainObject( s ) ) { return [s]; } // Selector - jQuery filtered cells var jqResult = allCells .filter( s ) .map( function (i, el) { return { // use a new object, in case someone changes the values row: el._DT_CellIndex.row, column: el._DT_CellIndex.column }; } ) .toArray(); if ( jqResult.length || ! s.nodeName ) { return jqResult; } // Otherwise the selector is a node, and there is one last option - the // element might be a child of an element which has dt-row and dt-column // data attributes host = $(s).closest('*[data-dt-row]'); return host.length ? [ { row: host.data('dt-row'), column: host.data('dt-column') } ] : []; }; return _selector_run( 'cell', selector, run, settings, opts ); }; _api_register( 'cells()', function ( rowSelector, columnSelector, opts ) { // Argument shifting if ( $.isPlainObject( rowSelector ) ) { // Indexes if ( rowSelector.row === undefined ) { // Selector options in first parameter opts = rowSelector; rowSelector = null; } else { // Cell index objects in first parameter opts = columnSelector; columnSelector = null; } } if ( $.isPlainObject( columnSelector ) ) { opts = columnSelector; columnSelector = null; } // Cell selector if ( columnSelector === null || columnSelector === undefined ) { return this.iterator( 'table', function ( settings ) { return __cell_selector( settings, rowSelector, _selector_opts( opts ) ); } ); } // Row + column selector var columns = this.columns( columnSelector, opts ); var rows = this.rows( rowSelector, opts ); var a, i, ien, j, jen; var cells = this.iterator( 'table', function ( settings, idx ) { a = []; for ( i=0, ien=rows[idx].length ; i<ien ; i++ ) { for ( j=0, jen=columns[idx].length ; j<jen ; j++ ) { a.push( { row: rows[idx][i], column: columns[idx][j] } ); } } return a; }, 1 ); $.extend( cells.selector, { cols: columnSelector, rows: rowSelector, opts: opts } ); return cells; } ); _api_registerPlural( 'cells().nodes()', 'cell().node()', function () { return this.iterator( 'cell', function ( settings, row, column ) { var data = settings.aoData[ row ]; return data && data.anCells ? data.anCells[ column ] : undefined; }, 1 ); } ); _api_register( 'cells().data()', function () { return this.iterator( 'cell', function ( settings, row, column ) { return _fnGetCellData( settings, row, column ); }, 1 ); } ); _api_registerPlural( 'cells().cache()', 'cell().cache()', function ( type ) { type = type === 'search' ? '_aFilterData' : '_aSortData'; return this.iterator( 'cell', function ( settings, row, column ) { return settings.aoData[ row ][ type ][ column ]; }, 1 ); } ); _api_registerPlural( 'cells().render()', 'cell().render()', function ( type ) { return this.iterator( 'cell', function ( settings, row, column ) { return _fnGetCellData( settings, row, column, type ); }, 1 ); } ); _api_registerPlural( 'cells().indexes()', 'cell().index()', function () { return this.iterator( 'cell', function ( settings, row, column ) { return { row: row, column: column, columnVisible: _fnColumnIndexToVisible( settings, column ) }; }, 1 ); } ); _api_registerPlural( 'cells().invalidate()', 'cell().invalidate()', function ( src ) { return this.iterator( 'cell', function ( settings, row, column ) { _fnInvalidate( settings, row, src, column ); } ); } ); _api_register( 'cell()', function ( rowSelector, columnSelector, opts ) { return _selector_first( this.cells( rowSelector, columnSelector, opts ) ); } ); _api_register( 'cell().data()', function ( data ) { var ctx = this.context; var cell = this[0]; if ( data === undefined ) { // Get return ctx.length && cell.length ? _fnGetCellData( ctx[0], cell[0].row, cell[0].column ) : undefined; } // Set _fnSetCellData( ctx[0], cell[0].row, cell[0].column, data ); _fnInvalidate( ctx[0], cell[0].row, 'data', cell[0].column ); return this; } ); /** * Get current ordering (sorting) that has been applied to the table. * * @returns {array} 2D array containing the sorting information for the first * table in the current context. Each element in the parent array represents * a column being sorted upon (i.e. multi-sorting with two columns would have * 2 inner arrays). The inner arrays may have 2 or 3 elements. The first is * the column index that the sorting condition applies to, the second is the * direction of the sort (`desc` or `asc`) and, optionally, the third is the * index of the sorting order from the `column.sorting` initialisation array. *//** * Set the ordering for the table. * * @param {integer} order Column index to sort upon. * @param {string} direction Direction of the sort to be applied (`asc` or `desc`) * @returns {DataTables.Api} this *//** * Set the ordering for the table. * * @param {array} order 1D array of sorting information to be applied. * @param {array} [...] Optional additional sorting conditions * @returns {DataTables.Api} this *//** * Set the ordering for the table. * * @param {array} order 2D array of sorting information to be applied. * @returns {DataTables.Api} this */ _api_register( 'order()', function ( order, dir ) { var ctx = this.context; if ( order === undefined ) { // get return ctx.length !== 0 ? ctx[0].aaSorting : undefined; } // set if ( typeof order === 'number' ) { // Simple column / direction passed in order = [ [ order, dir ] ]; } else if ( order.length && ! $.isArray( order[0] ) ) { // Arguments passed in (list of 1D arrays) order = Array.prototype.slice.call( arguments ); } // otherwise a 2D array was passed in return this.iterator( 'table', function ( settings ) { settings.aaSorting = order.slice(); } ); } ); /** * Attach a sort listener to an element for a given column * * @param {node|jQuery|string} node Identifier for the element(s) to attach the * listener to. This can take the form of a single DOM node, a jQuery * collection of nodes or a jQuery selector which will identify the node(s). * @param {integer} column the column that a click on this node will sort on * @param {function} [callback] callback function when sort is run * @returns {DataTables.Api} this */ _api_register( 'order.listener()', function ( node, column, callback ) { return this.iterator( 'table', function ( settings ) { _fnSortAttachListener( settings, node, column, callback ); } ); } ); _api_register( 'order.fixed()', function ( set ) { if ( ! set ) { var ctx = this.context; var fixed = ctx.length ? ctx[0].aaSortingFixed : undefined; return $.isArray( fixed ) ? { pre: fixed } : fixed; } return this.iterator( 'table', function ( settings ) { settings.aaSortingFixed = $.extend( true, {}, set ); } ); } ); // Order by the selected column(s) _api_register( [ 'columns().order()', 'column().order()' ], function ( dir ) { var that = this; return this.iterator( 'table', function ( settings, i ) { var sort = []; $.each( that[i], function (j, col) { sort.push( [ col, dir ] ); } ); settings.aaSorting = sort; } ); } ); _api_register( 'search()', function ( input, regex, smart, caseInsen ) { var ctx = this.context; if ( input === undefined ) { // get return ctx.length !== 0 ? ctx[0].oPreviousSearch.sSearch : undefined; } // set return this.iterator( 'table', function ( settings ) { if ( ! settings.oFeatures.bFilter ) { return; } _fnFilterComplete( settings, $.extend( {}, settings.oPreviousSearch, { "sSearch": input+"", "bRegex": regex === null ? false : regex, "bSmart": smart === null ? true : smart, "bCaseInsensitive": caseInsen === null ? true : caseInsen } ), 1 ); } ); } ); _api_registerPlural( 'columns().search()', 'column().search()', function ( input, regex, smart, caseInsen ) { return this.iterator( 'column', function ( settings, column ) { var preSearch = settings.aoPreSearchCols; if ( input === undefined ) { // get return preSearch[ column ].sSearch; } // set if ( ! settings.oFeatures.bFilter ) { return; } $.extend( preSearch[ column ], { "sSearch": input+"", "bRegex": regex === null ? false : regex, "bSmart": smart === null ? true : smart, "bCaseInsensitive": caseInsen === null ? true : caseInsen } ); _fnFilterComplete( settings, settings.oPreviousSearch, 1 ); } ); } ); /* * State API methods */ _api_register( 'state()', function () { return this.context.length ? this.context[0].oSavedState : null; } ); _api_register( 'state.clear()', function () { return this.iterator( 'table', function ( settings ) { // Save an empty object settings.fnStateSaveCallback.call( settings.oInstance, settings, {} ); } ); } ); _api_register( 'state.loaded()', function () { return this.context.length ? this.context[0].oLoadedState : null; } ); _api_register( 'state.save()', function () { return this.iterator( 'table', function ( settings ) { _fnSaveState( settings ); } ); } ); /** * Provide a common method for plug-ins to check the version of DataTables being * used, in order to ensure compatibility. * * @param {string} version Version string to check for, in the format "X.Y.Z". * Note that the formats "X" and "X.Y" are also acceptable. * @returns {boolean} true if this version of DataTables is greater or equal to * the required version, or false if this version of DataTales is not * suitable * @static * @dtopt API-Static * * @example * alert( $.fn.dataTable.versionCheck( '1.9.0' ) ); */ DataTable.versionCheck = DataTable.fnVersionCheck = function( version ) { var aThis = DataTable.version.split('.'); var aThat = version.split('.'); var iThis, iThat; for ( var i=0, iLen=aThat.length ; i<iLen ; i++ ) { iThis = parseInt( aThis[i], 10 ) || 0; iThat = parseInt( aThat[i], 10 ) || 0; // Parts are the same, keep comparing if (iThis === iThat) { continue; } // Parts are different, return immediately return iThis > iThat; } return true; }; /** * Check if a `<table>` node is a DataTable table already or not. * * @param {node|jquery|string} table Table node, jQuery object or jQuery * selector for the table to test. Note that if more than more than one * table is passed on, only the first will be checked * @returns {boolean} true the table given is a DataTable, or false otherwise * @static * @dtopt API-Static * * @example * if ( ! $.fn.DataTable.isDataTable( '#example' ) ) { * $('#example').dataTable(); * } */ DataTable.isDataTable = DataTable.fnIsDataTable = function ( table ) { var t = $(table).get(0); var is = false; if ( table instanceof DataTable.Api ) { return true; } $.each( DataTable.settings, function (i, o) { var head = o.nScrollHead ? $('table', o.nScrollHead)[0] : null; var foot = o.nScrollFoot ? $('table', o.nScrollFoot)[0] : null; if ( o.nTable === t || head === t || foot === t ) { is = true; } } ); return is; }; /** * Get all DataTable tables that have been initialised - optionally you can * select to get only currently visible tables. * * @param {boolean} [visible=false] Flag to indicate if you want all (default) * or visible tables only. * @returns {array} Array of `table` nodes (not DataTable instances) which are * DataTables * @static * @dtopt API-Static * * @example * $.each( $.fn.dataTable.tables(true), function () { * $(table).DataTable().columns.adjust(); * } ); */ DataTable.tables = DataTable.fnTables = function ( visible ) { var api = false; if ( $.isPlainObject( visible ) ) { api = visible.api; visible = visible.visible; } var a = $.map( DataTable.settings, function (o) { if ( !visible || (visible && $(o.nTable).is(':visible')) ) { return o.nTable; } } ); return api ? new _Api( a ) : a; }; /** * Convert from camel case parameters to Hungarian notation. This is made public * for the extensions to provide the same ability as DataTables core to accept * either the 1.9 style Hungarian notation, or the 1.10+ style camelCase * parameters. * * @param {object} src The model object which holds all parameters that can be * mapped. * @param {object} user The object to convert from camel case to Hungarian. * @param {boolean} force When set to `true`, properties which already have a * Hungarian value in the `user` object will be overwritten. Otherwise they * won't be. */ DataTable.camelToHungarian = _fnCamelToHungarian; /** * */ _api_register( '$()', function ( selector, opts ) { var rows = this.rows( opts ).nodes(), // Get all rows jqRows = $(rows); return $( [].concat( jqRows.filter( selector ).toArray(), jqRows.find( selector ).toArray() ) ); } ); // jQuery functions to operate on the tables $.each( [ 'on', 'one', 'off' ], function (i, key) { _api_register( key+'()', function ( /* event, handler */ ) { var args = Array.prototype.slice.call(arguments); // Add the `dt` namespace automatically if it isn't already present args[0] = $.map( args[0].split( /\s/ ), function ( e ) { return ! e.match(/\.dt\b/) ? e+'.dt' : e; } ).join( ' ' ); var inst = $( this.tables().nodes() ); inst[key].apply( inst, args ); return this; } ); } ); _api_register( 'clear()', function () { return this.iterator( 'table', function ( settings ) { _fnClearTable( settings ); } ); } ); _api_register( 'settings()', function () { return new _Api( this.context, this.context ); } ); _api_register( 'init()', function () { var ctx = this.context; return ctx.length ? ctx[0].oInit : null; } ); _api_register( 'data()', function () { return this.iterator( 'table', function ( settings ) { return _pluck( settings.aoData, '_aData' ); } ).flatten(); } ); _api_register( 'destroy()', function ( remove ) { remove = remove || false; return this.iterator( 'table', function ( settings ) { var orig = settings.nTableWrapper.parentNode; var classes = settings.oClasses; var table = settings.nTable; var tbody = settings.nTBody; var thead = settings.nTHead; var tfoot = settings.nTFoot; var jqTable = $(table); var jqTbody = $(tbody); var jqWrapper = $(settings.nTableWrapper); var rows = $.map( settings.aoData, function (r) { return r.nTr; } ); var i, ien; // Flag to note that the table is currently being destroyed - no action // should be taken settings.bDestroying = true; // Fire off the destroy callbacks for plug-ins etc _fnCallbackFire( settings, "aoDestroyCallback", "destroy", [settings] ); // If not being removed from the document, make all columns visible if ( ! remove ) { new _Api( settings ).columns().visible( true ); } // Blitz all `DT` namespaced events (these are internal events, the // lowercase, `dt` events are user subscribed and they are responsible // for removing them jqWrapper.off('.DT').find(':not(tbody *)').off('.DT'); $(window).off('.DT-'+settings.sInstance); // When scrolling we had to break the table up - restore it if ( table != thead.parentNode ) { jqTable.children('thead').detach(); jqTable.append( thead ); } if ( tfoot && table != tfoot.parentNode ) { jqTable.children('tfoot').detach(); jqTable.append( tfoot ); } settings.aaSorting = []; settings.aaSortingFixed = []; _fnSortingClasses( settings ); $( rows ).removeClass( settings.asStripeClasses.join(' ') ); $('th, td', thead).removeClass( classes.sSortable+' '+ classes.sSortableAsc+' '+classes.sSortableDesc+' '+classes.sSortableNone ); // Add the TR elements back into the table in their original order jqTbody.children().detach(); jqTbody.append( rows ); // Remove the DataTables generated nodes, events and classes var removedMethod = remove ? 'remove' : 'detach'; jqTable[ removedMethod ](); jqWrapper[ removedMethod ](); // If we need to reattach the table to the document if ( ! remove && orig ) { // insertBefore acts like appendChild if !arg[1] orig.insertBefore( table, settings.nTableReinsertBefore ); // Restore the width of the original table - was read from the style property, // so we can restore directly to that jqTable .css( 'width', settings.sDestroyWidth ) .removeClass( classes.sTable ); // If the were originally stripe classes - then we add them back here. // Note this is not fool proof (for example if not all rows had stripe // classes - but it's a good effort without getting carried away ien = settings.asDestroyStripes.length; if ( ien ) { jqTbody.children().each( function (i) { $(this).addClass( settings.asDestroyStripes[i % ien] ); } ); } } /* Remove the settings object from the settings array */ var idx = $.inArray( settings, DataTable.settings ); if ( idx !== -1 ) { DataTable.settings.splice( idx, 1 ); } } ); } ); // Add the `every()` method for rows, columns and cells in a compact form $.each( [ 'column', 'row', 'cell' ], function ( i, type ) { _api_register( type+'s().every()', function ( fn ) { var opts = this.selector.opts; var api = this; return this.iterator( type, function ( settings, arg1, arg2, arg3, arg4 ) { // Rows and columns: // arg1 - index // arg2 - table counter // arg3 - loop counter // arg4 - undefined // Cells: // arg1 - row index // arg2 - column index // arg3 - table counter // arg4 - loop counter fn.call( api[ type ]( arg1, type==='cell' ? arg2 : opts, type==='cell' ? opts : undefined ), arg1, arg2, arg3, arg4 ); } ); } ); } ); // i18n method for extensions to be able to use the language object from the // DataTable _api_register( 'i18n()', function ( token, def, plural ) { var ctx = this.context[0]; var resolved = _fnGetObjectDataFn( token )( ctx.oLanguage ); if ( resolved === undefined ) { resolved = def; } if ( plural !== undefined && $.isPlainObject( resolved ) ) { resolved = resolved[ plural ] !== undefined ? resolved[ plural ] : resolved._; } return resolved.replace( '%d', plural ); // nb: plural might be undefined, } ); /** * Version string for plug-ins to check compatibility. Allowed format is * `a.b.c-d` where: a:int, b:int, c:int, d:string(dev|beta|alpha). `d` is used * only for non-release builds. See http://semver.org/ for more information. * @member * @type string * @default Version number */ DataTable.version = "1.10.16"; /** * Private data store, containing all of the settings objects that are * created for the tables on a given page. * * Note that the `DataTable.settings` object is aliased to * `jQuery.fn.dataTableExt` through which it may be accessed and * manipulated, or `jQuery.fn.dataTable.settings`. * @member * @type array * @default [] * @private */ DataTable.settings = []; /** * Object models container, for the various models that DataTables has * available to it. These models define the objects that are used to hold * the active state and configuration of the table. * @namespace */ DataTable.models = {}; /** * Template object for the way in which DataTables holds information about * search information for the global filter and individual column filters. * @namespace */ DataTable.models.oSearch = { /** * Flag to indicate if the filtering should be case insensitive or not * @type boolean * @default true */ "bCaseInsensitive": true, /** * Applied search term * @type string * @default <i>Empty string</i> */ "sSearch": "", /** * Flag to indicate if the search term should be interpreted as a * regular expression (true) or not (false) and therefore and special * regex characters escaped. * @type boolean * @default false */ "bRegex": false, /** * Flag to indicate if DataTables is to use its smart filtering or not. * @type boolean * @default true */ "bSmart": true }; /** * Template object for the way in which DataTables holds information about * each individual row. This is the object format used for the settings * aoData array. * @namespace */ DataTable.models.oRow = { /** * TR element for the row * @type node * @default null */ "nTr": null, /** * Array of TD elements for each row. This is null until the row has been * created. * @type array nodes * @default [] */ "anCells": null, /** * Data object from the original data source for the row. This is either * an array if using the traditional form of DataTables, or an object if * using mData options. The exact type will depend on the passed in * data from the data source, or will be an array if using DOM a data * source. * @type array|object * @default [] */ "_aData": [], /** * Sorting data cache - this array is ostensibly the same length as the * number of columns (although each index is generated only as it is * needed), and holds the data that is used for sorting each column in the * row. We do this cache generation at the start of the sort in order that * the formatting of the sort data need be done only once for each cell * per sort. This array should not be read from or written to by anything * other than the master sorting methods. * @type array * @default null * @private */ "_aSortData": null, /** * Per cell filtering data cache. As per the sort data cache, used to * increase the performance of the filtering in DataTables * @type array * @default null * @private */ "_aFilterData": null, /** * Filtering data cache. This is the same as the cell filtering cache, but * in this case a string rather than an array. This is easily computed with * a join on `_aFilterData`, but is provided as a cache so the join isn't * needed on every search (memory traded for performance) * @type array * @default null * @private */ "_sFilterRow": null, /** * Cache of the class name that DataTables has applied to the row, so we * can quickly look at this variable rather than needing to do a DOM check * on className for the nTr property. * @type string * @default <i>Empty string</i> * @private */ "_sRowStripe": "", /** * Denote if the original data source was from the DOM, or the data source * object. This is used for invalidating data, so DataTables can * automatically read data from the original source, unless uninstructed * otherwise. * @type string * @default null * @private */ "src": null, /** * Index in the aoData array. This saves an indexOf lookup when we have the * object, but want to know the index * @type integer * @default -1 * @private */ "idx": -1 }; /** * Template object for the column information object in DataTables. This object * is held in the settings aoColumns array and contains all the information that * DataTables needs about each individual column. * * Note that this object is related to {@link DataTable.defaults.column} * but this one is the internal data store for DataTables's cache of columns. * It should NOT be manipulated outside of DataTables. Any configuration should * be done through the initialisation options. * @namespace */ DataTable.models.oColumn = { /** * Column index. This could be worked out on-the-fly with $.inArray, but it * is faster to just hold it as a variable * @type integer * @default null */ "idx": null, /** * A list of the columns that sorting should occur on when this column * is sorted. That this property is an array allows multi-column sorting * to be defined for a column (for example first name / last name columns * would benefit from this). The values are integers pointing to the * columns to be sorted on (typically it will be a single integer pointing * at itself, but that doesn't need to be the case). * @type array */ "aDataSort": null, /** * Define the sorting directions that are applied to the column, in sequence * as the column is repeatedly sorted upon - i.e. the first value is used * as the sorting direction when the column if first sorted (clicked on). * Sort it again (click again) and it will move on to the next index. * Repeat until loop. * @type array */ "asSorting": null, /** * Flag to indicate if the column is searchable, and thus should be included * in the filtering or not. * @type boolean */ "bSearchable": null, /** * Flag to indicate if the column is sortable or not. * @type boolean */ "bSortable": null, /** * Flag to indicate if the column is currently visible in the table or not * @type boolean */ "bVisible": null, /** * Store for manual type assignment using the `column.type` option. This * is held in store so we can manipulate the column's `sType` property. * @type string * @default null * @private */ "_sManualType": null, /** * Flag to indicate if HTML5 data attributes should be used as the data * source for filtering or sorting. True is either are. * @type boolean * @default false * @private */ "_bAttrSrc": false, /** * Developer definable function that is called whenever a cell is created (Ajax source, * etc) or processed for input (DOM source). This can be used as a compliment to mRender * allowing you to modify the DOM element (add background colour for example) when the * element is available. * @type function * @param {element} nTd The TD node that has been created * @param {*} sData The Data for the cell * @param {array|object} oData The data for the whole row * @param {int} iRow The row index for the aoData data store * @default null */ "fnCreatedCell": null, /** * Function to get data from a cell in a column. You should <b>never</b> * access data directly through _aData internally in DataTables - always use * the method attached to this property. It allows mData to function as * required. This function is automatically assigned by the column * initialisation method * @type function * @param {array|object} oData The data array/object for the array * (i.e. aoData[]._aData) * @param {string} sSpecific The specific data type you want to get - * 'display', 'type' 'filter' 'sort' * @returns {*} The data for the cell from the given row's data * @default null */ "fnGetData": null, /** * Function to set data for a cell in the column. You should <b>never</b> * set the data directly to _aData internally in DataTables - always use * this method. It allows mData to function as required. This function * is automatically assigned by the column initialisation method * @type function * @param {array|object} oData The data array/object for the array * (i.e. aoData[]._aData) * @param {*} sValue Value to set * @default null */ "fnSetData": null, /** * Property to read the value for the cells in the column from the data * source array / object. If null, then the default content is used, if a * function is given then the return from the function is used. * @type function|int|string|null * @default null */ "mData": null, /** * Partner property to mData which is used (only when defined) to get * the data - i.e. it is basically the same as mData, but without the * 'set' option, and also the data fed to it is the result from mData. * This is the rendering method to match the data method of mData. * @type function|int|string|null * @default null */ "mRender": null, /** * Unique header TH/TD element for this column - this is what the sorting * listener is attached to (if sorting is enabled.) * @type node * @default null */ "nTh": null, /** * Unique footer TH/TD element for this column (if there is one). Not used * in DataTables as such, but can be used for plug-ins to reference the * footer for each column. * @type node * @default null */ "nTf": null, /** * The class to apply to all TD elements in the table's TBODY for the column * @type string * @default null */ "sClass": null, /** * When DataTables calculates the column widths to assign to each column, * it finds the longest string in each column and then constructs a * temporary table and reads the widths from that. The problem with this * is that "mmm" is much wider then "iiii", but the latter is a longer * string - thus the calculation can go wrong (doing it properly and putting * it into an DOM object and measuring that is horribly(!) slow). Thus as * a "work around" we provide this option. It will append its value to the * text that is found to be the longest string for the column - i.e. padding. * @type string */ "sContentPadding": null, /** * Allows a default value to be given for a column's data, and will be used * whenever a null data source is encountered (this can be because mData * is set to null, or because the data source itself is null). * @type string * @default null */ "sDefaultContent": null, /** * Name for the column, allowing reference to the column by name as well as * by index (needs a lookup to work by name). * @type string */ "sName": null, /** * Custom sorting data type - defines which of the available plug-ins in * afnSortData the custom sorting will use - if any is defined. * @type string * @default std */ "sSortDataType": 'std', /** * Class to be applied to the header element when sorting on this column * @type string * @default null */ "sSortingClass": null, /** * Class to be applied to the header element when sorting on this column - * when jQuery UI theming is used. * @type string * @default null */ "sSortingClassJUI": null, /** * Title of the column - what is seen in the TH element (nTh). * @type string */ "sTitle": null, /** * Column sorting and filtering type * @type string * @default null */ "sType": null, /** * Width of the column * @type string * @default null */ "sWidth": null, /** * Width of the column when it was first "encountered" * @type string * @default null */ "sWidthOrig": null }; /* * Developer note: The properties of the object below are given in Hungarian * notation, that was used as the interface for DataTables prior to v1.10, however * from v1.10 onwards the primary interface is camel case. In order to avoid * breaking backwards compatibility utterly with this change, the Hungarian * version is still, internally the primary interface, but is is not documented * - hence the @name tags in each doc comment. This allows a Javascript function * to create a map from Hungarian notation to camel case (going the other direction * would require each property to be listed, which would at around 3K to the size * of DataTables, while this method is about a 0.5K hit. * * Ultimately this does pave the way for Hungarian notation to be dropped * completely, but that is a massive amount of work and will break current * installs (therefore is on-hold until v2). */ /** * Initialisation options that can be given to DataTables at initialisation * time. * @namespace */ DataTable.defaults = { /** * An array of data to use for the table, passed in at initialisation which * will be used in preference to any data which is already in the DOM. This is * particularly useful for constructing tables purely in Javascript, for * example with a custom Ajax call. * @type array * @default null * * @dtopt Option * @name DataTable.defaults.data * * @example * // Using a 2D array data source * $(document).ready( function () { * $('#example').dataTable( { * "data": [ * ['Trident', 'Internet Explorer 4.0', 'Win 95+', 4, 'X'], * ['Trident', 'Internet Explorer 5.0', 'Win 95+', 5, 'C'], * ], * "columns": [ * { "title": "Engine" }, * { "title": "Browser" }, * { "title": "Platform" }, * { "title": "Version" }, * { "title": "Grade" } * ] * } ); * } ); * * @example * // Using an array of objects as a data source (`data`) * $(document).ready( function () { * $('#example').dataTable( { * "data": [ * { * "engine": "Trident", * "browser": "Internet Explorer 4.0", * "platform": "Win 95+", * "version": 4, * "grade": "X" * }, * { * "engine": "Trident", * "browser": "Internet Explorer 5.0", * "platform": "Win 95+", * "version": 5, * "grade": "C" * } * ], * "columns": [ * { "title": "Engine", "data": "engine" }, * { "title": "Browser", "data": "browser" }, * { "title": "Platform", "data": "platform" }, * { "title": "Version", "data": "version" }, * { "title": "Grade", "data": "grade" } * ] * } ); * } ); */ "aaData": null, /** * If ordering is enabled, then DataTables will perform a first pass sort on * initialisation. You can define which column(s) the sort is performed * upon, and the sorting direction, with this variable. The `sorting` array * should contain an array for each column to be sorted initially containing * the column's index and a direction string ('asc' or 'desc'). * @type array * @default [[0,'asc']] * * @dtopt Option * @name DataTable.defaults.order * * @example * // Sort by 3rd column first, and then 4th column * $(document).ready( function() { * $('#example').dataTable( { * "order": [[2,'asc'], [3,'desc']] * } ); * } ); * * // No initial sorting * $(document).ready( function() { * $('#example').dataTable( { * "order": [] * } ); * } ); */ "aaSorting": [[0,'asc']], /** * This parameter is basically identical to the `sorting` parameter, but * cannot be overridden by user interaction with the table. What this means * is that you could have a column (visible or hidden) which the sorting * will always be forced on first - any sorting after that (from the user) * will then be performed as required. This can be useful for grouping rows * together. * @type array * @default null * * @dtopt Option * @name DataTable.defaults.orderFixed * * @example * $(document).ready( function() { * $('#example').dataTable( { * "orderFixed": [[0,'asc']] * } ); * } ) */ "aaSortingFixed": [], /** * DataTables can be instructed to load data to display in the table from a * Ajax source. This option defines how that Ajax call is made and where to. * * The `ajax` property has three different modes of operation, depending on * how it is defined. These are: * * * `string` - Set the URL from where the data should be loaded from. * * `object` - Define properties for `jQuery.ajax`. * * `function` - Custom data get function * * `string` * -------- * * As a string, the `ajax` property simply defines the URL from which * DataTables will load data. * * `object` * -------- * * As an object, the parameters in the object are passed to * [jQuery.ajax](http://api.jquery.com/jQuery.ajax/) allowing fine control * of the Ajax request. DataTables has a number of default parameters which * you can override using this option. Please refer to the jQuery * documentation for a full description of the options available, although * the following parameters provide additional options in DataTables or * require special consideration: * * * `data` - As with jQuery, `data` can be provided as an object, but it * can also be used as a function to manipulate the data DataTables sends * to the server. The function takes a single parameter, an object of * parameters with the values that DataTables has readied for sending. An * object may be returned which will be merged into the DataTables * defaults, or you can add the items to the object that was passed in and * not return anything from the function. This supersedes `fnServerParams` * from DataTables 1.9-. * * * `dataSrc` - By default DataTables will look for the property `data` (or * `aaData` for compatibility with DataTables 1.9-) when obtaining data * from an Ajax source or for server-side processing - this parameter * allows that property to be changed. You can use Javascript dotted * object notation to get a data source for multiple levels of nesting, or * it my be used as a function. As a function it takes a single parameter, * the JSON returned from the server, which can be manipulated as * required, with the returned value being that used by DataTables as the * data source for the table. This supersedes `sAjaxDataProp` from * DataTables 1.9-. * * * `success` - Should not be overridden it is used internally in * DataTables. To manipulate / transform the data returned by the server * use `ajax.dataSrc`, or use `ajax` as a function (see below). * * `function` * ---------- * * As a function, making the Ajax call is left up to yourself allowing * complete control of the Ajax request. Indeed, if desired, a method other * than Ajax could be used to obtain the required data, such as Web storage * or an AIR database. * * The function is given four parameters and no return is required. The * parameters are: * * 1. _object_ - Data to send to the server * 2. _function_ - Callback function that must be executed when the required * data has been obtained. That data should be passed into the callback * as the only parameter * 3. _object_ - DataTables settings object for the table * * Note that this supersedes `fnServerData` from DataTables 1.9-. * * @type string|object|function * @default null * * @dtopt Option * @name DataTable.defaults.ajax * @since 1.10.0 * * @example * // Get JSON data from a file via Ajax. * // Note DataTables expects data in the form `{ data: [ ...data... ] }` by default). * $('#example').dataTable( { * "ajax": "data.json" * } ); * * @example * // Get JSON data from a file via Ajax, using `dataSrc` to change * // `data` to `tableData` (i.e. `{ tableData: [ ...data... ] }`) * $('#example').dataTable( { * "ajax": { * "url": "data.json", * "dataSrc": "tableData" * } * } ); * * @example * // Get JSON data from a file via Ajax, using `dataSrc` to read data * // from a plain array rather than an array in an object * $('#example').dataTable( { * "ajax": { * "url": "data.json", * "dataSrc": "" * } * } ); * * @example * // Manipulate the data returned from the server - add a link to data * // (note this can, should, be done using `render` for the column - this * // is just a simple example of how the data can be manipulated). * $('#example').dataTable( { * "ajax": { * "url": "data.json", * "dataSrc": function ( json ) { * for ( var i=0, ien=json.length ; i<ien ; i++ ) { * json[i][0] = '<a href="/message/'+json[i][0]+'>View message</a>'; * } * return json; * } * } * } ); * * @example * // Add data to the request * $('#example').dataTable( { * "ajax": { * "url": "data.json", * "data": function ( d ) { * return { * "extra_search": $('#extra').val() * }; * } * } * } ); * * @example * // Send request as POST * $('#example').dataTable( { * "ajax": { * "url": "data.json", * "type": "POST" * } * } ); * * @example * // Get the data from localStorage (could interface with a form for * // adding, editing and removing rows). * $('#example').dataTable( { * "ajax": function (data, callback, settings) { * callback( * JSON.parse( localStorage.getItem('dataTablesData') ) * ); * } * } ); */ "ajax": null, /** * This parameter allows you to readily specify the entries in the length drop * down menu that DataTables shows when pagination is enabled. It can be * either a 1D array of options which will be used for both the displayed * option and the value, or a 2D array which will use the array in the first * position as the value, and the array in the second position as the * displayed options (useful for language strings such as 'All'). * * Note that the `pageLength` property will be automatically set to the * first value given in this array, unless `pageLength` is also provided. * @type array * @default [ 10, 25, 50, 100 ] * * @dtopt Option * @name DataTable.defaults.lengthMenu * * @example * $(document).ready( function() { * $('#example').dataTable( { * "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]] * } ); * } ); */ "aLengthMenu": [ 10, 25, 50, 100 ], /** * The `columns` option in the initialisation parameter allows you to define * details about the way individual columns behave. For a full list of * column options that can be set, please see * {@link DataTable.defaults.column}. Note that if you use `columns` to * define your columns, you must have an entry in the array for every single * column that you have in your table (these can be null if you don't which * to specify any options). * @member * * @name DataTable.defaults.column */ "aoColumns": null, /** * Very similar to `columns`, `columnDefs` allows you to target a specific * column, multiple columns, or all columns, using the `targets` property of * each object in the array. This allows great flexibility when creating * tables, as the `columnDefs` arrays can be of any length, targeting the * columns you specifically want. `columnDefs` may use any of the column * options available: {@link DataTable.defaults.column}, but it _must_ * have `targets` defined in each object in the array. Values in the `targets` * array may be: * <ul> * <li>a string - class name will be matched on the TH for the column</li> * <li>0 or a positive integer - column index counting from the left</li> * <li>a negative integer - column index counting from the right</li> * <li>the string "_all" - all columns (i.e. assign a default)</li> * </ul> * @member * * @name DataTable.defaults.columnDefs */ "aoColumnDefs": null, /** * Basically the same as `search`, this parameter defines the individual column * filtering state at initialisation time. The array must be of the same size * as the number of columns, and each element be an object with the parameters * `search` and `escapeRegex` (the latter is optional). 'null' is also * accepted and the default will be used. * @type array * @default [] * * @dtopt Option * @name DataTable.defaults.searchCols * * @example * $(document).ready( function() { * $('#example').dataTable( { * "searchCols": [ * null, * { "search": "My filter" }, * null, * { "search": "^[0-9]", "escapeRegex": false } * ] * } ); * } ) */ "aoSearchCols": [], /** * An array of CSS classes that should be applied to displayed rows. This * array may be of any length, and DataTables will apply each class * sequentially, looping when required. * @type array * @default null <i>Will take the values determined by the `oClasses.stripe*` * options</i> * * @dtopt Option * @name DataTable.defaults.stripeClasses * * @example * $(document).ready( function() { * $('#example').dataTable( { * "stripeClasses": [ 'strip1', 'strip2', 'strip3' ] * } ); * } ) */ "asStripeClasses": null, /** * Enable or disable automatic column width calculation. This can be disabled * as an optimisation (it takes some time to calculate the widths) if the * tables widths are passed in using `columns`. * @type boolean * @default true * * @dtopt Features * @name DataTable.defaults.autoWidth * * @example * $(document).ready( function () { * $('#example').dataTable( { * "autoWidth": false * } ); * } ); */ "bAutoWidth": true, /** * Deferred rendering can provide DataTables with a huge speed boost when you * are using an Ajax or JS data source for the table. This option, when set to * true, will cause DataTables to defer the creation of the table elements for * each row until they are needed for a draw - saving a significant amount of * time. * @type boolean * @default false * * @dtopt Features * @name DataTable.defaults.deferRender * * @example * $(document).ready( function() { * $('#example').dataTable( { * "ajax": "sources/arrays.txt", * "deferRender": true * } ); * } ); */ "bDeferRender": false, /** * Replace a DataTable which matches the given selector and replace it with * one which has the properties of the new initialisation object passed. If no * table matches the selector, then the new DataTable will be constructed as * per normal. * @type boolean * @default false * * @dtopt Options * @name DataTable.defaults.destroy * * @example * $(document).ready( function() { * $('#example').dataTable( { * "srollY": "200px", * "paginate": false * } ); * * // Some time later.... * $('#example').dataTable( { * "filter": false, * "destroy": true * } ); * } ); */ "bDestroy": false, /** * Enable or disable filtering of data. Filtering in DataTables is "smart" in * that it allows the end user to input multiple words (space separated) and * will match a row containing those words, even if not in the order that was * specified (this allow matching across multiple columns). Note that if you * wish to use filtering in DataTables this must remain 'true' - to remove the * default filtering input box and retain filtering abilities, please use * {@link DataTable.defaults.dom}. * @type boolean * @default true * * @dtopt Features * @name DataTable.defaults.searching * * @example * $(document).ready( function () { * $('#example').dataTable( { * "searching": false * } ); * } ); */ "bFilter": true, /** * Enable or disable the table information display. This shows information * about the data that is currently visible on the page, including information * about filtered data if that action is being performed. * @type boolean * @default true * * @dtopt Features * @name DataTable.defaults.info * * @example * $(document).ready( function () { * $('#example').dataTable( { * "info": false * } ); * } ); */ "bInfo": true, /** * Allows the end user to select the size of a formatted page from a select * menu (sizes are 10, 25, 50 and 100). Requires pagination (`paginate`). * @type boolean * @default true * * @dtopt Features * @name DataTable.defaults.lengthChange * * @example * $(document).ready( function () { * $('#example').dataTable( { * "lengthChange": false * } ); * } ); */ "bLengthChange": true, /** * Enable or disable pagination. * @type boolean * @default true * * @dtopt Features * @name DataTable.defaults.paging * * @example * $(document).ready( function () { * $('#example').dataTable( { * "paging": false * } ); * } ); */ "bPaginate": true, /** * Enable or disable the display of a 'processing' indicator when the table is * being processed (e.g. a sort). This is particularly useful for tables with * large amounts of data where it can take a noticeable amount of time to sort * the entries. * @type boolean * @default false * * @dtopt Features * @name DataTable.defaults.processing * * @example * $(document).ready( function () { * $('#example').dataTable( { * "processing": true * } ); * } ); */ "bProcessing": false, /** * Retrieve the DataTables object for the given selector. Note that if the * table has already been initialised, this parameter will cause DataTables * to simply return the object that has already been set up - it will not take * account of any changes you might have made to the initialisation object * passed to DataTables (setting this parameter to true is an acknowledgement * that you understand this). `destroy` can be used to reinitialise a table if * you need. * @type boolean * @default false * * @dtopt Options * @name DataTable.defaults.retrieve * * @example * $(document).ready( function() { * initTable(); * tableActions(); * } ); * * function initTable () * { * return $('#example').dataTable( { * "scrollY": "200px", * "paginate": false, * "retrieve": true * } ); * } * * function tableActions () * { * var table = initTable(); * // perform API operations with oTable * } */ "bRetrieve": false, /** * When vertical (y) scrolling is enabled, DataTables will force the height of * the table's viewport to the given height at all times (useful for layout). * However, this can look odd when filtering data down to a small data set, * and the footer is left "floating" further down. This parameter (when * enabled) will cause DataTables to collapse the table's viewport down when * the result set will fit within the given Y height. * @type boolean * @default false * * @dtopt Options * @name DataTable.defaults.scrollCollapse * * @example * $(document).ready( function() { * $('#example').dataTable( { * "scrollY": "200", * "scrollCollapse": true * } ); * } ); */ "bScrollCollapse": false, /** * Configure DataTables to use server-side processing. Note that the * `ajax` parameter must also be given in order to give DataTables a * source to obtain the required data for each draw. * @type boolean * @default false * * @dtopt Features * @dtopt Server-side * @name DataTable.defaults.serverSide * * @example * $(document).ready( function () { * $('#example').dataTable( { * "serverSide": true, * "ajax": "xhr.php" * } ); * } ); */ "bServerSide": false, /** * Enable or disable sorting of columns. Sorting of individual columns can be * disabled by the `sortable` option for each column. * @type boolean * @default true * * @dtopt Features * @name DataTable.defaults.ordering * * @example * $(document).ready( function () { * $('#example').dataTable( { * "ordering": false * } ); * } ); */ "bSort": true, /** * Enable or display DataTables' ability to sort multiple columns at the * same time (activated by shift-click by the user). * @type boolean * @default true * * @dtopt Options * @name DataTable.defaults.orderMulti * * @example * // Disable multiple column sorting ability * $(document).ready( function () { * $('#example').dataTable( { * "orderMulti": false * } ); * } ); */ "bSortMulti": true, /** * Allows control over whether DataTables should use the top (true) unique * cell that is found for a single column, or the bottom (false - default). * This is useful when using complex headers. * @type boolean * @default false * * @dtopt Options * @name DataTable.defaults.orderCellsTop * * @example * $(document).ready( function() { * $('#example').dataTable( { * "orderCellsTop": true * } ); * } ); */ "bSortCellsTop": false, /** * Enable or disable the addition of the classes `sorting\_1`, `sorting\_2` and * `sorting\_3` to the columns which are currently being sorted on. This is * presented as a feature switch as it can increase processing time (while * classes are removed and added) so for large data sets you might want to * turn this off. * @type boolean * @default true * * @dtopt Features * @name DataTable.defaults.orderClasses * * @example * $(document).ready( function () { * $('#example').dataTable( { * "orderClasses": false * } ); * } ); */ "bSortClasses": true, /** * Enable or disable state saving. When enabled HTML5 `localStorage` will be * used to save table display information such as pagination information, * display length, filtering and sorting. As such when the end user reloads * the page the display display will match what thy had previously set up. * * Due to the use of `localStorage` the default state saving is not supported * in IE6 or 7. If state saving is required in those browsers, use * `stateSaveCallback` to provide a storage solution such as cookies. * @type boolean * @default false * * @dtopt Features * @name DataTable.defaults.stateSave * * @example * $(document).ready( function () { * $('#example').dataTable( { * "stateSave": true * } ); * } ); */ "bStateSave": false, /** * This function is called when a TR element is created (and all TD child * elements have been inserted), or registered if using a DOM source, allowing * manipulation of the TR element (adding classes etc). * @type function * @param {node} row "TR" element for the current row * @param {array} data Raw data array for this row * @param {int} dataIndex The index of this row in the internal aoData array * * @dtopt Callbacks * @name DataTable.defaults.createdRow * * @example * $(document).ready( function() { * $('#example').dataTable( { * "createdRow": function( row, data, dataIndex ) { * // Bold the grade for all 'A' grade browsers * if ( data[4] == "A" ) * { * $('td:eq(4)', row).html( '<b>A</b>' ); * } * } * } ); * } ); */ "fnCreatedRow": null, /** * This function is called on every 'draw' event, and allows you to * dynamically modify any aspect you want about the created DOM. * @type function * @param {object} settings DataTables settings object * * @dtopt Callbacks * @name DataTable.defaults.drawCallback * * @example * $(document).ready( function() { * $('#example').dataTable( { * "drawCallback": function( settings ) { * alert( 'DataTables has redrawn the table' ); * } * } ); * } ); */ "fnDrawCallback": null, /** * Identical to fnHeaderCallback() but for the table footer this function * allows you to modify the table footer on every 'draw' event. * @type function * @param {node} foot "TR" element for the footer * @param {array} data Full table data (as derived from the original HTML) * @param {int} start Index for the current display starting point in the * display array * @param {int} end Index for the current display ending point in the * display array * @param {array int} display Index array to translate the visual position * to the full data array * * @dtopt Callbacks * @name DataTable.defaults.footerCallback * * @example * $(document).ready( function() { * $('#example').dataTable( { * "footerCallback": function( tfoot, data, start, end, display ) { * tfoot.getElementsByTagName('th')[0].innerHTML = "Starting index is "+start; * } * } ); * } ) */ "fnFooterCallback": null, /** * When rendering large numbers in the information element for the table * (i.e. "1 su 10 di 57 righe") DataTables will render large numbers * to have a comma separator for the 'thousands' units (e.g. 1 million is * rendered as "1,000,000") to help readability for the end user. This * function will override the default method DataTables uses. * @type function * @member * @param {int} toFormat number to be formatted * @returns {string} formatted string for DataTables to show the number * * @dtopt Callbacks * @name DataTable.defaults.formatNumber * * @example * // Format a number using a single quote for the separator (note that * // this can also be done with the language.thousands option) * $(document).ready( function() { * $('#example').dataTable( { * "formatNumber": function ( toFormat ) { * return toFormat.toString().replace( * /\B(?=(\d{3})+(?!\d))/g, "'" * ); * }; * } ); * } ); */ "fnFormatNumber": function ( toFormat ) { return toFormat.toString().replace( /\B(?=(\d{3})+(?!\d))/g, this.oLanguage.sThousands ); }, /** * This function is called on every 'draw' event, and allows you to * dynamically modify the header row. This can be used to calculate and * display useful information about the table. * @type function * @param {node} head "TR" element for the header * @param {array} data Full table data (as derived from the original HTML) * @param {int} start Index for the current display starting point in the * display array * @param {int} end Index for the current display ending point in the * display array * @param {array int} display Index array to translate the visual position * to the full data array * * @dtopt Callbacks * @name DataTable.defaults.headerCallback * * @example * $(document).ready( function() { * $('#example').dataTable( { * "fheaderCallback": function( head, data, start, end, display ) { * head.getElementsByTagName('th')[0].innerHTML = "Displaying "+(end-start)+" records"; * } * } ); * } ) */ "fnHeaderCallback": null, /** * The information element can be used to convey information about the current * state of the table. Although the internationalisation options presented by * DataTables are quite capable of dealing with most customisations, there may * be times where you wish to customise the string further. This callback * allows you to do exactly that. * @type function * @param {object} oSettings DataTables settings object * @param {int} start Starting position in data for the draw * @param {int} end End position in data for the draw * @param {int} max Total number of rows in the table (regardless of * filtering) * @param {int} total Total number of rows in the data set, after filtering * @param {string} pre The string that DataTables has formatted using it's * own rules * @returns {string} The string to be displayed in the information element. * * @dtopt Callbacks * @name DataTable.defaults.infoCallback * * @example * $('#example').dataTable( { * "infoCallback": function( settings, start, end, max, total, pre ) { * return start +" to "+ end; * } * } ); */ "fnInfoCallback": null, /** * Called when the table has been initialised. Normally DataTables will * initialise sequentially and there will be no need for this function, * however, this does not hold true when using external language information * since that is obtained using an async XHR call. * @type function * @param {object} settings DataTables settings object * @param {object} json The JSON object request from the server - only * present if client-side Ajax sourced data is used * * @dtopt Callbacks * @name DataTable.defaults.initComplete * * @example * $(document).ready( function() { * $('#example').dataTable( { * "initComplete": function(settings, json) { * alert( 'DataTables has finished its initialisation.' ); * } * } ); * } ) */ "fnInitComplete": null, /** * Called at the very start of each table draw and can be used to cancel the * draw by returning false, any other return (including undefined) results in * the full draw occurring). * @type function * @param {object} settings DataTables settings object * @returns {boolean} False will cancel the draw, anything else (including no * return) will allow it to complete. * * @dtopt Callbacks * @name DataTable.defaults.preDrawCallback * * @example * $(document).ready( function() { * $('#example').dataTable( { * "preDrawCallback": function( settings ) { * if ( $('#test').val() == 1 ) { * return false; * } * } * } ); * } ); */ "fnPreDrawCallback": null, /** * This function allows you to 'post process' each row after it have been * generated for each table draw, but before it is rendered on screen. This * function might be used for setting the row class name etc. * @type function * @param {node} row "TR" element for the current row * @param {array} data Raw data array for this row * @param {int} displayIndex The display index for the current table draw * @param {int} displayIndexFull The index of the data in the full list of * rows (after filtering) * * @dtopt Callbacks * @name DataTable.defaults.rowCallback * * @example * $(document).ready( function() { * $('#example').dataTable( { * "rowCallback": function( row, data, displayIndex, displayIndexFull ) { * // Bold the grade for all 'A' grade browsers * if ( data[4] == "A" ) { * $('td:eq(4)', row).html( '<b>A</b>' ); * } * } * } ); * } ); */ "fnRowCallback": null, /** * __Deprecated__ The functionality provided by this parameter has now been * superseded by that provided through `ajax`, which should be used instead. * * This parameter allows you to override the default function which obtains * the data from the server so something more suitable for your application. * For example you could use POST data, or pull information from a Gears or * AIR database. * @type function * @member * @param {string} source HTTP source to obtain the data from (`ajax`) * @param {array} data A key/value pair object containing the data to send * to the server * @param {function} callback to be called on completion of the data get * process that will draw the data on the page. * @param {object} settings DataTables settings object * * @dtopt Callbacks * @dtopt Server-side * @name DataTable.defaults.serverData * * @deprecated 1.10. Please use `ajax` for this functionality now. */ "fnServerData": null, /** * __Deprecated__ The functionality provided by this parameter has now been * superseded by that provided through `ajax`, which should be used instead. * * It is often useful to send extra data to the server when making an Ajax * request - for example custom filtering information, and this callback * function makes it trivial to send extra information to the server. The * passed in parameter is the data set that has been constructed by * DataTables, and you can add to this or modify it as you require. * @type function * @param {array} data Data array (array of objects which are name/value * pairs) that has been constructed by DataTables and will be sent to the * server. In the case of Ajax sourced data with server-side processing * this will be an empty array, for server-side processing there will be a * significant number of parameters! * @returns {undefined} Ensure that you modify the data array passed in, * as this is passed by reference. * * @dtopt Callbacks * @dtopt Server-side * @name DataTable.defaults.serverParams * * @deprecated 1.10. Please use `ajax` for this functionality now. */ "fnServerParams": null, /** * Load the table state. With this function you can define from where, and how, the * state of a table is loaded. By default DataTables will load from `localStorage` * but you might wish to use a server-side database or cookies. * @type function * @member * @param {object} settings DataTables settings object * @param {object} callback Callback that can be executed when done. It * should be passed the loaded state object. * @return {object} The DataTables state object to be loaded * * @dtopt Callbacks * @name DataTable.defaults.stateLoadCallback * * @example * $(document).ready( function() { * $('#example').dataTable( { * "stateSave": true, * "stateLoadCallback": function (settings, callback) { * $.ajax( { * "url": "/state_load", * "dataType": "json", * "success": function (json) { * callback( json ); * } * } ); * } * } ); * } ); */ "fnStateLoadCallback": function ( settings ) { try { return JSON.parse( (settings.iStateDuration === -1 ? sessionStorage : localStorage).getItem( 'DataTables_'+settings.sInstance+'_'+location.pathname ) ); } catch (e) {} }, /** * Callback which allows modification of the saved state prior to loading that state. * This callback is called when the table is loading state from the stored data, but * prior to the settings object being modified by the saved state. Note that for * plug-in authors, you should use the `stateLoadParams` event to load parameters for * a plug-in. * @type function * @param {object} settings DataTables settings object * @param {object} data The state object that is to be loaded * * @dtopt Callbacks * @name DataTable.defaults.stateLoadParams * * @example * // Remove a saved filter, so filtering is never loaded * $(document).ready( function() { * $('#example').dataTable( { * "stateSave": true, * "stateLoadParams": function (settings, data) { * data.oSearch.sSearch = ""; * } * } ); * } ); * * @example * // Disallow state loading by returning false * $(document).ready( function() { * $('#example').dataTable( { * "stateSave": true, * "stateLoadParams": function (settings, data) { * return false; * } * } ); * } ); */ "fnStateLoadParams": null, /** * Callback that is called when the state has been loaded from the state saving method * and the DataTables settings object has been modified as a result of the loaded state. * @type function * @param {object} settings DataTables settings object * @param {object} data The state object that was loaded * * @dtopt Callbacks * @name DataTable.defaults.stateLoaded * * @example * // Show an alert with the filtering value that was saved * $(document).ready( function() { * $('#example').dataTable( { * "stateSave": true, * "stateLoaded": function (settings, data) { * alert( 'Saved filter was: '+data.oSearch.sSearch ); * } * } ); * } ); */ "fnStateLoaded": null, /** * Save the table state. This function allows you to define where and how the state * information for the table is stored By default DataTables will use `localStorage` * but you might wish to use a server-side database or cookies. * @type function * @member * @param {object} settings DataTables settings object * @param {object} data The state object to be saved * * @dtopt Callbacks * @name DataTable.defaults.stateSaveCallback * * @example * $(document).ready( function() { * $('#example').dataTable( { * "stateSave": true, * "stateSaveCallback": function (settings, data) { * // Send an Ajax request to the server with the state object * $.ajax( { * "url": "/state_save", * "data": data, * "dataType": "json", * "method": "POST" * "success": function () {} * } ); * } * } ); * } ); */ "fnStateSaveCallback": function ( settings, data ) { try { (settings.iStateDuration === -1 ? sessionStorage : localStorage).setItem( 'DataTables_'+settings.sInstance+'_'+location.pathname, JSON.stringify( data ) ); } catch (e) {} }, /** * Callback which allows modification of the state to be saved. Called when the table * has changed state a new state save is required. This method allows modification of * the state saving object prior to actually doing the save, including addition or * other state properties or modification. Note that for plug-in authors, you should * use the `stateSaveParams` event to save parameters for a plug-in. * @type function * @param {object} settings DataTables settings object * @param {object} data The state object to be saved * * @dtopt Callbacks * @name DataTable.defaults.stateSaveParams * * @example * // Remove a saved filter, so filtering is never saved * $(document).ready( function() { * $('#example').dataTable( { * "stateSave": true, * "stateSaveParams": function (settings, data) { * data.oSearch.sSearch = ""; * } * } ); * } ); */ "fnStateSaveParams": null, /** * Duration for which the saved state information is considered valid. After this period * has elapsed the state will be returned to the default. * Value is given in seconds. * @type int * @default 7200 <i>(2 hours)</i> * * @dtopt Options * @name DataTable.defaults.stateDuration * * @example * $(document).ready( function() { * $('#example').dataTable( { * "stateDuration": 60*60*24; // 1 day * } ); * } ) */ "iStateDuration": 7200, /** * When enabled DataTables will not make a request to the server for the first * page draw - rather it will use the data already on the page (no sorting etc * will be applied to it), thus saving on an XHR at load time. `deferLoading` * is used to indicate that deferred loading is required, but it is also used * to tell DataTables how many records there are in the full table (allowing * the information element and pagination to be displayed correctly). In the case * where a filtering is applied to the table on initial load, this can be * indicated by giving the parameter as an array, where the first element is * the number of records available after filtering and the second element is the * number of records without filtering (allowing the table information element * to be shown correctly). * @type int | array * @default null * * @dtopt Options * @name DataTable.defaults.deferLoading * * @example * // 57 records available in the table, no filtering applied * $(document).ready( function() { * $('#example').dataTable( { * "serverSide": true, * "ajax": "scripts/server_processing.php", * "deferLoading": 57 * } ); * } ); * * @example * // 57 records after filtering, 100 without filtering (an initial filter applied) * $(document).ready( function() { * $('#example').dataTable( { * "serverSide": true, * "ajax": "scripts/server_processing.php", * "deferLoading": [ 57, 100 ], * "search": { * "search": "my_filter" * } * } ); * } ); */ "iDeferLoading": null, /** * Number of rows to display on a single page when using pagination. If * feature enabled (`lengthChange`) then the end user will be able to override * this to a custom setting using a pop-up menu. * @type int * @default 10 * * @dtopt Options * @name DataTable.defaults.pageLength * * @example * $(document).ready( function() { * $('#example').dataTable( { * "pageLength": 50 * } ); * } ) */ "iDisplayLength": 10, /** * Define the starting point for data display when using DataTables with * pagination. Note that this parameter is the number of records, rather than * the page number, so if you have 10 records per page and want to start on * the third page, it should be "20". * @type int * @default 0 * * @dtopt Options * @name DataTable.defaults.displayStart * * @example * $(document).ready( function() { * $('#example').dataTable( { * "displayStart": 20 * } ); * } ) */ "iDisplayStart": 0, /** * By default DataTables allows keyboard navigation of the table (sorting, paging, * and filtering) by adding a `tabindex` attribute to the required elements. This * allows you to tab through the controls and press the enter key to activate them. * The tabindex is default 0, meaning that the tab follows the flow of the document. * You can overrule this using this parameter if you wish. Use a value of -1 to * disable built-in keyboard navigation. * @type int * @default 0 * * @dtopt Options * @name DataTable.defaults.tabIndex * * @example * $(document).ready( function() { * $('#example').dataTable( { * "tabIndex": 1 * } ); * } ); */ "iTabIndex": 0, /** * Classes that DataTables assigns to the various components and features * that it adds to the HTML table. This allows classes to be configured * during initialisation in addition to through the static * {@link DataTable.ext.oStdClasses} object). * @namespace * @name DataTable.defaults.classes */ "oClasses": {}, /** * All strings that DataTables uses in the user interface that it creates * are defined in this object, allowing you to modified them individually or * completely replace them all as required. * @namespace * @name DataTable.defaults.language */ "oLanguage": { /** * Strings that are used for WAI-ARIA labels and controls only (these are not * actually visible on the page, but will be read by screenreaders, and thus * must be internationalised as well). * @namespace * @name DataTable.defaults.language.aria */ "oAria": { /** * ARIA label that is added to the table headers when the column may be * sorted ascending by activing the column (click or return when focused). * Note that the column header is prefixed to this string. * @type string * @default : activate to sort column ascending * * @dtopt Language * @name DataTable.defaults.language.aria.sortAscending * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "aria": { * "sortAscending": " - click/return to sort ascending" * } * } * } ); * } ); */ "sSortAscending": ": activate to sort column ascending", /** * ARIA label that is added to the table headers when the column may be * sorted descending by activing the column (click or return when focused). * Note that the column header is prefixed to this string. * @type string * @default : activate to sort column ascending * * @dtopt Language * @name DataTable.defaults.language.aria.sortDescending * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "aria": { * "sortDescending": " - click/return to sort descending" * } * } * } ); * } ); */ "sSortDescending": ": activate to sort column descending" }, /** * Pagination string used by DataTables for the built-in pagination * control types. * @namespace * @name DataTable.defaults.language.paginate */ "oPaginate": { /** * Text to use when using the 'full_numbers' type of pagination for the * button to take the user to the first page. * @type string * @default First * * @dtopt Language * @name DataTable.defaults.language.paginate.first * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "paginate": { * "first": "First page" * } * } * } ); * } ); */ "sFirst": "First", /** * Text to use when using the 'full_numbers' type of pagination for the * button to take the user to the last page. * @type string * @default Last * * @dtopt Language * @name DataTable.defaults.language.paginate.last * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "paginate": { * "last": "Last page" * } * } * } ); * } ); */ "sLast": "Last", /** * Text to use for the 'next' pagination button (to take the user to the * next page). * @type string * @default Next * * @dtopt Language * @name DataTable.defaults.language.paginate.next * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "paginate": { * "next": "Next page" * } * } * } ); * } ); */ "sNext": "Next", /** * Text to use for the 'previous' pagination button (to take the user to * the previous page). * @type string * @default Previous * * @dtopt Language * @name DataTable.defaults.language.paginate.previous * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "paginate": { * "previous": "Previous page" * } * } * } ); * } ); */ "sPrevious": "Previous" }, /** * This string is shown in preference to `zeroRecords` when the table is * empty of data (regardless of filtering). Note that this is an optional * parameter - if it is not given, the value of `zeroRecords` will be used * instead (either the default or given value). * @type string * @default No data available in table * * @dtopt Language * @name DataTable.defaults.language.emptyTable * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "emptyTable": "No data available in table" * } * } ); * } ); */ "sEmptyTable": "Non ci sono dati disponibili nella tabella", /** * This string gives information to the end user about the information * that is current on display on the page. The following tokens can be * used in the string and will be dynamically replaced as the table * display updates. This tokens can be placed anywhere in the string, or * removed as needed by the language requires: * * * `\_START\_` - Display index of the first record on the current page * * `\_END\_` - Display index of the last record on the current page * * `\_TOTAL\_` - Number of records in the table after filtering * * `\_MAX\_` - Number of records in the table without filtering * * `\_PAGE\_` - Current page number * * `\_PAGES\_` - Total number of pages of data in the table * * @type string * @default Showing _START_ to _END_ of _TOTAL_ entries * * @dtopt Language * @name DataTable.defaults.language.info * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "info": "Showing page _PAGE_ of _PAGES_" * } * } ); * } ); */ "sInfo": "_START_ su _END_ di _TOTAL_ righe", /** * Display information string for when the table is empty. Typically the * format of this string should match `info`. * @type string * @default Showing 0 to 0 of 0 entries * * @dtopt Language * @name DataTable.defaults.language.infoEmpty * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "infoEmpty": "Non ci sono righe" * } * } ); * } ); */ "sInfoEmpty": "Non ci sono righe", /** * When a user filters the information in a table, this string is appended * to the information (`info`) to give an idea of how strong the filtering * is. The variable _MAX_ is dynamically updated. * @type string * @default (filtered from _MAX_ total entries) * * @dtopt Language * @name DataTable.defaults.language.infoFiltered * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "infoFiltered": " - filtering from _MAX_ records" * } * } ); * } ); */ "sInfoFiltered": "(filtered from _MAX_ total entries)", /** * If can be useful to append extra information to the info string at times, * and this variable does exactly that. This information will be appended to * the `info` (`infoEmpty` and `infoFiltered` in whatever combination they are * being used) at all times. * @type string * @default <i>Empty string</i> * * @dtopt Language * @name DataTable.defaults.language.infoPostFix * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "infoPostFix": "All records shown are derived from real information." * } * } ); * } ); */ "sInfoPostFix": "", /** * This decimal place operator is a little different from the other * language options since DataTables doesn't output floating point * numbers, so it won't ever use this for display of a number. Rather, * what this parameter does is modify the sort methods of the table so * that numbers which are in a format which has a character other than * a period (`.`) as a decimal place will be sorted numerically. * * Note that numbers with different decimal places cannot be shown in * the same table and still be sortable, the table must be consistent. * However, multiple different tables on the page can use different * decimal place characters. * @type string * @default * * @dtopt Language * @name DataTable.defaults.language.decimal * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "decimal": "," * "thousands": "." * } * } ); * } ); */ "sDecimal": "", /** * DataTables has a build in number formatter (`formatNumber`) which is * used to format large numbers that are used in the table information. * By default a comma is used, but this can be trivially changed to any * character you wish with this parameter. * @type string * @default , * * @dtopt Language * @name DataTable.defaults.language.thousands * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "thousands": "'" * } * } ); * } ); */ "sThousands": ",", /** * Detail the action that will be taken when the drop down menu for the * pagination length option is changed. The '_MENU_' variable is replaced * with a default select list of 10, 25, 50 and 100, and can be replaced * with a custom select box if required. * @type string * @default Show _MENU_ entries * * @dtopt Language * @name DataTable.defaults.language.lengthMenu * * @example * // Language change only * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "lengthMenu": "Display _MENU_ records" * } * } ); * } ); * * @example * // Language and options change * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "lengthMenu": 'Display <select>'+ * '<option value="10">10</option>'+ * '<option value="20">20</option>'+ * '<option value="30">30</option>'+ * '<option value="40">40</option>'+ * '<option value="50">50</option>'+ * '<option value="-1">All</option>'+ * '</select> records' * } * } ); * } ); */ "sLengthMenu": "Mostra _MENU_ righe", /** * When using Ajax sourced data and during the first draw when DataTables is * gathering the data, this message is shown in an empty row in the table to * indicate to the end user the the data is being loaded. Note that this * parameter is not used when loading data by server-side processing, just * Ajax sourced data with client-side processing. * @type string * @default Loading... * * @dtopt Language * @name DataTable.defaults.language.loadingRecords * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "loadingRecords": "Per favore attendi - carico..." * } * } ); * } ); */ "sLoadingRecords": "Carico...", /** * Text which is displayed when the table is processing a user action * (usually a sort command or similar). * @type string * @default Processing... * * @dtopt Language * @name DataTable.defaults.language.processing * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "processing": "DataTables is currently busy" * } * } ); * } ); */ "sProcessing": "Processo...", /** * Details the actions that will be taken when the user types into the * filtering input text box. The variable "_INPUT_", if used in the string, * is replaced with the HTML text box for the filtering input allowing * control over where it appears in the string. If "_INPUT_" is not given * then the input box is appended to the string automatically. * @type string * @default Search: * * @dtopt Language * @name DataTable.defaults.language.search * * @example * // Input text box will be appended at the end automatically * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "search": "Filter records:" * } * } ); * } ); * * @example * // Specify where the filter should appear * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "search": "Apply filter _INPUT_ to table" * } * } ); * } ); */ "sSearch": "Cerca:", /** * Assign a `placeholder` attribute to the search `input` element * @type string * @default * * @dtopt Language * @name DataTable.defaults.language.searchPlaceholder */ "sSearchPlaceholder": "", /** * All of the language information can be stored in a file on the * server-side, which DataTables will look up if this parameter is passed. * It must store the URL of the language file, which is in a JSON format, * and the object has the same properties as the oLanguage object in the * initialiser object (i.e. the above parameters). Please refer to one of * the example language files to see how this works in action. * @type string * @default <i>Empty string - i.e. disabled</i> * * @dtopt Language * @name DataTable.defaults.language.url * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "url": "http://www.sprymedia.co.uk/dataTables/lang.txt" * } * } ); * } ); */ "sUrl": "", /** * Text shown inside the table records when the is no information to be * displayed after filtering. `emptyTable` is shown when there is simply no * information in the table at all (regardless of filtering). * @type string * @default No matching records found * * @dtopt Language * @name DataTable.defaults.language.zeroRecords * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "zeroRecords": "No records to display" * } * } ); * } ); */ "sZeroRecords": "Non ci sono righe" }, /** * This parameter allows you to have define the global filtering state at * initialisation time. As an object the `search` parameter must be * defined, but all other parameters are optional. When `regex` is true, * the search string will be treated as a regular expression, when false * (default) it will be treated as a straight string. When `smart` * DataTables will use it's smart filtering methods (to word match at * any point in the data), when false this will not be done. * @namespace * @extends DataTable.models.oSearch * * @dtopt Options * @name DataTable.defaults.search * * @example * $(document).ready( function() { * $('#example').dataTable( { * "search": {"search": "Initial search"} * } ); * } ) */ "oSearch": $.extend( {}, DataTable.models.oSearch ), /** * __Deprecated__ The functionality provided by this parameter has now been * superseded by that provided through `ajax`, which should be used instead. * * By default DataTables will look for the property `data` (or `aaData` for * compatibility with DataTables 1.9-) when obtaining data from an Ajax * source or for server-side processing - this parameter allows that * property to be changed. You can use Javascript dotted object notation to * get a data source for multiple levels of nesting. * @type string * @default data * * @dtopt Options * @dtopt Server-side * @name DataTable.defaults.ajaxDataProp * * @deprecated 1.10. Please use `ajax` for this functionality now. */ "sAjaxDataProp": "data", /** * __Deprecated__ The functionality provided by this parameter has now been * superseded by that provided through `ajax`, which should be used instead. * * You can instruct DataTables to load data from an external * source using this parameter (use aData if you want to pass data in you * already have). Simply provide a url a JSON object can be obtained from. * @type string * @default null * * @dtopt Options * @dtopt Server-side * @name DataTable.defaults.ajaxSource * * @deprecated 1.10. Please use `ajax` for this functionality now. */ "sAjaxSource": null, /** * This initialisation variable allows you to specify exactly where in the * DOM you want DataTables to inject the various controls it adds to the page * (for example you might want the pagination controls at the top of the * table). DIV elements (with or without a custom class) can also be added to * aid styling. The follow syntax is used: * <ul> * <li>The following options are allowed: * <ul> * <li>'l' - Length changing</li> * <li>'f' - Filtering input</li> * <li>'t' - The table!</li> * <li>'i' - Information</li> * <li>'p' - Pagination</li> * <li>'r' - pRocessing</li> * </ul> * </li> * <li>The following constants are allowed: * <ul> * <li>'H' - jQueryUI theme "header" classes ('fg-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix')</li> * <li>'F' - jQueryUI theme "footer" classes ('fg-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix')</li> * </ul> * </li> * <li>The following syntax is expected: * <ul> * <li>'&lt;' and '&gt;' - div elements</li> * <li>'&lt;"class" and '&gt;' - div with a class</li> * <li>'&lt;"#id" and '&gt;' - div with an ID</li> * </ul> * </li> * <li>Examples: * <ul> * <li>'&lt;"wrapper"flipt&gt;'</li> * <li>'&lt;lf&lt;t&gt;ip&gt;'</li> * </ul> * </li> * </ul> * @type string * @default lfrtip <i>(when `jQueryUI` is false)</i> <b>or</b> * <"H"lfr>t<"F"ip> <i>(when `jQueryUI` is true)</i> * * @dtopt Options * @name DataTable.defaults.dom * * @example * $(document).ready( function() { * $('#example').dataTable( { * "dom": '&lt;"top"i&gt;rt&lt;"bottom"flp&gt;&lt;"clear"&gt;' * } ); * } ); */ "sDom": "lfrtip", /** * Search delay option. This will throttle full table searches that use the * DataTables provided search input element (it does not effect calls to * `dt-api search()`, providing a delay before the search is made. * @type integer * @default 0 * * @dtopt Options * @name DataTable.defaults.searchDelay * * @example * $(document).ready( function() { * $('#example').dataTable( { * "searchDelay": 200 * } ); * } ) */ "searchDelay": null, /** * DataTables features six different built-in options for the buttons to * display for pagination control: * * * `numbers` - Page number buttons only * * `simple` - 'Previous' and 'Next' buttons only * * 'simple_numbers` - 'Previous' and 'Next' buttons, plus page numbers * * `full` - 'First', 'Previous', 'Next' and 'Last' buttons * * `full_numbers` - 'First', 'Previous', 'Next' and 'Last' buttons, plus page numbers * * `first_last_numbers` - 'First' and 'Last' buttons, plus page numbers * * Further methods can be added using {@link DataTable.ext.oPagination}. * @type string * @default simple_numbers * * @dtopt Options * @name DataTable.defaults.pagingType * * @example * $(document).ready( function() { * $('#example').dataTable( { * "pagingType": "full_numbers" * } ); * } ) */ "sPaginationType": "simple_numbers", /** * Enable horizontal scrolling. When a table is too wide to fit into a * certain layout, or you have a large number of columns in the table, you * can enable x-scrolling to show the table in a viewport, which can be * scrolled. This property can be `true` which will allow the table to * scroll horizontally when needed, or any CSS unit, or a number (in which * case it will be treated as a pixel measurement). Setting as simply `true` * is recommended. * @type boolean|string * @default <i>blank string - i.e. disabled</i> * * @dtopt Features * @name DataTable.defaults.scrollX * * @example * $(document).ready( function() { * $('#example').dataTable( { * "scrollX": true, * "scrollCollapse": true * } ); * } ); */ "sScrollX": "", /** * This property can be used to force a DataTable to use more width than it * might otherwise do when x-scrolling is enabled. For example if you have a * table which requires to be well spaced, this parameter is useful for * "over-sizing" the table, and thus forcing scrolling. This property can by * any CSS unit, or a number (in which case it will be treated as a pixel * measurement). * @type string * @default <i>blank string - i.e. disabled</i> * * @dtopt Options * @name DataTable.defaults.scrollXInner * * @example * $(document).ready( function() { * $('#example').dataTable( { * "scrollX": "100%", * "scrollXInner": "110%" * } ); * } ); */ "sScrollXInner": "", /** * Enable vertical scrolling. Vertical scrolling will constrain the DataTable * to the given height, and enable scrolling for any data which overflows the * current viewport. This can be used as an alternative to paging to display * a lot of data in a small area (although paging and scrolling can both be * enabled at the same time). This property can be any CSS unit, or a number * (in which case it will be treated as a pixel measurement). * @type string * @default <i>blank string - i.e. disabled</i> * * @dtopt Features * @name DataTable.defaults.scrollY * * @example * $(document).ready( function() { * $('#example').dataTable( { * "scrollY": "200px", * "paginate": false * } ); * } ); */ "sScrollY": "", /** * __Deprecated__ The functionality provided by this parameter has now been * superseded by that provided through `ajax`, which should be used instead. * * Set the HTTP method that is used to make the Ajax call for server-side * processing or Ajax sourced data. * @type string * @default GET * * @dtopt Options * @dtopt Server-side * @name DataTable.defaults.serverMethod * * @deprecated 1.10. Please use `ajax` for this functionality now. */ "sServerMethod": "GET", /** * DataTables makes use of renderers when displaying HTML elements for * a table. These renderers can be added or modified by plug-ins to * generate suitable mark-up for a site. For example the Bootstrap * integration plug-in for DataTables uses a paging button renderer to * display pagination buttons in the mark-up required by Bootstrap. * * For further information about the renderers available see * DataTable.ext.renderer * @type string|object * @default null * * @name DataTable.defaults.renderer * */ "renderer": null, /** * Set the data property name that DataTables should use to get a row's id * to set as the `id` property in the node. * @type string * @default DT_RowId * * @name DataTable.defaults.rowId */ "rowId": "DT_RowId" }; _fnHungarianMap( DataTable.defaults ); /* * Developer note - See note in model.defaults.js about the use of Hungarian * notation and camel case. */ /** * Column options that can be given to DataTables at initialisation time. * @namespace */ DataTable.defaults.column = { /** * Define which column(s) an order will occur on for this column. This * allows a column's ordering to take multiple columns into account when * doing a sort or use the data from a different column. For example first * name / last name columns make sense to do a multi-column sort over the * two columns. * @type array|int * @default null <i>Takes the value of the column index automatically</i> * * @name DataTable.defaults.column.orderData * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "orderData": [ 0, 1 ], "targets": [ 0 ] }, * { "orderData": [ 1, 0 ], "targets": [ 1 ] }, * { "orderData": 2, "targets": [ 2 ] } * ] * } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * { "orderData": [ 0, 1 ] }, * { "orderData": [ 1, 0 ] }, * { "orderData": 2 }, * null, * null * ] * } ); * } ); */ "aDataSort": null, "iDataSort": -1, /** * You can control the default ordering direction, and even alter the * behaviour of the sort handler (i.e. only allow ascending ordering etc) * using this parameter. * @type array * @default [ 'asc', 'desc' ] * * @name DataTable.defaults.column.orderSequence * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "orderSequence": [ "asc" ], "targets": [ 1 ] }, * { "orderSequence": [ "desc", "asc", "asc" ], "targets": [ 2 ] }, * { "orderSequence": [ "desc" ], "targets": [ 3 ] } * ] * } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * null, * { "orderSequence": [ "asc" ] }, * { "orderSequence": [ "desc", "asc", "asc" ] }, * { "orderSequence": [ "desc" ] }, * null * ] * } ); * } ); */ "asSorting": [ 'asc', 'desc' ], /** * Enable or disable filtering on the data in this column. * @type boolean * @default true * * @name DataTable.defaults.column.searchable * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "searchable": false, "targets": [ 0 ] } * ] } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * { "searchable": false }, * null, * null, * null, * null * ] } ); * } ); */ "bSearchable": true, /** * Enable or disable ordering on this column. * @type boolean * @default true * * @name DataTable.defaults.column.orderable * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "orderable": false, "targets": [ 0 ] } * ] } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * { "orderable": false }, * null, * null, * null, * null * ] } ); * } ); */ "bSortable": true, /** * Enable or disable the display of this column. * @type boolean * @default true * * @name DataTable.defaults.column.visible * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "visible": false, "targets": [ 0 ] } * ] } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * { "visible": false }, * null, * null, * null, * null * ] } ); * } ); */ "bVisible": true, /** * Developer definable function that is called whenever a cell is created (Ajax source, * etc) or processed for input (DOM source). This can be used as a compliment to mRender * allowing you to modify the DOM element (add background colour for example) when the * element is available. * @type function * @param {element} td The TD node that has been created * @param {*} cellData The Data for the cell * @param {array|object} rowData The data for the whole row * @param {int} row The row index for the aoData data store * @param {int} col The column index for aoColumns * * @name DataTable.defaults.column.createdCell * @dtopt Columns * * @example * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ { * "targets": [3], * "createdCell": function (td, cellData, rowData, row, col) { * if ( cellData == "1.7" ) { * $(td).css('color', 'blue') * } * } * } ] * }); * } ); */ "fnCreatedCell": null, /** * This parameter has been replaced by `data` in DataTables to ensure naming * consistency. `dataProp` can still be used, as there is backwards * compatibility in DataTables for this option, but it is strongly * recommended that you use `data` in preference to `dataProp`. * @name DataTable.defaults.column.dataProp */ /** * This property can be used to read data from any data source property, * including deeply nested objects / properties. `data` can be given in a * number of different ways which effect its behaviour: * * * `integer` - treated as an array index for the data source. This is the * default that DataTables uses (incrementally increased for each column). * * `string` - read an object property from the data source. There are * three 'special' options that can be used in the string to alter how * DataTables reads the data from the source object: * * `.` - Dotted Javascript notation. Just as you use a `.` in * Javascript to read from nested objects, so to can the options * specified in `data`. For example: `browser.version` or * `browser.name`. If your object parameter name contains a period, use * `\\` to escape it - i.e. `first\\.name`. * * `[]` - Array notation. DataTables can automatically combine data * from and array source, joining the data with the characters provided * between the two brackets. For example: `name[, ]` would provide a * comma-space separated list from the source array. If no characters * are provided between the brackets, the original array source is * returned. * * `()` - Function notation. Adding `()` to the end of a parameter will * execute a function of the name given. For example: `browser()` for a * simple function on the data source, `browser.version()` for a * function in a nested property or even `browser().version` to get an * object property if the function called returns an object. Note that * function notation is recommended for use in `render` rather than * `data` as it is much simpler to use as a renderer. * * `null` - use the original data source for the row rather than plucking * data directly from it. This action has effects on two other * initialisation options: * * `defaultContent` - When null is given as the `data` option and * `defaultContent` is specified for the column, the value defined by * `defaultContent` will be used for the cell. * * `render` - When null is used for the `data` option and the `render` * option is specified for the column, the whole data source for the * row is used for the renderer. * * `function` - the function given will be executed whenever DataTables * needs to set or get the data for a cell in the column. The function * takes three parameters: * * Parameters: * * `{array|object}` The data source for the row * * `{string}` The type call data requested - this will be 'set' when * setting data or 'filter', 'display', 'type', 'sort' or undefined * when gathering data. Note that when `undefined` is given for the * type DataTables expects to get the raw data for the object back< * * `{*}` Data to set when the second parameter is 'set'. * * Return: * * The return value from the function is not required when 'set' is * the type of call, but otherwise the return is what will be used * for the data requested. * * Note that `data` is a getter and setter option. If you just require * formatting of data for output, you will likely want to use `render` which * is simply a getter and thus simpler to use. * * Note that prior to DataTables 1.9.2 `data` was called `mDataProp`. The * name change reflects the flexibility of this property and is consistent * with the naming of mRender. If 'mDataProp' is given, then it will still * be used by DataTables, as it automatically maps the old name to the new * if required. * * @type string|int|function|null * @default null <i>Use automatically calculated column index</i> * * @name DataTable.defaults.column.data * @dtopt Columns * * @example * // Read table data from objects * // JSON structure for each row: * // { * // "engine": {value}, * // "browser": {value}, * // "platform": {value}, * // "version": {value}, * // "grade": {value} * // } * $(document).ready( function() { * $('#example').dataTable( { * "ajaxSource": "sources/objects.txt", * "columns": [ * { "data": "engine" }, * { "data": "browser" }, * { "data": "platform" }, * { "data": "version" }, * { "data": "grade" } * ] * } ); * } ); * * @example * // Read information from deeply nested objects * // JSON structure for each row: * // { * // "engine": {value}, * // "browser": {value}, * // "platform": { * // "inner": {value} * // }, * // "details": [ * // {value}, {value} * // ] * // } * $(document).ready( function() { * $('#example').dataTable( { * "ajaxSource": "sources/deep.txt", * "columns": [ * { "data": "engine" }, * { "data": "browser" }, * { "data": "platform.inner" }, * { "data": "platform.details.0" }, * { "data": "platform.details.1" } * ] * } ); * } ); * * @example * // Using `data` as a function to provide different information for * // sorting, filtering and display. In this case, currency (price) * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ { * "targets": [ 0 ], * "data": function ( source, type, val ) { * if (type === 'set') { * source.price = val; * // Store the computed dislay and filter values for efficiency * source.price_display = val=="" ? "" : "$"+numberFormat(val); * source.price_filter = val=="" ? "" : "$"+numberFormat(val)+" "+val; * return; * } * else if (type === 'display') { * return source.price_display; * } * else if (type === 'filter') { * return source.price_filter; * } * // 'sort', 'type' and undefined all just use the integer * return source.price; * } * } ] * } ); * } ); * * @example * // Using default content * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ { * "targets": [ 0 ], * "data": null, * "defaultContent": "Click to edit" * } ] * } ); * } ); * * @example * // Using array notation - outputting a list from an array * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ { * "targets": [ 0 ], * "data": "name[, ]" * } ] * } ); * } ); * */ "mData": null, /** * This property is the rendering partner to `data` and it is suggested that * when you want to manipulate data for display (including filtering, * sorting etc) without altering the underlying data for the table, use this * property. `render` can be considered to be the the read only companion to * `data` which is read / write (then as such more complex). Like `data` * this option can be given in a number of different ways to effect its * behaviour: * * * `integer` - treated as an array index for the data source. This is the * default that DataTables uses (incrementally increased for each column). * * `string` - read an object property from the data source. There are * three 'special' options that can be used in the string to alter how * DataTables reads the data from the source object: * * `.` - Dotted Javascript notation. Just as you use a `.` in * Javascript to read from nested objects, so to can the options * specified in `data`. For example: `browser.version` or * `browser.name`. If your object parameter name contains a period, use * `\\` to escape it - i.e. `first\\.name`. * * `[]` - Array notation. DataTables can automatically combine data * from and array source, joining the data with the characters provided * between the two brackets. For example: `name[, ]` would provide a * comma-space separated list from the source array. If no characters * are provided between the brackets, the original array source is * returned. * * `()` - Function notation. Adding `()` to the end of a parameter will * execute a function of the name given. For example: `browser()` for a * simple function on the data source, `browser.version()` for a * function in a nested property or even `browser().version` to get an * object property if the function called returns an object. * * `object` - use different data for the different data types requested by * DataTables ('filter', 'display', 'type' or 'sort'). The property names * of the object is the data type the property refers to and the value can * defined using an integer, string or function using the same rules as * `render` normally does. Note that an `_` option _must_ be specified. * This is the default value to use if you haven't specified a value for * the data type requested by DataTables. * * `function` - the function given will be executed whenever DataTables * needs to set or get the data for a cell in the column. The function * takes three parameters: * * Parameters: * * {array|object} The data source for the row (based on `data`) * * {string} The type call data requested - this will be 'filter', * 'display', 'type' or 'sort'. * * {array|object} The full data source for the row (not based on * `data`) * * Return: * * The return value from the function is what will be used for the * data requested. * * @type string|int|function|object|null * @default null Use the data source value. * * @name DataTable.defaults.column.render * @dtopt Columns * * @example * // Create a comma separated list from an array of objects * $(document).ready( function() { * $('#example').dataTable( { * "ajaxSource": "sources/deep.txt", * "columns": [ * { "data": "engine" }, * { "data": "browser" }, * { * "data": "platform", * "render": "[, ].name" * } * ] * } ); * } ); * * @example * // Execute a function to obtain data * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ { * "targets": [ 0 ], * "data": null, // Use the full data source object for the renderer's source * "render": "browserName()" * } ] * } ); * } ); * * @example * // As an object, extracting different data for the different types * // This would be used with a data source such as: * // { "phone": 5552368, "phone_filter": "5552368 555-2368", "phone_display": "555-2368" } * // Here the `phone` integer is used for sorting and type detection, while `phone_filter` * // (which has both forms) is used for filtering for if a user inputs either format, while * // the formatted phone number is the one that is shown in the table. * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ { * "targets": [ 0 ], * "data": null, // Use the full data source object for the renderer's source * "render": { * "_": "phone", * "filter": "phone_filter", * "display": "phone_display" * } * } ] * } ); * } ); * * @example * // Use as a function to create a link from the data source * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ { * "targets": [ 0 ], * "data": "download_link", * "render": function ( data, type, full ) { * return '<a href="'+data+'">Download</a>'; * } * } ] * } ); * } ); */ "mRender": null, /** * Change the cell type created for the column - either TD cells or TH cells. This * can be useful as TH cells have semantic meaning in the table body, allowing them * to act as a header for a row (you may wish to add scope='row' to the TH elements). * @type string * @default td * * @name DataTable.defaults.column.cellType * @dtopt Columns * * @example * // Make the first column use TH cells * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ { * "targets": [ 0 ], * "cellType": "th" * } ] * } ); * } ); */ "sCellType": "td", /** * Class to give to each cell in this column. * @type string * @default <i>Empty string</i> * * @name DataTable.defaults.column.class * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "class": "my_class", "targets": [ 0 ] } * ] * } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * { "class": "my_class" }, * null, * null, * null, * null * ] * } ); * } ); */ "sClass": "", /** * When DataTables calculates the column widths to assign to each column, * it finds the longest string in each column and then constructs a * temporary table and reads the widths from that. The problem with this * is that "mmm" is much wider then "iiii", but the latter is a longer * string - thus the calculation can go wrong (doing it properly and putting * it into an DOM object and measuring that is horribly(!) slow). Thus as * a "work around" we provide this option. It will append its value to the * text that is found to be the longest string for the column - i.e. padding. * Generally you shouldn't need this! * @type string * @default <i>Empty string<i> * * @name DataTable.defaults.column.contentPadding * @dtopt Columns * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * null, * null, * null, * { * "contentPadding": "mmm" * } * ] * } ); * } ); */ "sContentPadding": "", /** * Allows a default value to be given for a column's data, and will be used * whenever a null data source is encountered (this can be because `data` * is set to null, or because the data source itself is null). * @type string * @default null * * @name DataTable.defaults.column.defaultContent * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { * "data": null, * "defaultContent": "Edit", * "targets": [ -1 ] * } * ] * } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * null, * null, * null, * { * "data": null, * "defaultContent": "Edit" * } * ] * } ); * } ); */ "sDefaultContent": null, /** * This parameter is only used in DataTables' server-side processing. It can * be exceptionally useful to know what columns are being displayed on the * client side, and to map these to database fields. When defined, the names * also allow DataTables to reorder information from the server if it comes * back in an unexpected order (i.e. if you switch your columns around on the * client-side, your server-side code does not also need updating). * @type string * @default <i>Empty string</i> * * @name DataTable.defaults.column.name * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "name": "engine", "targets": [ 0 ] }, * { "name": "browser", "targets": [ 1 ] }, * { "name": "platform", "targets": [ 2 ] }, * { "name": "version", "targets": [ 3 ] }, * { "name": "grade", "targets": [ 4 ] } * ] * } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * { "name": "engine" }, * { "name": "browser" }, * { "name": "platform" }, * { "name": "version" }, * { "name": "grade" } * ] * } ); * } ); */ "sName": "", /** * Defines a data source type for the ordering which can be used to read * real-time information from the table (updating the internally cached * version) prior to ordering. This allows ordering to occur on user * editable elements such as form inputs. * @type string * @default std * * @name DataTable.defaults.column.orderDataType * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "orderDataType": "dom-text", "targets": [ 2, 3 ] }, * { "type": "numeric", "targets": [ 3 ] }, * { "orderDataType": "dom-select", "targets": [ 4 ] }, * { "orderDataType": "dom-checkbox", "targets": [ 5 ] } * ] * } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * null, * null, * { "orderDataType": "dom-text" }, * { "orderDataType": "dom-text", "type": "numeric" }, * { "orderDataType": "dom-select" }, * { "orderDataType": "dom-checkbox" } * ] * } ); * } ); */ "sSortDataType": "std", /** * The title of this column. * @type string * @default null <i>Derived from the 'TH' value for this column in the * original HTML table.</i> * * @name DataTable.defaults.column.title * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "title": "My column title", "targets": [ 0 ] } * ] * } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * { "title": "My column title" }, * null, * null, * null, * null * ] * } ); * } ); */ "sTitle": null, /** * The type allows you to specify how the data for this column will be * ordered. Four types (string, numeric, date and html (which will strip * HTML tags before ordering)) are currently available. Note that only date * formats understood by Javascript's Date() object will be accepted as type * date. For example: "Mar 26, 2008 5:03 PM". May take the values: 'string', * 'numeric', 'date' or 'html' (by default). Further types can be adding * through plug-ins. * @type string * @default null <i>Auto-detected from raw data</i> * * @name DataTable.defaults.column.type * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "type": "html", "targets": [ 0 ] } * ] * } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * { "type": "html" }, * null, * null, * null, * null * ] * } ); * } ); */ "sType": null, /** * Defining the width of the column, this parameter may take any CSS value * (3em, 20px etc). DataTables applies 'smart' widths to columns which have not * been given a specific width through this interface ensuring that the table * remains readable. * @type string * @default null <i>Automatic</i> * * @name DataTable.defaults.column.width * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "width": "20%", "targets": [ 0 ] } * ] * } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * { "width": "20%" }, * null, * null, * null, * null * ] * } ); * } ); */ "sWidth": null }; _fnHungarianMap( DataTable.defaults.column ); /** * DataTables settings object - this holds all the information needed for a * given table, including configuration, data and current application of the * table options. DataTables does not have a single instance for each DataTable * with the settings attached to that instance, but rather instances of the * DataTable "class" are created on-the-fly as needed (typically by a * $().dataTable() call) and the settings object is then applied to that * instance. * * Note that this object is related to {@link DataTable.defaults} but this * one is the internal data store for DataTables's cache of columns. It should * NOT be manipulated outside of DataTables. Any configuration should be done * through the initialisation options. * @namespace * @todo Really should attach the settings object to individual instances so we * don't need to create new instances on each $().dataTable() call (if the * table already exists). It would also save passing oSettings around and * into every single function. However, this is a very significant * architecture change for DataTables and will almost certainly break * backwards compatibility with older installations. This is something that * will be done in 2.0. */ DataTable.models.oSettings = { /** * Primary features of DataTables and their enablement state. * @namespace */ "oFeatures": { /** * Flag to say if DataTables should automatically try to calculate the * optimum table and columns widths (true) or not (false). * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bAutoWidth": null, /** * Delay the creation of TR and TD elements until they are actually * needed by a driven page draw. This can give a significant speed * increase for Ajax source and Javascript source data, but makes no * difference at all fro DOM and server-side processing tables. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bDeferRender": null, /** * Enable filtering on the table or not. Note that if this is disabled * then there is no filtering at all on the table, including fnFilter. * To just remove the filtering input use sDom and remove the 'f' option. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bFilter": null, /** * Table information element (the 'Showing x of y records' div) enable * flag. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bInfo": null, /** * Present a user control allowing the end user to change the page size * when pagination is enabled. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bLengthChange": null, /** * Pagination enabled or not. Note that if this is disabled then length * changing must also be disabled. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bPaginate": null, /** * Processing indicator enable flag whenever DataTables is enacting a * user request - typically an Ajax request for server-side processing. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bProcessing": null, /** * Server-side processing enabled flag - when enabled DataTables will * get all data from the server for every draw - there is no filtering, * sorting or paging done on the client-side. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bServerSide": null, /** * Sorting enablement flag. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bSort": null, /** * Multi-column sorting * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bSortMulti": null, /** * Apply a class to the columns which are being sorted to provide a * visual highlight or not. This can slow things down when enabled since * there is a lot of DOM interaction. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bSortClasses": null, /** * State saving enablement flag. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bStateSave": null }, /** * Scrolling settings for a table. * @namespace */ "oScroll": { /** * When the table is shorter in height than sScrollY, collapse the * table container down to the height of the table (when true). * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bCollapse": null, /** * Width of the scrollbar for the web-browser's platform. Calculated * during table initialisation. * @type int * @default 0 */ "iBarWidth": 0, /** * Viewport width for horizontal scrolling. Horizontal scrolling is * disabled if an empty string. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string */ "sX": null, /** * Width to expand the table to when using x-scrolling. Typically you * should not need to use this. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string * @deprecated */ "sXInner": null, /** * Viewport height for vertical scrolling. Vertical scrolling is disabled * if an empty string. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string */ "sY": null }, /** * Language information for the table. * @namespace * @extends DataTable.defaults.oLanguage */ "oLanguage": { /** * Information callback function. See * {@link DataTable.defaults.fnInfoCallback} * @type function * @default null */ "fnInfoCallback": null }, /** * Browser support parameters * @namespace */ "oBrowser": { /** * Indicate if the browser incorrectly calculates width:100% inside a * scrolling element (IE6/7) * @type boolean * @default false */ "bScrollOversize": false, /** * Determine if the vertical scrollbar is on the right or left of the * scrolling container - needed for rtl language layout, although not * all browsers move the scrollbar (Safari). * @type boolean * @default false */ "bScrollbarLeft": false, /** * Flag for if `getBoundingClientRect` is fully supported or not * @type boolean * @default false */ "bBounding": false, /** * Browser scrollbar width * @type integer * @default 0 */ "barWidth": 0 }, "ajax": null, /** * Array referencing the nodes which are used for the features. The * parameters of this object match what is allowed by sDom - i.e. * <ul> * <li>'l' - Length changing</li> * <li>'f' - Filtering input</li> * <li>'t' - The table!</li> * <li>'i' - Information</li> * <li>'p' - Pagination</li> * <li>'r' - pRocessing</li> * </ul> * @type array * @default [] */ "aanFeatures": [], /** * Store data information - see {@link DataTable.models.oRow} for detailed * information. * @type array * @default [] */ "aoData": [], /** * Array of indexes which are in the current display (after filtering etc) * @type array * @default [] */ "aiDisplay": [], /** * Array of indexes for display - no filtering * @type array * @default [] */ "aiDisplayMaster": [], /** * Map of row ids to data indexes * @type object * @default {} */ "aIds": {}, /** * Store information about each column that is in use * @type array * @default [] */ "aoColumns": [], /** * Store information about the table's header * @type array * @default [] */ "aoHeader": [], /** * Store information about the table's footer * @type array * @default [] */ "aoFooter": [], /** * Store the applied global search information in case we want to force a * research or compare the old search to a new one. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @namespace * @extends DataTable.models.oSearch */ "oPreviousSearch": {}, /** * Store the applied search for each column - see * {@link DataTable.models.oSearch} for the format that is used for the * filtering information for each column. * @type array * @default [] */ "aoPreSearchCols": [], /** * Sorting that is applied to the table. Note that the inner arrays are * used in the following manner: * <ul> * <li>Index 0 - column number</li> * <li>Index 1 - current sorting direction</li> * </ul> * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type array * @todo These inner arrays should really be objects */ "aaSorting": null, /** * Sorting that is always applied to the table (i.e. prefixed in front of * aaSorting). * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type array * @default [] */ "aaSortingFixed": [], /** * Classes to use for the striping of a table. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type array * @default [] */ "asStripeClasses": null, /** * If restoring a table - we should restore its striping classes as well * @type array * @default [] */ "asDestroyStripes": [], /** * If restoring a table - we should restore its width * @type int * @default 0 */ "sDestroyWidth": 0, /** * Callback functions array for every time a row is inserted (i.e. on a draw). * @type array * @default [] */ "aoRowCallback": [], /** * Callback functions for the header on each draw. * @type array * @default [] */ "aoHeaderCallback": [], /** * Callback function for the footer on each draw. * @type array * @default [] */ "aoFooterCallback": [], /** * Array of callback functions for draw callback functions * @type array * @default [] */ "aoDrawCallback": [], /** * Array of callback functions for row created function * @type array * @default [] */ "aoRowCreatedCallback": [], /** * Callback functions for just before the table is redrawn. A return of * false will be used to cancel the draw. * @type array * @default [] */ "aoPreDrawCallback": [], /** * Callback functions for when the table has been initialised. * @type array * @default [] */ "aoInitComplete": [], /** * Callbacks for modifying the settings to be stored for state saving, prior to * saving state. * @type array * @default [] */ "aoStateSaveParams": [], /** * Callbacks for modifying the settings that have been stored for state saving * prior to using the stored values to restore the state. * @type array * @default [] */ "aoStateLoadParams": [], /** * Callbacks for operating on the settings object once the saved state has been * loaded * @type array * @default [] */ "aoStateLoaded": [], /** * Cache the table ID for quick access * @type string * @default <i>Empty string</i> */ "sTableId": "", /** * The TABLE node for the main table * @type node * @default null */ "nTable": null, /** * Permanent ref to the thead element * @type node * @default null */ "nTHead": null, /** * Permanent ref to the tfoot element - if it exists * @type node * @default null */ "nTFoot": null, /** * Permanent ref to the tbody element * @type node * @default null */ "nTBody": null, /** * Cache the wrapper node (contains all DataTables controlled elements) * @type node * @default null */ "nTableWrapper": null, /** * Indicate if when using server-side processing the loading of data * should be deferred until the second draw. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean * @default false */ "bDeferLoading": false, /** * Indicate if all required information has been read in * @type boolean * @default false */ "bInitialised": false, /** * Information about open rows. Each object in the array has the parameters * 'nTr' and 'nParent' * @type array * @default [] */ "aoOpenRows": [], /** * Dictate the positioning of DataTables' control elements - see * {@link DataTable.model.oInit.sDom}. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string * @default null */ "sDom": null, /** * Search delay (in mS) * @type integer * @default null */ "searchDelay": null, /** * Which type of pagination should be used. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string * @default two_button */ "sPaginationType": "two_button", /** * The state duration (for `stateSave`) in seconds. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type int * @default 0 */ "iStateDuration": 0, /** * Array of callback functions for state saving. Each array element is an * object with the following parameters: * <ul> * <li>function:fn - function to call. Takes two parameters, oSettings * and the JSON string to save that has been thus far created. Returns * a JSON string to be inserted into a json object * (i.e. '"param": [ 0, 1, 2]')</li> * <li>string:sName - name of callback</li> * </ul> * @type array * @default [] */ "aoStateSave": [], /** * Array of callback functions for state loading. Each array element is an * object with the following parameters: * <ul> * <li>function:fn - function to call. Takes two parameters, oSettings * and the object stored. May return false to cancel state loading</li> * <li>string:sName - name of callback</li> * </ul> * @type array * @default [] */ "aoStateLoad": [], /** * State that was saved. Useful for back reference * @type object * @default null */ "oSavedState": null, /** * State that was loaded. Useful for back reference * @type object * @default null */ "oLoadedState": null, /** * Source url for AJAX data for the table. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string * @default null */ "sAjaxSource": null, /** * Property from a given object from which to read the table data from. This * can be an empty string (when not server-side processing), in which case * it is assumed an an array is given directly. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string */ "sAjaxDataProp": null, /** * Note if draw should be blocked while getting data * @type boolean * @default true */ "bAjaxDataGet": true, /** * The last jQuery XHR object that was used for server-side data gathering. * This can be used for working with the XHR information in one of the * callbacks * @type object * @default null */ "jqXHR": null, /** * JSON returned from the server in the last Ajax request * @type object * @default undefined */ "json": undefined, /** * Data submitted as part of the last Ajax request * @type object * @default undefined */ "oAjaxData": undefined, /** * Function to get the server-side data. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type function */ "fnServerData": null, /** * Functions which are called prior to sending an Ajax request so extra * parameters can easily be sent to the server * @type array * @default [] */ "aoServerParams": [], /** * Send the XHR HTTP method - GET or POST (could be PUT or DELETE if * required). * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string */ "sServerMethod": null, /** * Format numbers for display. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type function */ "fnFormatNumber": null, /** * List of options that can be used for the user selectable length menu. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type array * @default [] */ "aLengthMenu": null, /** * Counter for the draws that the table does. Also used as a tracker for * server-side processing * @type int * @default 0 */ "iDraw": 0, /** * Indicate if a redraw is being done - useful for Ajax * @type boolean * @default false */ "bDrawing": false, /** * Draw index (iDraw) of the last error when parsing the returned data * @type int * @default -1 */ "iDrawError": -1, /** * Paging display length * @type int * @default 10 */ "_iDisplayLength": 10, /** * Paging start point - aiDisplay index * @type int * @default 0 */ "_iDisplayStart": 0, /** * Server-side processing - number of records in the result set * (i.e. before filtering), Use fnRecordsTotal rather than * this property to get the value of the number of records, regardless of * the server-side processing setting. * @type int * @default 0 * @private */ "_iRecordsTotal": 0, /** * Server-side processing - number of records in the current display set * (i.e. after filtering). Use fnRecordsDisplay rather than * this property to get the value of the number of records, regardless of * the server-side processing setting. * @type boolean * @default 0 * @private */ "_iRecordsDisplay": 0, /** * The classes to use for the table * @type object * @default {} */ "oClasses": {}, /** * Flag attached to the settings object so you can check in the draw * callback if filtering has been done in the draw. Deprecated in favour of * events. * @type boolean * @default false * @deprecated */ "bFiltered": false, /** * Flag attached to the settings object so you can check in the draw * callback if sorting has been done in the draw. Deprecated in favour of * events. * @type boolean * @default false * @deprecated */ "bSorted": false, /** * Indicate that if multiple rows are in the header and there is more than * one unique cell per column, if the top one (true) or bottom one (false) * should be used for sorting / title by DataTables. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bSortCellsTop": null, /** * Initialisation object that is used for the table * @type object * @default null */ "oInit": null, /** * Destroy callback functions - for plug-ins to attach themselves to the * destroy so they can clean up markup and events. * @type array * @default [] */ "aoDestroyCallback": [], /** * Get the number of records in the current record set, before filtering * @type function */ "fnRecordsTotal": function () { return _fnDataSource( this ) == 'ssp' ? this._iRecordsTotal * 1 : this.aiDisplayMaster.length; }, /** * Get the number of records in the current record set, after filtering * @type function */ "fnRecordsDisplay": function () { return _fnDataSource( this ) == 'ssp' ? this._iRecordsDisplay * 1 : this.aiDisplay.length; }, /** * Get the display end point - aiDisplay index * @type function */ "fnDisplayEnd": function () { var len = this._iDisplayLength, start = this._iDisplayStart, calc = start + len, records = this.aiDisplay.length, features = this.oFeatures, paginate = features.bPaginate; if ( features.bServerSide ) { return paginate === false || len === -1 ? start + records : Math.min( start+len, this._iRecordsDisplay ); } else { return ! paginate || calc>records || len===-1 ? records : calc; } }, /** * The DataTables object for this table * @type object * @default null */ "oInstance": null, /** * Unique identifier for each instance of the DataTables object. If there * is an ID on the table node, then it takes that value, otherwise an * incrementing internal counter is used. * @type string * @default null */ "sInstance": null, /** * tabindex attribute value that is added to DataTables control elements, allowing * keyboard navigation of the table and its controls. */ "iTabIndex": 0, /** * DIV container for the footer scrolling table if scrolling */ "nScrollHead": null, /** * DIV container for the footer scrolling table if scrolling */ "nScrollFoot": null, /** * Last applied sort * @type array * @default [] */ "aLastSort": [], /** * Stored plug-in instances * @type object * @default {} */ "oPlugins": {}, /** * Function used to get a row's id from the row's data * @type function * @default null */ "rowIdFn": null, /** * Data location where to store a row's id * @type string * @default null */ "rowId": null }; /** * Extension object for DataTables that is used to provide all extension * options. * * Note that the `DataTable.ext` object is available through * `jQuery.fn.dataTable.ext` where it may be accessed and manipulated. It is * also aliased to `jQuery.fn.dataTableExt` for historic reasons. * @namespace * @extends DataTable.models.ext */ /** * DataTables extensions * * This namespace acts as a collection area for plug-ins that can be used to * extend DataTables capabilities. Indeed many of the build in methods * use this method to provide their own capabilities (sorting methods for * example). * * Note that this namespace is aliased to `jQuery.fn.dataTableExt` for legacy * reasons * * @namespace */ DataTable.ext = _ext = { /** * Buttons. For use with the Buttons extension for DataTables. This is * defined here so other extensions can define buttons regardless of load * order. It is _not_ used by DataTables core. * * @type object * @default {} */ buttons: {}, /** * Element class names * * @type object * @default {} */ classes: {}, /** * DataTables build type (expanded by the download builder) * * @type string */ builder: "-source-", /** * Error reporting. * * How should DataTables report an error. Can take the value 'alert', * 'throw', 'none' or a function. * * @type string|function * @default alert */ errMode: "alert", /** * Feature plug-ins. * * This is an array of objects which describe the feature plug-ins that are * available to DataTables. These feature plug-ins are then available for * use through the `dom` initialisation option. * * Each feature plug-in is described by an object which must have the * following properties: * * * `fnInit` - function that is used to initialise the plug-in, * * `cFeature` - a character so the feature can be enabled by the `dom` * instillation option. This is case sensitive. * * The `fnInit` function has the following input parameters: * * 1. `{object}` DataTables settings object: see * {@link DataTable.models.oSettings} * * And the following return is expected: * * * {node|null} The element which contains your feature. Note that the * return may also be void if your plug-in does not require to inject any * DOM elements into DataTables control (`dom`) - for example this might * be useful when developing a plug-in which allows table control via * keyboard entry * * @type array * * @example * $.fn.dataTable.ext.features.push( { * "fnInit": function( oSettings ) { * return new TableTools( { "oDTSettings": oSettings } ); * }, * "cFeature": "T" * } ); */ feature: [], /** * Row searching. * * This method of searching is complimentary to the default type based * searching, and a lot more comprehensive as it allows you complete control * over the searching logic. Each element in this array is a function * (parameters described below) that is called for every row in the table, * and your logic decides if it should be included in the searching data set * or not. * * Searching functions have the following input parameters: * * 1. `{object}` DataTables settings object: see * {@link DataTable.models.oSettings} * 2. `{array|object}` Data for the row to be processed (same as the * original format that was passed in as the data source, or an array * from a DOM data source * 3. `{int}` Row index ({@link DataTable.models.oSettings.aoData}), which * can be useful to retrieve the `TR` element if you need DOM interaction. * * And the following return is expected: * * * {boolean} Include the row in the searched result set (true) or not * (false) * * Note that as with the main search ability in DataTables, technically this * is "filtering", since it is subtractive. However, for consistency in * naming we call it searching here. * * @type array * @default [] * * @example * // The following example shows custom search being applied to the * // fourth column (i.e. the data[3] index) based on two input values * // from the end-user, matching the data in a certain range. * $.fn.dataTable.ext.search.push( * function( settings, data, dataIndex ) { * var min = document.getElementById('min').value * 1; * var max = document.getElementById('max').value * 1; * var version = data[3] == "-" ? 0 : data[3]*1; * * if ( min == "" && max == "" ) { * return true; * } * else if ( min == "" && version < max ) { * return true; * } * else if ( min < version && "" == max ) { * return true; * } * else if ( min < version && version < max ) { * return true; * } * return false; * } * ); */ search: [], /** * Selector extensions * * The `selector` option can be used to extend the options available for the * selector modifier options (`selector-modifier` object data type) that * each of the three built in selector types offer (row, column and cell + * their plural counterparts). For example the Select extension uses this * mechanism to provide an option to select only rows, columns and cells * that have been marked as selected by the end user (`{selected: true}`), * which can be used in conjunction with the existing built in selector * options. * * Each property is an array to which functions can be pushed. The functions * take three attributes: * * * Settings object for the host table * * Options object (`selector-modifier` object type) * * Array of selected item indexes * * The return is an array of the resulting item indexes after the custom * selector has been applied. * * @type object */ selector: { cell: [], column: [], row: [] }, /** * Internal functions, exposed for used in plug-ins. * * Please note that you should not need to use the internal methods for * anything other than a plug-in (and even then, try to avoid if possible). * The internal function may change between releases. * * @type object * @default {} */ internal: {}, /** * Legacy configuration options. Enable and disable legacy options that * are available in DataTables. * * @type object */ legacy: { /** * Enable / disable DataTables 1.9 compatible server-side processing * requests * * @type boolean * @default null */ ajax: null }, /** * Pagination plug-in methods. * * Each entry in this object is a function and defines which buttons should * be shown by the pagination rendering method that is used for the table: * {@link DataTable.ext.renderer.pageButton}. The renderer addresses how the * buttons are displayed in the document, while the functions here tell it * what buttons to display. This is done by returning an array of button * descriptions (what each button will do). * * Pagination types (the four built in options and any additional plug-in * options defined here) can be used through the `paginationType` * initialisation parameter. * * The functions defined take two parameters: * * 1. `{int} page` The current page index * 2. `{int} pages` The number of pages in the table * * Each function is expected to return an array where each element of the * array can be one of: * * * `first` - Jump to first page when activated * * `last` - Jump to last page when activated * * `previous` - Show previous page when activated * * `next` - Show next page when activated * * `{int}` - Show page of the index given * * `{array}` - A nested array containing the above elements to add a * containing 'DIV' element (might be useful for styling). * * Note that DataTables v1.9- used this object slightly differently whereby * an object with two functions would be defined for each plug-in. That * ability is still supported by DataTables 1.10+ to provide backwards * compatibility, but this option of use is now decremented and no longer * documented in DataTables 1.10+. * * @type object * @default {} * * @example * // Show previous, next and current page buttons only * $.fn.dataTableExt.oPagination.current = function ( page, pages ) { * return [ 'previous', page, 'next' ]; * }; */ pager: {}, renderer: { pageButton: {}, header: {} }, /** * Ordering plug-ins - custom data source * * The extension options for ordering of data available here is complimentary * to the default type based ordering that DataTables typically uses. It * allows much greater control over the the data that is being used to * order a column, but is necessarily therefore more complex. * * This type of ordering is useful if you want to do ordering based on data * live from the DOM (for example the contents of an 'input' element) rather * than just the static string that DataTables knows of. * * The way these plug-ins work is that you create an array of the values you * wish to be ordering for the column in question and then return that * array. The data in the array much be in the index order of the rows in * the table (not the currently ordering order!). Which order data gathering * function is run here depends on the `dt-init columns.orderDataType` * parameter that is used for the column (if any). * * The functions defined take two parameters: * * 1. `{object}` DataTables settings object: see * {@link DataTable.models.oSettings} * 2. `{int}` Target column index * * Each function is expected to return an array: * * * `{array}` Data for the column to be ordering upon * * @type array * * @example * // Ordering using `input` node values * $.fn.dataTable.ext.order['dom-text'] = function ( settings, col ) * { * return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) { * return $('input', td).val(); * } ); * } */ order: {}, /** * Type based plug-ins. * * Each column in DataTables has a type assigned to it, either by automatic * detection or by direct assignment using the `type` option for the column. * The type of a column will effect how it is ordering and search (plug-ins * can also make use of the column type if required). * * @namespace */ type: { /** * Type detection functions. * * The functions defined in this object are used to automatically detect * a column's type, making initialisation of DataTables super easy, even * when complex data is in the table. * * The functions defined take two parameters: * * 1. `{*}` Data from the column cell to be analysed * 2. `{settings}` DataTables settings object. This can be used to * perform context specific type detection - for example detection * based on language settings such as using a comma for a decimal * place. Generally speaking the options from the settings will not * be required * * Each function is expected to return: * * * `{string|null}` Data type detected, or null if unknown (and thus * pass it on to the other type detection functions. * * @type array * * @example * // Currency type detection plug-in: * $.fn.dataTable.ext.type.detect.push( * function ( data, settings ) { * // Check the numeric part * if ( ! $.isNumeric( data.substring(1) ) ) { * return null; * } * * // Check prefixed by currency * if ( data.charAt(0) == '$' || data.charAt(0) == '&pound;' ) { * return 'currency'; * } * return null; * } * ); */ detect: [], /** * Type based search formatting. * * The type based searching functions can be used to pre-format the * data to be search on. For example, it can be used to strip HTML * tags or to de-format telephone numbers for numeric only searching. * * Note that is a search is not defined for a column of a given type, * no search formatting will be performed. * * Pre-processing of searching data plug-ins - When you assign the sType * for a column (or have it automatically detected for you by DataTables * or a type detection plug-in), you will typically be using this for * custom sorting, but it can also be used to provide custom searching * by allowing you to pre-processing the data and returning the data in * the format that should be searched upon. This is done by adding * functions this object with a parameter name which matches the sType * for that target column. This is the corollary of <i>afnSortData</i> * for searching data. * * The functions defined take a single parameter: * * 1. `{*}` Data from the column cell to be prepared for searching * * Each function is expected to return: * * * `{string|null}` Formatted string that will be used for the searching. * * @type object * @default {} * * @example * $.fn.dataTable.ext.type.search['title-numeric'] = function ( d ) { * return d.replace(/\n/g," ").replace( /<.*?>/g, "" ); * } */ search: {}, /** * Type based ordering. * * The column type tells DataTables what ordering to apply to the table * when a column is sorted upon. The order for each type that is defined, * is defined by the functions available in this object. * * Each ordering option can be described by three properties added to * this object: * * * `{type}-pre` - Pre-formatting function * * `{type}-asc` - Ascending order function * * `{type}-desc` - Descending order function * * All three can be used together, only `{type}-pre` or only * `{type}-asc` and `{type}-desc` together. It is generally recommended * that only `{type}-pre` is used, as this provides the optimal * implementation in terms of speed, although the others are provided * for compatibility with existing Javascript sort functions. * * `{type}-pre`: Functions defined take a single parameter: * * 1. `{*}` Data from the column cell to be prepared for ordering * * And return: * * * `{*}` Data to be sorted upon * * `{type}-asc` and `{type}-desc`: Functions are typical Javascript sort * functions, taking two parameters: * * 1. `{*}` Data to compare to the second parameter * 2. `{*}` Data to compare to the first parameter * * And returning: * * * `{*}` Ordering match: <0 if first parameter should be sorted lower * than the second parameter, ===0 if the two parameters are equal and * >0 if the first parameter should be sorted height than the second * parameter. * * @type object * @default {} * * @example * // Numeric ordering of formatted numbers with a pre-formatter * $.extend( $.fn.dataTable.ext.type.order, { * "string-pre": function(x) { * a = (a === "-" || a === "") ? 0 : a.replace( /[^\d\-\.]/g, "" ); * return parseFloat( a ); * } * } ); * * @example * // Case-sensitive string ordering, with no pre-formatting method * $.extend( $.fn.dataTable.ext.order, { * "string-case-asc": function(x,y) { * return ((x < y) ? -1 : ((x > y) ? 1 : 0)); * }, * "string-case-desc": function(x,y) { * return ((x < y) ? 1 : ((x > y) ? -1 : 0)); * } * } ); */ order: {} }, /** * Unique DataTables instance counter * * @type int * @private */ _unique: 0, // // Depreciated // The following properties are retained for backwards compatiblity only. // The should not be used in new projects and will be removed in a future // version // /** * Version check function. * @type function * @depreciated Since 1.10 */ fnVersionCheck: DataTable.fnVersionCheck, /** * Index for what 'this' index API functions should use * @type int * @deprecated Since v1.10 */ iApiIndex: 0, /** * jQuery UI class container * @type object * @deprecated Since v1.10 */ oJUIClasses: {}, /** * Software version * @type string * @deprecated Since v1.10 */ sVersion: DataTable.version }; // // Backwards compatibility. Alias to pre 1.10 Hungarian notation counter parts // $.extend( _ext, { afnFiltering: _ext.search, aTypes: _ext.type.detect, ofnSearch: _ext.type.search, oSort: _ext.type.order, afnSortData: _ext.order, aoFeatures: _ext.feature, oApi: _ext.internal, oStdClasses: _ext.classes, oPagination: _ext.pager } ); $.extend( DataTable.ext.classes, { "sTable": "dataTable", "sNoFooter": "no-footer", /* Paging buttons */ "sPageButton": "paginate_button", "sPageButtonActive": "current", "sPageButtonDisabled": "disabled", /* Striping classes */ "sStripeOdd": "odd", "sStripeEven": "even", /* Empty row */ "sRowEmpty": "dataTables_empty", /* Features */ "sWrapper": "dataTables_wrapper", "sFilter": "dataTables_filter", "sInfo": "dataTables_info", "sPaging": "dataTables_paginate paging_", /* Note that the type is postfixed */ "sLength": "dataTables_length", "sProcessing": "dataTables_processing", /* Sorting */ "sSortAsc": "sorting_asc", "sSortDesc": "sorting_desc", "sSortable": "sorting", /* Sortable in both directions */ "sSortableAsc": "sorting_asc_disabled", "sSortableDesc": "sorting_desc_disabled", "sSortableNone": "sorting_disabled", "sSortColumn": "sorting_", /* Note that an int is postfixed for the sorting order */ /* Filtering */ "sFilterInput": "", /* Page length */ "sLengthSelect": "", /* Scrolling */ "sScrollWrapper": "dataTables_scroll", "sScrollHead": "dataTables_scrollHead", "sScrollHeadInner": "dataTables_scrollHeadInner", "sScrollBody": "dataTables_scrollBody", "sScrollFoot": "dataTables_scrollFoot", "sScrollFootInner": "dataTables_scrollFootInner", /* Misc */ "sHeaderTH": "", "sFooterTH": "", // Deprecated "sSortJUIAsc": "", "sSortJUIDesc": "", "sSortJUI": "", "sSortJUIAscAllowed": "", "sSortJUIDescAllowed": "", "sSortJUIWrapper": "", "sSortIcon": "", "sJUIHeader": "", "sJUIFooter": "" } ); var extPagination = DataTable.ext.pager; function _numbers ( page, pages ) { var numbers = [], buttons = extPagination.numbers_length, half = Math.floor( buttons / 2 ), i = 1; if ( pages <= buttons ) { numbers = _range( 0, pages ); } else if ( page <= half ) { numbers = _range( 0, buttons-2 ); numbers.push( 'ellipsis' ); numbers.push( pages-1 ); } else if ( page >= pages - 1 - half ) { numbers = _range( pages-(buttons-2), pages ); numbers.splice( 0, 0, 'ellipsis' ); // no unshift in ie6 numbers.splice( 0, 0, 0 ); } else { numbers = _range( page-half+2, page+half-1 ); numbers.push( 'ellipsis' ); numbers.push( pages-1 ); numbers.splice( 0, 0, 'ellipsis' ); numbers.splice( 0, 0, 0 ); } numbers.DT_el = 'span'; return numbers; } $.extend( extPagination, { simple: function ( page, pages ) { return [ 'previous', 'next' ]; }, full: function ( page, pages ) { return [ 'first', 'previous', 'next', 'last' ]; }, numbers: function ( page, pages ) { return [ _numbers(page, pages) ]; }, simple_numbers: function ( page, pages ) { return [ 'previous', _numbers(page, pages), 'next' ]; }, full_numbers: function ( page, pages ) { return [ 'first', 'previous', _numbers(page, pages), 'next', 'last' ]; }, first_last_numbers: function (page, pages) { return ['first', _numbers(page, pages), 'last']; }, // For testing and plug-ins to use _numbers: _numbers, // Number of number buttons (including ellipsis) to show. _Must be odd!_ numbers_length: 7 } ); $.extend( true, DataTable.ext.renderer, { pageButton: { _: function ( settings, host, idx, buttons, page, pages ) { var classes = settings.oClasses; var lang = settings.oLanguage.oPaginate; var aria = settings.oLanguage.oAria.paginate || {}; var btnDisplay, btnClass, counter=0; var attach = function( container, buttons ) { var i, ien, node, button; var clickHandler = function ( e ) { _fnPageChange( settings, e.data.action, true ); }; for ( i=0, ien=buttons.length ; i<ien ; i++ ) { button = buttons[i]; if ( $.isArray( button ) ) { var inner = $( '<'+(button.DT_el || 'div')+'/>' ) .appendTo( container ); attach( inner, button ); } else { btnDisplay = null; btnClass = ''; switch ( button ) { case 'ellipsis': container.append('<span class="ellipsis">&#x2026;</span>'); break; case 'first': btnDisplay = lang.sFirst; btnClass = button + (page > 0 ? '' : ' '+classes.sPageButtonDisabled); break; case 'previous': btnDisplay = lang.sPrevious; btnClass = button + (page > 0 ? '' : ' '+classes.sPageButtonDisabled); break; case 'next': btnDisplay = lang.sNext; btnClass = button + (page < pages-1 ? '' : ' '+classes.sPageButtonDisabled); break; case 'last': btnDisplay = lang.sLast; btnClass = button + (page < pages-1 ? '' : ' '+classes.sPageButtonDisabled); break; default: btnDisplay = button + 1; btnClass = page === button ? classes.sPageButtonActive : ''; break; } if ( btnDisplay !== null ) { node = $('<a>', { 'class': classes.sPageButton+' '+btnClass, 'aria-controls': settings.sTableId, 'aria-label': aria[ button ], 'data-dt-idx': counter, 'tabindex': settings.iTabIndex, 'id': idx === 0 && typeof button === 'string' ? settings.sTableId +'_'+ button : null } ) .html( btnDisplay ) .appendTo( container ); _fnBindAction( node, {action: button}, clickHandler ); counter++; } } } }; // IE9 throws an 'unknown error' if document.activeElement is used // inside an iframe or frame. Try / catch the error. Not good for // accessibility, but neither are frames. var activeEl; try { // Because this approach is destroying and recreating the paging // elements, focus is lost on the select button which is bad for // accessibility. So we want to restore focus once the draw has // completed activeEl = $(host).find(document.activeElement).data('dt-idx'); } catch (e) {} attach( $(host).empty(), buttons ); if ( activeEl !== undefined ) { $(host).find( '[data-dt-idx='+activeEl+']' ).focus(); } } } } ); // Built in type detection. See model.ext.aTypes for information about // what is required from this methods. $.extend( DataTable.ext.type.detect, [ // Plain numbers - first since V8 detects some plain numbers as dates // e.g. Date.parse('55') (but not all, e.g. Date.parse('22')...). function ( d, settings ) { var decimal = settings.oLanguage.sDecimal; return _isNumber( d, decimal ) ? 'num'+decimal : null; }, // Dates (only those recognised by the browser's Date.parse) function ( d, settings ) { // V8 tries _very_ hard to make a string passed into `Date.parse()` // valid, so we need to use a regex to restrict date formats. Use a // plug-in for anything other than ISO8601 style strings if ( d && !(d instanceof Date) && ! _re_date.test(d) ) { return null; } var parsed = Date.parse(d); return (parsed !== null && !isNaN(parsed)) || _empty(d) ? 'date' : null; }, // Formatted numbers function ( d, settings ) { var decimal = settings.oLanguage.sDecimal; return _isNumber( d, decimal, true ) ? 'num-fmt'+decimal : null; }, // HTML numeric function ( d, settings ) { var decimal = settings.oLanguage.sDecimal; return _htmlNumeric( d, decimal ) ? 'html-num'+decimal : null; }, // HTML numeric, formatted function ( d, settings ) { var decimal = settings.oLanguage.sDecimal; return _htmlNumeric( d, decimal, true ) ? 'html-num-fmt'+decimal : null; }, // HTML (this is strict checking - there must be html) function ( d, settings ) { return _empty( d ) || (typeof d === 'string' && d.indexOf('<') !== -1) ? 'html' : null; } ] ); // Filter formatting functions. See model.ext.ofnSearch for information about // what is required from these methods. // // Note that additional search methods are added for the html numbers and // html formatted numbers by `_addNumericSort()` when we know what the decimal // place is $.extend( DataTable.ext.type.search, { html: function ( data ) { return _empty(data) ? data : typeof data === 'string' ? data .replace( _re_new_lines, " " ) .replace( _re_html, "" ) : ''; }, string: function ( data ) { return _empty(data) ? data : typeof data === 'string' ? data.replace( _re_new_lines, " " ) : data; } } ); var __numericReplace = function ( d, decimalPlace, re1, re2 ) { if ( d !== 0 && (!d || d === '-') ) { return -Infinity; } // If a decimal place other than `.` is used, it needs to be given to the // function so we can detect it and replace with a `.` which is the only // decimal place Javascript recognises - it is not locale aware. if ( decimalPlace ) { d = _numToDecimal( d, decimalPlace ); } if ( d.replace ) { if ( re1 ) { d = d.replace( re1, '' ); } if ( re2 ) { d = d.replace( re2, '' ); } } return d * 1; }; // Add the numeric 'deformatting' functions for sorting and search. This is done // in a function to provide an easy ability for the language options to add // additional methods if a non-period decimal place is used. function _addNumericSort ( decimalPlace ) { $.each( { // Plain numbers "num": function ( d ) { return __numericReplace( d, decimalPlace ); }, // Formatted numbers "num-fmt": function ( d ) { return __numericReplace( d, decimalPlace, _re_formatted_numeric ); }, // HTML numeric "html-num": function ( d ) { return __numericReplace( d, decimalPlace, _re_html ); }, // HTML numeric, formatted "html-num-fmt": function ( d ) { return __numericReplace( d, decimalPlace, _re_html, _re_formatted_numeric ); } }, function ( key, fn ) { // Add the ordering method _ext.type.order[ key+decimalPlace+'-pre' ] = fn; // For HTML types add a search formatter that will strip the HTML if ( key.match(/^html\-/) ) { _ext.type.search[ key+decimalPlace ] = _ext.type.search.html; } } ); } // Default sort methods $.extend( _ext.type.order, { // Dates "date-pre": function ( d ) { return Date.parse( d ) || -Infinity; }, // html "html-pre": function ( a ) { return _empty(a) ? '' : a.replace ? a.replace( /<.*?>/g, "" ).toLowerCase() : a+''; }, // string "string-pre": function ( a ) { // This is a little complex, but faster than always calling toString, // http://jsperf.com/tostring-v-check return _empty(a) ? '' : typeof a === 'string' ? a.toLowerCase() : ! a.toString ? '' : a.toString(); }, // string-asc and -desc are retained only for compatibility with the old // sort methods "string-asc": function ( x, y ) { return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }, "string-desc": function ( x, y ) { return ((x < y) ? 1 : ((x > y) ? -1 : 0)); } } ); // Numeric sorting types - order doesn't matter here _addNumericSort( '' ); $.extend( true, DataTable.ext.renderer, { header: { _: function ( settings, cell, column, classes ) { // No additional mark-up required // Attach a sort listener to update on sort - note that using the // `DT` namespace will allow the event to be removed automatically // on destroy, while the `dt` namespaced event is the one we are // listening for $(settings.nTable).on( 'order.dt.DT', function ( e, ctx, sorting, columns ) { if ( settings !== ctx ) { // need to check this this is the host return; // table, not a nested one } var colIdx = column.idx; cell .removeClass( column.sSortingClass +' '+ classes.sSortAsc +' '+ classes.sSortDesc ) .addClass( columns[ colIdx ] == 'asc' ? classes.sSortAsc : columns[ colIdx ] == 'desc' ? classes.sSortDesc : column.sSortingClass ); } ); }, jqueryui: function ( settings, cell, column, classes ) { $('<div/>') .addClass( classes.sSortJUIWrapper ) .append( cell.contents() ) .append( $('<span/>') .addClass( classes.sSortIcon+' '+column.sSortingClassJUI ) ) .appendTo( cell ); // Attach a sort listener to update on sort $(settings.nTable).on( 'order.dt.DT', function ( e, ctx, sorting, columns ) { if ( settings !== ctx ) { return; } var colIdx = column.idx; cell .removeClass( classes.sSortAsc +" "+classes.sSortDesc ) .addClass( columns[ colIdx ] == 'asc' ? classes.sSortAsc : columns[ colIdx ] == 'desc' ? classes.sSortDesc : column.sSortingClass ); cell .find( 'span.'+classes.sSortIcon ) .removeClass( classes.sSortJUIAsc +" "+ classes.sSortJUIDesc +" "+ classes.sSortJUI +" "+ classes.sSortJUIAscAllowed +" "+ classes.sSortJUIDescAllowed ) .addClass( columns[ colIdx ] == 'asc' ? classes.sSortJUIAsc : columns[ colIdx ] == 'desc' ? classes.sSortJUIDesc : column.sSortingClassJUI ); } ); } } } ); /* * Public helper functions. These aren't used internally by DataTables, or * called by any of the options passed into DataTables, but they can be used * externally by developers working with DataTables. They are helper functions * to make working with DataTables a little bit easier. */ var __htmlEscapeEntities = function ( d ) { return typeof d === 'string' ? d.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;') : d; }; /** * Helpers for `columns.render`. * * The options defined here can be used with the `columns.render` initialisation * option to provide a display renderer. The following functions are defined: * * * `number` - Will format numeric data (defined by `columns.data`) for * display, retaining the original unformatted data for sorting and filtering. * It takes 5 parameters: * * `string` - Thousands grouping separator * * `string` - Decimal point indicator * * `integer` - Number of decimal points to show * * `string` (optional) - Prefix. * * `string` (optional) - Postfix (/suffix). * * `text` - Escape HTML to help prevent XSS attacks. It has no optional * parameters. * * @example * // Column definition using the number renderer * { * data: "salary", * render: $.fn.dataTable.render.number( '\'', '.', 0, '$' ) * } * * @namespace */ DataTable.render = { number: function ( thousands, decimal, precision, prefix, postfix ) { return { display: function ( d ) { if ( typeof d !== 'number' && typeof d !== 'string' ) { return d; } var negative = d < 0 ? '-' : ''; var flo = parseFloat( d ); // If NaN then there isn't much formatting that we can do - just // return immediately, escaping any HTML (this was supposed to // be a number after all) if ( isNaN( flo ) ) { return __htmlEscapeEntities( d ); } flo = flo.toFixed( precision ); d = Math.abs( flo ); var intPart = parseInt( d, 10 ); var floatPart = precision ? decimal+(d - intPart).toFixed( precision ).substring( 2 ): ''; return negative + (prefix||'') + intPart.toString().replace( /\B(?=(\d{3})+(?!\d))/g, thousands ) + floatPart + (postfix||''); } }; }, text: function () { return { display: __htmlEscapeEntities }; } }; /* * This is really a good bit rubbish this method of exposing the internal methods * publicly... - To be fixed in 2.0 using methods on the prototype */ /** * Create a wrapper function for exporting an internal functions to an external API. * @param {string} fn API function name * @returns {function} wrapped function * @memberof DataTable#internal */ function _fnExternApiFunc (fn) { return function() { var args = [_fnSettingsFromNode( this[DataTable.ext.iApiIndex] )].concat( Array.prototype.slice.call(arguments) ); return DataTable.ext.internal[fn].apply( this, args ); }; } /** * Reference to internal functions for use by plug-in developers. Note that * these methods are references to internal functions and are considered to be * private. If you use these methods, be aware that they are liable to change * between versions. * @namespace */ $.extend( DataTable.ext.internal, { _fnExternApiFunc: _fnExternApiFunc, _fnBuildAjax: _fnBuildAjax, _fnAjaxUpdate: _fnAjaxUpdate, _fnAjaxParameters: _fnAjaxParameters, _fnAjaxUpdateDraw: _fnAjaxUpdateDraw, _fnAjaxDataSrc: _fnAjaxDataSrc, _fnAddColumn: _fnAddColumn, _fnColumnOptions: _fnColumnOptions, _fnAdjustColumnSizing: _fnAdjustColumnSizing, _fnVisibleToColumnIndex: _fnVisibleToColumnIndex, _fnColumnIndexToVisible: _fnColumnIndexToVisible, _fnVisbleColumns: _fnVisbleColumns, _fnGetColumns: _fnGetColumns, _fnColumnTypes: _fnColumnTypes, _fnApplyColumnDefs: _fnApplyColumnDefs, _fnHungarianMap: _fnHungarianMap, _fnCamelToHungarian: _fnCamelToHungarian, _fnLanguageCompat: _fnLanguageCompat, _fnBrowserDetect: _fnBrowserDetect, _fnAddData: _fnAddData, _fnAddTr: _fnAddTr, _fnNodeToDataIndex: _fnNodeToDataIndex, _fnNodeToColumnIndex: _fnNodeToColumnIndex, _fnGetCellData: _fnGetCellData, _fnSetCellData: _fnSetCellData, _fnSplitObjNotation: _fnSplitObjNotation, _fnGetObjectDataFn: _fnGetObjectDataFn, _fnSetObjectDataFn: _fnSetObjectDataFn, _fnGetDataMaster: _fnGetDataMaster, _fnClearTable: _fnClearTable, _fnDeleteIndex: _fnDeleteIndex, _fnInvalidate: _fnInvalidate, _fnGetRowElements: _fnGetRowElements, _fnCreateTr: _fnCreateTr, _fnBuildHead: _fnBuildHead, _fnDrawHead: _fnDrawHead, _fnDraw: _fnDraw, _fnReDraw: _fnReDraw, _fnAddOptionsHtml: _fnAddOptionsHtml, _fnDetectHeader: _fnDetectHeader, _fnGetUniqueThs: _fnGetUniqueThs, _fnFeatureHtmlFilter: _fnFeatureHtmlFilter, _fnFilterComplete: _fnFilterComplete, _fnFilterCustom: _fnFilterCustom, _fnFilterColumn: _fnFilterColumn, _fnFilter: _fnFilter, _fnFilterCreateSearch: _fnFilterCreateSearch, _fnEscapeRegex: _fnEscapeRegex, _fnFilterData: _fnFilterData, _fnFeatureHtmlInfo: _fnFeatureHtmlInfo, _fnUpdateInfo: _fnUpdateInfo, _fnInfoMacros: _fnInfoMacros, _fnInitialise: _fnInitialise, _fnInitComplete: _fnInitComplete, _fnLengthChange: _fnLengthChange, _fnFeatureHtmlLength: _fnFeatureHtmlLength, _fnFeatureHtmlPaginate: _fnFeatureHtmlPaginate, _fnPageChange: _fnPageChange, _fnFeatureHtmlProcessing: _fnFeatureHtmlProcessing, _fnProcessingDisplay: _fnProcessingDisplay, _fnFeatureHtmlTable: _fnFeatureHtmlTable, _fnScrollDraw: _fnScrollDraw, _fnApplyToChildren: _fnApplyToChildren, _fnCalculateColumnWidths: _fnCalculateColumnWidths, _fnThrottle: _fnThrottle, _fnConvertToWidth: _fnConvertToWidth, _fnGetWidestNode: _fnGetWidestNode, _fnGetMaxLenString: _fnGetMaxLenString, _fnStringToCss: _fnStringToCss, _fnSortFlatten: _fnSortFlatten, _fnSort: _fnSort, _fnSortAria: _fnSortAria, _fnSortListener: _fnSortListener, _fnSortAttachListener: _fnSortAttachListener, _fnSortingClasses: _fnSortingClasses, _fnSortData: _fnSortData, _fnSaveState: _fnSaveState, _fnLoadState: _fnLoadState, _fnSettingsFromNode: _fnSettingsFromNode, _fnLog: _fnLog, _fnMap: _fnMap, _fnBindAction: _fnBindAction, _fnCallbackReg: _fnCallbackReg, _fnCallbackFire: _fnCallbackFire, _fnLengthOverflow: _fnLengthOverflow, _fnRenderer: _fnRenderer, _fnDataSource: _fnDataSource, _fnRowAttributes: _fnRowAttributes, _fnCalculateEnd: function () {} // Used by a lot of plug-ins, but redundant // in 1.10, so this dead-end function is // added to prevent errors } ); // jQuery access $.fn.dataTable = DataTable; // Provide access to the host jQuery object (circular reference) DataTable.$ = $; // Legacy aliases $.fn.dataTableSettings = DataTable.settings; $.fn.dataTableExt = DataTable.ext; // With a capital `D` we return a DataTables API instance rather than a // jQuery object $.fn.DataTable = function ( opts ) { return $(this).dataTable( opts ).api(); }; // All properties that are available to $.fn.dataTable should also be // available on $.fn.DataTable $.each( DataTable, function ( prop, val ) { $.fn.DataTable[ prop ] = val; } ); // Information about events fired by DataTables - for documentation. /** * Draw event, fired whenever the table is redrawn on the page, at the same * point as fnDrawCallback. This may be useful for binding events or * performing calculations when the table is altered at all. * @name DataTable#draw.dt * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} */ /** * Search event, fired when the searching applied to the table (using the * built-in global search, or column filters) is altered. * @name DataTable#search.dt * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} */ /** * Page change event, fired when the paging of the table is altered. * @name DataTable#page.dt * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} */ /** * Order event, fired when the ordering applied to the table is altered. * @name DataTable#order.dt * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} */ /** * DataTables initialisation complete event, fired when the table is fully * drawn, including Ajax data loaded, if Ajax data is required. * @name DataTable#init.dt * @event * @param {event} e jQuery event object * @param {object} oSettings DataTables settings object * @param {object} json The JSON object request from the server - only * present if client-side Ajax sourced data is used</li></ol> */ /** * State save event, fired when the table has changed state a new state save * is required. This event allows modification of the state saving object * prior to actually doing the save, including addition or other state * properties (for plug-ins) or modification of a DataTables core property. * @name DataTable#stateSaveParams.dt * @event * @param {event} e jQuery event object * @param {object} oSettings DataTables settings object * @param {object} json The state information to be saved */ /** * State load event, fired when the table is loading state from the stored * data, but prior to the settings object being modified by the saved state * - allowing modification of the saved state is required or loading of * state for a plug-in. * @name DataTable#stateLoadParams.dt * @event * @param {event} e jQuery event object * @param {object} oSettings DataTables settings object * @param {object} json The saved state information */ /** * State loaded event, fired when state has been loaded from stored data and * the settings object has been modified by the loaded data. * @name DataTable#stateLoaded.dt * @event * @param {event} e jQuery event object * @param {object} oSettings DataTables settings object * @param {object} json The saved state information */ /** * Processing event, fired when DataTables is doing some kind of processing * (be it, order, searcg or anything else). It can be used to indicate to * the end user that there is something happening, or that something has * finished. * @name DataTable#processing.dt * @event * @param {event} e jQuery event object * @param {object} oSettings DataTables settings object * @param {boolean} bShow Flag for if DataTables is doing processing or not */ /** * Ajax (XHR) event, fired whenever an Ajax request is completed from a * request to made to the server for new data. This event is called before * DataTables processed the returned data, so it can also be used to pre- * process the data returned from the server, if needed. * * Note that this trigger is called in `fnServerData`, if you override * `fnServerData` and which to use this event, you need to trigger it in you * success function. * @name DataTable#xhr.dt * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} * @param {object} json JSON returned from the server * * @example * // Use a custom property returned from the server in another DOM element * $('#table').dataTable().on('xhr.dt', function (e, settings, json) { * $('#status').html( json.status ); * } ); * * @example * // Pre-process the data returned from the server * $('#table').dataTable().on('xhr.dt', function (e, settings, json) { * for ( var i=0, ien=json.aaData.length ; i<ien ; i++ ) { * json.aaData[i].sum = json.aaData[i].one + json.aaData[i].two; * } * // Note no return - manipulate the data directly in the JSON object. * } ); */ /** * Destroy event, fired when the DataTable is destroyed by calling fnDestroy * or passing the bDestroy:true parameter in the initialisation object. This * can be used to remove bound events, added DOM nodes, etc. * @name DataTable#destroy.dt * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} */ /** * Page length change event, fired when number of records to show on each * page (the length) is changed. * @name DataTable#length.dt * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} * @param {integer} len New length */ /** * Column sizing has changed. * @name DataTable#column-sizing.dt * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} */ /** * Column visibility has changed. * @name DataTable#column-visibility.dt * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} * @param {int} column Column index * @param {bool} vis `false` if column now hidden, or `true` if visible */ return $.fn.dataTable; }));
import SortDescending from "./SortDescending.svelte"; export { SortDescending }; export default SortDescending;
"use strict"; /* * Copyright (c) 2019 Rafael da Silva Rocha. */ exports.__esModule = true; /** * @fileoverview TypeScript declaration tests. * @see https://github.com/rochars/wave-resampler */ var index_js_1 = require("../../index.js"); var samples = index_js_1.resample([1], 1, 2);
import Constants from 'expo-constants'; import { UnavailabilityError } from 'expo-errors'; import invariant from 'invariant'; import ExpoGoogleSignIn from './ExpoGoogleSignIn'; import GoogleUser from './GoogleUser'; export const { ERRORS, SCOPES, TYPES } = ExpoGoogleSignIn; const DEFAULT_SCOPES = [SCOPES.PROFILE, SCOPES.EMAIL]; let _initialization; let _options; let _currentUser = null; let _isClientUsageEnabled = false; function setCurrentUser(currentUser) { _currentUser = currentUser; return _currentUser; } function validateOptions(options) { if (!options) { return { scopes: DEFAULT_SCOPES, }; } if (options.isOfflineEnabled) { invariant(typeof options.webClientId === 'string' && options.webClientId !== '', 'GoogleSignIn: Offline access (isOfflineEnabled: true) requires a valid google server id `webClientId`'); } return { ...options, scopes: options.scopes || DEFAULT_SCOPES, }; } function validateOwnership() { invariant(_isClientUsageEnabled || Constants.appOwnership !== 'expo', 'expo-google-sign-in is not supported in the Expo Client because a custom URL scheme is required at build time. Please refer to the docs for usage outside of Expo www.npmjs.com/package/expo-google-sign-in'); } async function ensureGoogleIsInitializedAsync(options) { if (_initialization == null) { return initAsync(options); } return _initialization; } async function invokeAuthMethod(method) { if (!ExpoGoogleSignIn[method]) { throw new UnavailabilityError('GoogleSignIn', method); } await ensureGoogleIsInitializedAsync(); const payload = await ExpoGoogleSignIn[method](); let account = payload != null ? new GoogleUser(payload) : null; return setCurrentUser(account); } export function allowInClient() { _isClientUsageEnabled = true; } export function getCurrentUser() { return _currentUser; } export async function askForPlayServicesAsync() { return await getPlayServiceAvailability(true); } export async function getPlayServiceAvailability(shouldAsk = false) { validateOwnership(); if (ExpoGoogleSignIn.arePlayServicesAvailableAsync) { return await ExpoGoogleSignIn.arePlayServicesAvailableAsync(shouldAsk); } else { return true; } } export async function initAsync(options) { if (!ExpoGoogleSignIn.initAsync) { throw new UnavailabilityError('GoogleSignIn', 'initAsync'); } _options = validateOptions(options || _options || {}); const hasPlayServices = await getPlayServiceAvailability(); if (!hasPlayServices) { return; } _initialization = ExpoGoogleSignIn.initAsync(_options || {}); return _initialization; } export async function isSignedInAsync() { const user = await getCurrentUserAsync(); return user != null; } export async function isConnectedAsync() { return await ExpoGoogleSignIn.isConnectedAsync(); } export async function signInSilentlyAsync() { const isConnected = await isConnectedAsync(); if (isConnected) { try { const auth = await invokeAuthMethod('signInSilentlyAsync'); return auth; } catch (error) { /* Return null to create parity with Android */ if (error.code === ERRORS.SIGN_IN_REQUIRED) { return null; } throw error; } } return null; } export async function signInAsync() { try { const user = await invokeAuthMethod('signInAsync'); return { type: 'success', user }; } catch (error) { if (error.code === ERRORS.SIGN_IN_CANCELLED) { return { type: 'cancel', user: null }; } throw error; } } export async function signOutAsync() { await invokeAuthMethod('signOutAsync'); } export async function disconnectAsync() { await invokeAuthMethod('disconnectAsync'); } export async function getCurrentUserAsync() { return await invokeAuthMethod('getCurrentUserAsync'); } export async function getPhotoAsync(size = 128) { if (!ExpoGoogleSignIn.getPhotoAsync) { throw new UnavailabilityError('GoogleSignIn', 'getPhotoAsync'); } await ensureGoogleIsInitializedAsync(); return await ExpoGoogleSignIn.getPhotoAsync(size); } export { default as GoogleAuthData } from './GoogleAuthData'; export { default as GoogleAuthentication } from './GoogleAuthentication'; export { default as GoogleIdentity } from './GoogleIdentity'; export { default as GoogleUser } from './GoogleUser'; //# sourceMappingURL=GoogleSignIn.js.map
import Boom from '@hapi/boom'; import { uuid } from 'uuidv4'; import { knex } from '../db'; import Pokemon from '../models/pokemon'; import Purchase from '../models/purchase'; import PurchaseRecord from '../models/purchase_record'; import Inventory from '../models/inventory'; import Sold from '../models/sold'; import SoldRecord from '../models/sold_record'; /** * CreatePokemon. * * @param {*} newPokemon * @returns */ export function createPokemon(newPokemon) { return knex .select('pokemons.name') .from('pokemons') .where({ name: newPokemon.name }) .then(function (pokemon) { if (pokemon.length === 0) { return knex.transaction(function (t) { const pokemonId = uuid(); return knex('pokemons') .transacting(t) .insert({ ...newPokemon, id: pokemonId }) .then(function () { return knex('inventories').transacting(t).insert({ id: uuid(), count: 0, total_price: 0, pokemon_id: pokemonId }); }) .then(t.commit) .catch(t.rollback); }); } throw Boom.notFound('User not found'); }); } /** * CreatePurchaseRecord. * * @param {*} newPurchaseRecord * @returns */ export async function createPurchaseRecord(newPurchaseRecord) { const purchase = await new Purchase(newPurchaseRecord.purchase).save(); const purchaseRecords = newPurchaseRecord.purchaseRecords.map((record) => { const total_price = record.price * record.count; const pokemon_id = record.pokemon.id; delete record.price; delete record.pokemon; const newRecord = { ...record, purchase_id: purchase.id, total_price, pokemon_id, date: newPurchaseRecord.purchase.date }; return new PurchaseRecord(newRecord).save(); }); const newPurchaseRecords = await Promise.all(purchaseRecords); /* eslint-disable no-await-in-loop */ for (const record of newPurchaseRecords) { const inventory = await Inventory.where({ pokemon_id: record.attributes.pokemon_id }).fetch({ require: true }); const newCount = parseInt(record.attributes.count) + parseInt(inventory.attributes.count); const newTotalPrice = parseInt(record.attributes.total_price) + parseInt(inventory.attributes.total_price); const newInventoryParams = { count: newCount, total_price: newTotalPrice, updated_at: new Date() }; await new Inventory({ id: inventory.id }).save(newInventoryParams); } return { purchase, purchaseRecords: newPurchaseRecords }; } /** * CreateSoldRecord. * * @param {*} newSoldRecord * @returns */ export async function createSoldRecord(newSoldRecord) { const data = await knex.transaction(async function (t) { const createdSold = await knex('solds') .transacting(t) .insert({ ...newSoldRecord.sold, id: uuid() }) .returning(['id']) .then(async (sold) => { const soldRecords = newSoldRecord.soldRecords.map((record) => { const total_price = record.price * record.count; delete record.price; const pokemon_id = record.pokemon.id; delete record.pokemon; return { ...record, sold_id: sold[0].id, total_price, date: newSoldRecord.sold.date, pokemon_id, id: uuid() }; }); const createRecords = await knex('sold_records') .transacting(t) .insert(soldRecords) .returning(['id', 'pokemon_id', 'count', 'total_price']); return { sold, records: createRecords }; }); /* eslint-disable no-await-in-loop */ for (const record of createdSold.records) { const inventory = await knex('inventories').where({ pokemon_id: record.pokemon_id }).first(); const newCount = parseInt(inventory.count) - parseInt(record.count); if (newCount < 0) throw Boom.badRequest('Error Counts'); const newTotalPrice = parseInt(inventory.total_price) - parseInt(record.total_price); const newInventoryParams = { id: uuid(), count: newCount, total_price: newTotalPrice, updated_at: new Date() }; await knex('inventories').transacting(t).where({ id: inventory.id }).update(newInventoryParams); } return createdSold; }); return data; } /** * QueryPurchaseRecords. * * @returns */ export async function queryPurchaseRecords() { const data = await knex('purchases') .select([ knex.ref('purchase_records.id').as('purchase_record_id'), knex.ref('purchases.name').as('purchase_name'), knex.ref('purchases.status').as('purchase_status'), 'purchases.purchaser', 'purchases.date', 'purchases.split', 'purchase_records.purchase_id', 'purchase_records.count', 'purchase_records.total_price', 'purchase_records.pokemon_id', knex.ref('pokemons.name').as('pokemon_name') ]) .join('purchase_records', function () { this.on('purchases.id', '=', 'purchase_records.purchase_id'); this.andOnVal('purchases.status', '=', 'active'); }) .join('pokemons', 'purchase_records.pokemon_id', '=', 'pokemons.id'); const tempData = {}; for (const item of data) { if (!tempData[item.purchase_id]) { tempData[item.purchase_id] = { purchase: { id: item.purchase_id, name: item.purchase_name, purchaser: item.purchaser, date: item.date, total_price: 0, split: item.split }, purchase_records: [] }; } tempData[item.purchase_id].purchase_records.push({ record: { id: item.purchase_record_id, count: item.count, total_price: item.total_price }, pokemon: { id: item.pokemon_id, name: item.pokemon_name } }); tempData[item.purchase_id].purchase.total_price += item.total_price; } return Object.values(tempData).map((item) => item); } /** * QueryInventories. * * @returns */ export async function queryInventories(params) { if (params.name) { let query = knex('pokemons'); query = query.where('name', 'like', `%${params.name}%`); const pokemons = await query.select(); const inventoryPromises = pokemons.map(async (pokemon) => { return await knex('inventories') .where({ pokemon_id: pokemon.id }) .then((inventories) => { return { ...inventories[0], pokemon }; }); }); return await Promise.all(inventoryPromises); } else { return new Inventory().fetchAll({ withRelated: ['pokemon'] }).then((inventories) => inventories); } } /** * QuerySoldRecords. * * @returns */ export async function querySoldRecords() { const data = await knex('solds') .select([ knex.ref('sold_records.id').as('sold_record_id'), knex.ref('solds.name').as('sold_name'), 'solds.date', 'solds.payee', 'solds.split', 'solds.sales_channel', 'sold_records.sold_id', 'sold_records.count', 'sold_records.total_price', 'sold_records.pokemon_id', knex.ref('pokemons.name').as('pokemon_name') ]) .join('sold_records', function () { this.on('solds.id', '=', 'sold_records.sold_id'); this.andOnVal('solds.status', '=', 'active'); }) .join('pokemons', 'sold_records.pokemon_id', '=', 'pokemons.id'); const tempData = {}; for (const item of data) { if (!tempData[item.sold_id]) { tempData[item.sold_id] = { sold: { id: item.sold_id, name: item.sold_name, date: item.date, total_price: 0, payee: item.payee, salesChannel: item.sales_channel, split: item.split }, sold_records: [] }; } tempData[item.sold_id].sold_records.push({ record: { id: item.purchase_record_id, count: item.count, total_price: item.total_price }, pokemon: { id: item.pokemon_id, name: item.pokemon_name } }); tempData[item.sold_id].sold.total_price += item.total_price; } return Object.values(tempData).map((item) => item); } /** * QueryPokemons. * * @param {*} params * @returns */ export function queryPokemons(params) { let query = knex('pokemons'); if (params.name) { query = query.where('name', 'like', `%${params.name}%`); } return query.select(); } /** * UpdatePokemon. * * @param {*} id * @param {*} params * @returns */ export function updatePokemon(id, params) { return new Pokemon({ id }).save(params); } /** * DeletePurchaseRecords. * * @param {*} param * @returns */ export async function deletePurchaseRecords({ ids }) { const dateTemp = {}; const data = await knex.transaction(async function (t) { /* eslint-disable no-await-in-loop */ for (const id of ids) { await knex('purchases') .transacting(t) .where({ id }) .update({ status: 'inactive' }, ['id', 'date', 'settlement', 'purchaser']) .then(async function (purchases) { const recordPromises = purchases.map((purchase) => { let date = null; if (purchase.settlement) { if (purchase.date.getMonth() + 1 < 10) { date = `${purchase.date.getFullYear()}-0${purchase.date.getMonth() + 1}`; } else { date = `${purchase.date.getFullYear()}-${purchase.date.getMonth() + 1}-01`; } if (!dateTemp[date]) { dateTemp[date] = { chad_purchase_price: 0, carol_purchase_price: 0 }; } } return knex('purchase_records') .transacting(t) .where({ purchase_id: purchase.id }) .update({ status: 'inactive' }, ['id', 'pokemon_id', 'count', 'total_price']) .then((purchaseRecords) => { const inventoryPrmoise = purchaseRecords.map(async (purchaseRecord) => { if (purchase.settlement) { if (purchase.purchaser === 'Chad') { dateTemp[date].chad_purchase_price += purchaseRecord.total_price; } else { dateTemp[date].carol_purchase_price += purchaseRecord.total_price; } } const inventory = await knex('inventories') .transacting(t) .where({ pokemon_id: purchaseRecord.pokemon_id }) .first(); const newCount = inventory.count - purchaseRecord.count; const newTotalPrice = inventory.total_price - purchaseRecord.total_price; return knex('inventories') .transacting(t) .where({ pokemon_id: purchaseRecord.pokemon_id }) .update({ total_price: newTotalPrice, count: newCount }); }); return Promise.all(inventoryPrmoise).then((inventories) => inventories); }); }); const record = await Promise.all(recordPromises); return { purchases, record }; }); } const settlementPromises = Object.keys(dateTemp).map(async (item) => { const month = new Date(item).getMonth() + 1; const year = new Date(item).getFullYear(); const settlement = await knex('settlements').where({ month, year }).first(); const updateParams = { chad_purchase_price: settlement.chad_purchase_price - dateTemp[item].chad_purchase_price, carol_purchase_price: settlement.carol_purchase_price - dateTemp[item].carol_purchase_price }; return knex('settlements').transacting(t).where({ id: settlement.id }).update(updateParams); }); return await Promise.all(settlementPromises); }); return data; } /** * DeleteSoldRecords. * * @param {*} param0 * @returns */ export async function deleteSoldRecords({ ids }) { const dateTemp = {}; const data = await knex.transaction(async function (t) { /* eslint-disable no-await-in-loop */ for (const id of ids) { await knex('solds') .transacting(t) .where({ id }) .update({ status: 'inactive' }, ['id', 'date', 'settlement', 'payee']) .then(async function (solds) { const recordPromises = solds.map((sold) => { let date = null; if (sold.settlement) { if (sold.date.getMonth() + 1 < 10) { date = `${sold.date.getFullYear()}-0${sold.date.getMonth() + 1}`; } else { date = `${sold.date.getFullYear()}-${sold.date.getMonth() + 1}-01`; } if (!dateTemp[date]) { dateTemp[date] = { chad_sold_price: 0, carol_sold_price: 0 }; } } return knex('sold_records') .transacting(t) .where({ sold_id: sold.id }) .update({ status: 'inactive' }, ['id', 'pokemon_id', 'count', 'total_price']) .then((soldRecords) => { const inventoryPrmoise = soldRecords.map(async (soldRecord) => { if (sold.settlement) { if (sold.payee === 'Chad') { dateTemp[date].chad_sold_price += soldRecord.total_price; } else { dateTemp[date].carol_sold_price += soldRecord.total_price; } } const inventory = await knex('inventories') .transacting(t) .where({ pokemon_id: soldRecord.pokemon_id }) .first(); const newCount = inventory.count + soldRecord.count; const newTotalPrice = inventory.total_price + soldRecord.total_price; return knex('inventories') .transacting(t) .where({ pokemon_id: soldRecord.pokemon_id }) .update({ total_price: newTotalPrice, count: newCount }); }); return Promise.all(inventoryPrmoise).then((inventories) => inventories); }); }); const record = await Promise.all(recordPromises); return { solds, record }; }); } const settlementPromises = Object.keys(dateTemp).map(async (item) => { const month = new Date(item).getMonth() + 1; const year = new Date(item).getFullYear(); const settlement = await knex('settlements').transacting(t).where({ month, year }).first(); const updateParams = { chad_sold_price: settlement.chad_sold_price - dateTemp[item].chad_sold_price, carol_sold_price: settlement.carol_sold_price - dateTemp[item].carol_sold_price }; return knex('settlements').where({ id: settlement.id }).update(updateParams); }); return Promise.all(settlementPromises); }); return data; } export async function updateSettlementRecords({ params }) { const transactionPromises = params.map((param) => { return knex.transaction(async function (t) { let chad_purchase_price = 0, chad_sold_price = 0, carol_purchase_price = 0, carol_sold_price = 0; await knex('purchases') .transacting(t) .andWhereRaw(`EXTRACT(YEAR FROM date::date) = ?`, [param.year]) .andWhereRaw(`EXTRACT(MONTH FROM date::date) = ?`, [param.month]) .where({ status: 'active', purchaser: 'Chad' }) .update({ settlement: true }, ['id']) .then((purchases) => { const purchaseRecordPromises = purchases.map((purchase) => { return knex('purchase_records') .where({ purchase_id: purchase.id }) .update({ settlement: true }, ['id', 'total_price']); }); return Promise.all(purchaseRecordPromises).then((purchaseRecords) => { for (const purchaseRecord of purchaseRecords) { for (const record of purchaseRecord) { chad_purchase_price += record.total_price; } } return purchaseRecords; }); }); await knex('solds') .transacting(t) .andWhereRaw(`EXTRACT(YEAR FROM date::date) = ?`, [param.year]) .andWhereRaw(`EXTRACT(MONTH FROM date::date) = ?`, [param.month]) .where({ status: 'active', payee: 'Chad' }) .update({ settlement: true }, ['id']) .then((solds) => { const soldRecordPromises = solds.map((sold) => { return knex('sold_records').where({ sold_id: sold.id }).update({ settlement: true }, ['id', 'total_price']); }); return Promise.all(soldRecordPromises).then((soldRecords) => { for (const soldRecord of soldRecords) { for (const record of soldRecord) { chad_sold_price += record.total_price; } } return soldRecords; }); }); await knex('purchases') .transacting(t) .andWhereRaw(`EXTRACT(YEAR FROM date::date) = ?`, [param.year]) .andWhereRaw(`EXTRACT(MONTH FROM date::date) = ?`, [param.month]) .where({ status: 'active', purchaser: 'Carol' }) .update({ settlement: true }, ['id']) .then((purchases) => { const purchaseRecordPromises = purchases.map((purchase) => { return knex('purchase_records') .where({ purchase_id: purchase.id }) .update({ settlement: true }, ['id', 'total_price']); }); return Promise.all(purchaseRecordPromises).then((purchaseRecords) => { for (const purchaseRecord of purchaseRecords) { for (const record of purchaseRecord) { carol_purchase_price += record.total_price; } } return purchaseRecords; }); }); await knex('solds') .transacting(t) .andWhereRaw(`EXTRACT(YEAR FROM date::date) = ?`, [param.year]) .andWhereRaw(`EXTRACT(MONTH FROM date::date) = ?`, [param.month]) .where({ status: 'active', payee: 'Carol' }) .update({ settlement: true }, ['id']) .then((solds) => { const soldRecordPromises = solds.map((sold) => { return knex('sold_records').where({ sold_id: sold.id }).update({ settlement: true }, ['id', 'total_price']); }); return Promise.all(soldRecordPromises).then((soldRecords) => { for (const soldRecord of soldRecords) { for (const record of soldRecord) { carol_sold_price += record.total_price; } } return soldRecords; }); }); let settlementData = null; const querySettlement = await knex('settlements').where({ month: param.month, year: param.year }).first(); if (!querySettlement) { settlementData = await knex('settlements').insert({ id: uuid(), month: param.month, year: param.year, chad_purchase_price, chad_sold_price, carol_purchase_price, carol_sold_price }); } else { settlementData = await knex('settlements').where({ id: querySettlement.id }).update({ chad_purchase_price, chad_sold_price, carol_purchase_price, carol_sold_price }); } return settlementData; }); }); const data = await Promise.all(transactionPromises); return data; } export async function queryRecordTotalByUnsettlement() { const purchaseRecords = await knex('purchase_records') .where({ settlement: false, status: 'active' }) .orderBy('date', 'desc'); const result = {}; for (const record of purchaseRecords) { const month = record.date.getUTCMonth() + 1; const year = record.date.getUTCFullYear(); const key = `${month}`; if (!result[key]) { result[key] = { year, month, purchase: 0, sold: 0 }; } result[key].purchase += record.total_price; } const soldRecords = await knex('sold_records').where({ settlement: false, status: 'active' }).orderBy('date', 'desc'); for (const record of soldRecords) { const month = record.date.getUTCMonth() + 1; const year = record.date.getUTCFullYear(); const key = `${month}`; if (!result[key]) { result[key] = { year, month, purchase: 0, sold: 0 }; } result[key].sold += record.total_price; } return result; } export async function querySettlements() { const settlements = await knex('settlements').orderBy('year', 'desc').orderBy('month', 'desc'); return settlements; } export async function getUnsettlementDetail({ year, month }) { let chad_purchase_price = 0, chad_sold_price = 0, carol_purchase_price = 0, carol_sold_price = 0; await knex('purchases') .andWhereRaw(`EXTRACT(YEAR FROM date::date) = ?`, [year]) .andWhereRaw(`EXTRACT(MONTH FROM date::date) = ?`, [month]) .where({ status: 'active', purchaser: 'Chad' }) .then((purchases) => { const purchaseRecordPromises = purchases.map((purchase) => { return knex('purchase_records').where({ purchase_id: purchase.id }); }); return Promise.all(purchaseRecordPromises).then((purchaseRecords) => { for (const purchaseRecord of purchaseRecords) { for (const record of purchaseRecord) { chad_purchase_price += record.total_price; } } return purchaseRecords; }); }); await knex('solds') .andWhereRaw(`EXTRACT(YEAR FROM date::date) = ?`, [year]) .andWhereRaw(`EXTRACT(MONTH FROM date::date) = ?`, [month]) .where({ status: 'active', payee: 'Chad' }) .then((solds) => { const soldRecordPromises = solds.map((sold) => { return knex('sold_records').where({ sold_id: sold.id }); }); return Promise.all(soldRecordPromises).then((soldRecords) => { for (const soldRecord of soldRecords) { for (const record of soldRecord) { chad_sold_price += record.total_price; } } return soldRecords; }); }); await knex('purchases') .andWhereRaw(`EXTRACT(YEAR FROM date::date) = ?`, [year]) .andWhereRaw(`EXTRACT(MONTH FROM date::date) = ?`, [month]) .where({ status: 'active', purchaser: 'Carol' }) .then((purchases) => { const purchaseRecordPromises = purchases.map((purchase) => { return knex('purchase_records').where({ purchase_id: purchase.id }); }); return Promise.all(purchaseRecordPromises).then((purchaseRecords) => { for (const purchaseRecord of purchaseRecords) { for (const record of purchaseRecord) { carol_purchase_price += record.total_price; } } return purchaseRecords; }); }); await knex('solds') .andWhereRaw(`EXTRACT(YEAR FROM date::date) = ?`, [year]) .andWhereRaw(`EXTRACT(MONTH FROM date::date) = ?`, [month]) .where({ status: 'active', payee: 'Carol' }) .update({ settlement: true }, ['id']) .then((solds) => { const soldRecordPromises = solds.map((sold) => { return knex('sold_records').where({ sold_id: sold.id }).update({ settlement: true }, ['id', 'total_price']); }); return Promise.all(soldRecordPromises).then((soldRecords) => { for (const soldRecord of soldRecords) { for (const record of soldRecord) { carol_sold_price += record.total_price; } } return soldRecords; }); }); return { year, month, chad_purchase_price, chad_sold_price, carol_purchase_price, carol_sold_price }; } export async function getSettlementDetail({ year, month }) { const settlement = knex('settlements').where({ year, month }).first(); return settlement; } export async function updatePurchaseRecordsById(id, params) { const purchase = await knex('purchases') .where({ id }) .first() .update(params, ['id']) .then((item) => { return knex('purchase_records').where({ purchase_id: item[0].id }).update(params, ['id']); }); return purchase; } export async function updatePurchaseRecordsByDate(params) { const purchases = await knex('purchases') .andWhereRaw(`EXTRACT(YEAR FROM date::date) = ?`, [params.date.year]) .andWhereRaw(`EXTRACT(MONTH FROM date::date) = ?`, [params.date.month]) .update({ split: params.split }, ['id']) .then((items) => { const purchaseRecordPromises = items.map((purchase) => { return knex('purchase_records').where({ purchase_id: purchase.id }).update({ split: params.split }, ['id']); }); return Promise.all(purchaseRecordPromises); }); return purchases; } export async function updateSoldRecordsById(id, params) { const sold = await knex('solds') .where({ id }) .first() .update(params, ['id']) .then((item) => { return knex('sold_records').where({ sold_id: item.id }).update(params, ['id']); }); return sold; } export async function updateSoldRecordsByDate(params) { const solds = await knex('solds') .andWhereRaw(`EXTRACT(YEAR FROM date::date) = ?`, [params.date.year]) .andWhereRaw(`EXTRACT(MONTH FROM date::date) = ?`, [params.date.month]) .update({ split: params.split }, ['id']) .then((items) => { const soldRecordPromises = items.map((sold) => { return knex('sold_records').where({ sold_id: sold.id }).update({ split: params.split }, ['id']); }); return Promise.all(soldRecordPromises); }); return solds; } export async function getUnsplitPurchasesByDate(date) { const purchases = await knex('purchases') .andWhereRaw(`EXTRACT(YEAR FROM date::date) = ?`, [date.year]) .andWhereRaw(`EXTRACT(MONTH FROM date::date) = ?`, [date.month]) .where({ split: false, status: 'active' }) .then((items) => { const result = items.map(async (purchase) => { const records = await knex('purchase_records').where({ purchase_id: purchase.id, split: false }); let total_price = 0; for (const record of records) { total_price = record.total_price; } return { ...purchase, total_price }; }); return Promise.all(result); }); return purchases; } export async function getUnsplitSoldsByDate(date) { const solds = await knex('solds') .andWhereRaw(`EXTRACT(YEAR FROM date::date) = ?`, [date.year]) .andWhereRaw(`EXTRACT(MONTH FROM date::date) = ?`, [date.month]) .where({ split: false, status: 'active' }) .then((items) => { const result = items.map(async (sold) => { const records = await knex('sold_records').where({ sold_id: sold.id, split: false }); let total_price = 0; for (const record of records) { total_price = record.total_price; } return { ...sold, total_price }; }); return Promise.all(result); }); return solds; }
var path = require('path'); var fs = require('fs'); // 返回该目录下所有文件的绝对路径(包括子目录) function readdir(dir, opts) { if ( opts === void 0 ) opts={}; var files = fs.readdirSync(dir); var p = normalizePattern(opts.pattern); var returnFiles = []; for (var i = 0; i < files.length; i++) { var absfile = path.join(dir, files[i]); if (!p(absfile)) { continue; } var isdir = fs.lstatSync(absfile).isDirectory(); returnFiles = returnFiles.concat(isdir ? readdir(absfile, opts) : absfile); } return returnFiles; }; function normalizePattern(fn) { if (!fn) { return function () { return true; }; } if (fn && fn.test) { return function (x) { return fn.test(x); }; } return fn; } module.exports = readdir;
import React from 'react'; import ReactDOM from 'react-dom'; // import App from './components/App'; import Routes from './Routes'; import './index.css'; ReactDOM.render(<Routes />, document.getElementById('root'));
function arePasswordsEqual(original, newPassword) { if (original == newPassword) { return true; } else { return false; } }
import 'whatwg-fetch'; export function getUsers(){ return get('users'); } function get(url){ return fetch(url).then(onSuccess,onError); } function onSuccess(response){ response.json(); } function onError(error){ console.log(error); //eslint-disable-line no-console }
require('dotenv').config(); const SETTINGS = process.env; const {Client, Collection, MessageEmbed} = require('discord.js') const { join } = require("path"); const { readdirSync } = require("fs"); /** * Client Events */ const client = new Client(); client.login(SETTINGS.DISCORD_BOT_TOKEN); client.commands = new Collection(); client.prefix = SETTINGS.prefix; const cooldowns = new Collection(); const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); client.on("ready", () => { console.log(`${client.user.username} ready!`); client.user.setActivity(`${SETTINGS.prefix}help`, { type: "LISTENING" }); }); client.on("warn", (info) => console.log(info)); client.on("error", console.error); client.on("message", async (message) => { if (message.author.bot) return; if (!message.guild) return; const prefixRegex = new RegExp(`^(<@!?${client.user.id}>|${escapeRegex(SETTINGS.prefix)})\\s*`); if (!prefixRegex.test(message.content)) return; const [, matchedPrefix] = message.content.match(prefixRegex); const args = message.content.slice(matchedPrefix.length).trim().split(/ +/); const commandName = args.shift().toLowerCase(); const command = client.commands.get(commandName) || client.commands.find((cmd) => cmd.aliases && cmd.aliases.includes(commandName)); if (!command) return; if ((SETTINGS.channelRestricted === "true") && (message.channel.id !== SETTINGS.statChannel)) { let wrongChannelEmbed = new MessageEmbed() .setTitle(`Ooops! Wrong Channel`) .setDescription(`**You can only search a player up at <#${SETTINGS.statChannel}>.**`) .setColor("#ff0300") .setAuthor('SquadStatJS by LeventHAN x 11TStudio', 'https://avatars2.githubusercontent.com/u/25463237?s=400&u=eccc0ee1cd33352f75338889e791a04d1909bcce&v=4', 'https://github.com/11TStudio') .setThumbnail("https://i.imgur.com/fqymYyZ.png"); wrongChannelEmbed.setAuthor('SquadStatJS by LeventHAN x 11TStudio', 'https://avatars2.githubusercontent.com/u/25463237?s=400&u=eccc0ee1cd33352f75338889e791a04d1909bcce&v=4', 'https://github.com/11TStudio') wrongChannelEmbed.setTimestamp(); wrongChannelEmbed.setFooter(SETTINGS.author, SETTINGS.footerImg); message.channel.send(wrongChannelEmbed) .then(msg => { msg.delete({timeout: 5000})}) .then(message.delete({timeout: 1000})) .catch(console.error); return; } if (!cooldowns.has(command.name)) { cooldowns.set(command.name, new Collection()); } const now = Date.now(); const cdtimestamps = cooldowns.get(command.name); const cooldownAmount = (command.cooldown || 1) * 1000; if (cdtimestamps.has(message.author.id)) { const expirationTime = cdtimestamps.get(message.author.id) + cooldownAmount; if (now < expirationTime) { const timeLeft = (expirationTime - now) / 1000; let wrongSyntaxEmbed = new MessageEmbed() .setTitle(`Ooops! You are too fast!`) .setDescription(`**Usage of this command is protected with a cooldown.**`) .setColor("#ff0300") .setAuthor('SquadStatJS by LeventHAN x 11TStudio', 'https://avatars2.githubusercontent.com/u/25463237?s=400&u=eccc0ee1cd33352f75338889e791a04d1909bcce&v=4', 'https://github.com/11TStudio') .setThumbnail("https://i.imgur.com/fqymYyZ.png"); wrongSyntaxEmbed.setAuthor('SquadStatJS by LeventHAN x 11TStudio', 'https://avatars2.githubusercontent.com/u/25463237?s=400&u=eccc0ee1cd33352f75338889e791a04d1909bcce&v=4', 'https://github.com/11TStudio') wrongSyntaxEmbed.addField(`Try after`,`\`${timeLeft.toFixed(1)}second(s)\``); wrongSyntaxEmbed.setTimestamp(); wrongSyntaxEmbed.setFooter(SETTINGS.author, SETTINGS.footerImg); message.channel.send(wrongSyntaxEmbed) .then(msg => { msg.delete({timeout: 5000})}) .then(message.delete({timeout: 5000})) .catch(console.error); return; } } //${timeLeft.toFixed(1)} cdtimestamps.set(message.author.id, now); setTimeout(() => cdtimestamps.delete(message.author.id), cooldownAmount); try { await command.execute(message, args); } catch (error) { console.error(error); message.reply("Oops something went wrong... How about try that again?").catch(console.error); } }); /* * Importing all the commands */ const commandList = readdirSync(join(__dirname, "comms")).filter((file) => file.endsWith(".js")); for (const file of commandList) { const command = require(join(__dirname, "comms", `${file}`)); client.commands.set(command.name, command); }
import React, { Component } from 'react'; import styles from './App.css'; import MainContainer from './containers/MainContainer'; import Header from './components/Header/Header'; import Footer from './components/Footer/Footer'; class App extends Component { render() { return ( <div className={styles.container}> <Header /> <MainContainer /> <Footer className="master branch" /> </div> ); } } const a = 12; let b = 'String'; const c = 'Super test'; export default App;
polyline = { "vertices" : { [0,0,0], [0,100,0], [100,100,0], [100,0,0] }, "numberFloors": "none", "buildingType": "office" }
/** * Created by Kelvin on 6/28/2016. */ 'use strict'; describe('Controller: RSVPCtrl', function () { // load the controller's module beforeEach(module('tiffanyAndKelvin')); beforeEach(module('templates')); var RSVPCtrl, scope, rootScope, deferred; var rsvpData = { data: {} }; beforeEach(module(function($provide) { $provide.factory('GoogleCalendar', function($q) { //calendarInitDefer = $q.defer(); return { initialized: $q.resolve(), setCalendarEvent: function() {return $q.resolve();} } }); })); // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope, $q) { rootScope = $rootScope; scope = $rootScope.$new(); deferred = $q.defer(); var promise = deferred.promise; rsvpData.save = function(formModel) { return promise; }; rsvpData.pepe = 'test'; RSVPCtrl = $controller('RSVPCtrl', { rsvpData: rsvpData }); spyOn(rsvpData, 'save').and.callThrough(); spyOn($.fn, 'removeClass'); })); it('should initialize isSaving to false', function() { expect(RSVPCtrl.isSaving).toBe(false); }); it('should initialize showCloseButton to true', function() { expect(RSVPCtrl.showCloseButton).toBe(true); }); it('should initialize form to an empty object', function() { var expected = {}; expect(RSVPCtrl.form).toEqual(expected); }); it('should set formModel to be rsvpData.data', function() { expect(RSVPCtrl.formModel).toEqual(rsvpData.data); }); it('should return whether a given property on form is dirty and invalid', function() { var element = 'foo'; var idx = 'bar'; RSVPCtrl.form.foobar = { $dirty: true, $invalid: false }; var expected = false; var actual = RSVPCtrl.showErrors(element, idx); expect(actual).toBe(expected); }); it('should initialize calendarEventAdded to false', function() { expect(RSVPCtrl.calendarEventAdded).toBe(false); }); it('should set calendarEventAdded to true if setCalendarEvent resolves', function() { RSVPCtrl.authCalendar(); scope.$apply(); expect(RSVPCtrl.calendarEventAdded).toBe(true); }); describe('closeToast', function() { it('should set showCloseButton to true when called', function() { RSVPCtrl.showCloseButton = false; RSVPCtrl.closeToast(); expect(RSVPCtrl.showCloseButton).toBe(true); }); it('should call removeClass with show-up', function() { RSVPCtrl.closeToast('success'); expect($.fn.removeClass).toHaveBeenCalledWith('show-up'); }); }); describe('submit', function() { var formModel = { code: 'foo' }; var mockForm = { $setPristine: function() {} }; beforeEach(function() { RSVPCtrl.form = mockForm; RSVPCtrl.submit(formModel); spyOn($.fn, 'addClass'); spyOn(mockForm, '$setPristine'); }); it('should call save on rsvpData', function() { expect(rsvpData.save).toHaveBeenCalledWith(formModel); }); it('should set showThankYou to be true when successful', function() { deferred.resolve(); scope.$apply(); expect(RSVPCtrl.showThankYou).toBe(true); }); it('should set atLeastOneGoing to false if not at least one person is going', function() { deferred.resolve(); scope.$apply(); expect(RSVPCtrl.atLeastOneGoing).toBe(false); }); it('should set atLeastOneGoing to true if not at least one person is going', function() { deferred.resolve(); scope.$apply(); formModel = { "A0": { "firstName": "Darbie", "going": "0", "lastName": "Grant", "plusOne": false, "plusOneDependent": false }, "B1": { "firstName": "Dave", "going": "1", "lastName": "Grant", "plusOne": false, "plusOneDependent": false }, "C2": { "firstName": "Natalie", "going": "0", "lastName": "Grant", "plusOne": false, "plusOneDependent": false }, "responded": false }; RSVPCtrl.submit(formModel); deferred.resolve(); scope.$apply(); expect(RSVPCtrl.atLeastOneGoing).toBe(true); }); it('should set the from to pristine when successful', function() { deferred.resolve(); scope.$apply(); expect(mockForm.$setPristine).toHaveBeenCalled(); }); it('should call add class with show-up when not successful', function() { deferred.reject(); scope.$apply(); expect($.fn.addClass).toHaveBeenCalledWith('show-up'); }); it('should set showCloseButton false when not successful', function() { deferred.reject(); scope.$apply(); expect(RSVPCtrl.showCloseButton).toBe(false); }); it('should set isSaving to true', function() { expect(RSVPCtrl.isSaving).toBe(true); }); it('should set isSaving to false when the promise finishes', function() { deferred.reject(); scope.$apply(); expect(RSVPCtrl.isSaving).toBe(false); }); }); describe('goingChanged', function() { it('should not modify mainNotGoin person.plusOneDependent is false', function() { var expected = false; RSVPCtrl.mainNotGoing = expected; RSVPCtrl.goingChanged({plusOneDependent: false}); expect(RSVPCtrl.mainNotGoing).toBe(expected); }); it('should set mainNotGoing to person.going "0" === false or "1" === true', function () { var expected = true; var person = { plusOneDependent: true, going: '0' }; RSVPCtrl.goingChanged(person); expect(RSVPCtrl.mainNotGoing).toBe(true); }); }); });
/** When your routing table is too long, you can split it into small modules **/ import Layout from '@/layout' const componentsRouter = { path: '/components', component: Layout, redirect: 'noRedirect', name: 'ComponentDemo', meta: { title: '组件', icon: 'component' }, children: [ { path: 'tinymce', component: () => import('@/views/components-demo/tinymce'), name: 'TinymceDemo', meta: { title: '富文本编辑器' } }, { path: 'markdown', component: () => import('@/views/components-demo/markdown'), name: 'MarkdownDemo', meta: { title: 'Markdown' } }, { path: 'json-editor', component: () => import('@/views/components-demo/json-editor'), name: 'JsonEditorDemo', meta: { title: 'JSON 编辑器' } }, { path: 'split-pane', component: () => import('@/views/components-demo/split-pane'), name: 'SplitpaneDemo', meta: { title: 'SplitPane' } }, { path: 'avatar-upload', component: () => import('@/views/components-demo/avatar-upload'), name: 'AvatarUploadDemo', meta: { title: '头像上传' } }, { path: 'dropzone', component: () => import('@/views/components-demo/dropzone'), name: 'DropzoneDemo', meta: { title: 'Dropzone' } }, { path: 'sticky', component: () => import('@/views/components-demo/sticky'), name: 'StickyDemo', meta: { title: 'Sticky' } }, { path: 'count-to', component: () => import('@/views/components-demo/count-to'), name: 'CountToDemo', meta: { title: 'Count To' } }, { path: 'mixin', component: () => import('@/views/components-demo/mixin'), name: 'ComponentMixinDemo', meta: { title: '小组件' } }, { path: 'back-to-top', component: () => import('@/views/components-demo/back-to-top'), name: 'BackToTopDemo', meta: { title: '返回顶部' } }, { path: 'drag-dialog', component: () => import('@/views/components-demo/drag-dialog'), name: 'DragDialogDemo', meta: { title: '拖拽 Dialog' } }, { path: 'drag-select', component: () => import('@/views/components-demo/drag-select'), name: 'DragSelectDemo', meta: { title: '拖拽 Select' } }, { path: 'dnd-list', component: () => import('@/views/components-demo/dnd-list'), name: 'DndListDemo', meta: { title: '列表拖拽' } }, { path: 'drag-kanban', component: () => import('@/views/components-demo/drag-kanban'), name: 'DragKanbanDemo', meta: { title: '可拖拽看板' } } ] } export default componentsRouter
/* Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 3.1.1 build: 47 */ YUI.add("lang/datatype-date-format_es-US",function(A){A.Intl.add("datatype-date-format","es-US",{"a":["dom","lun","mar","mié","jue","vie","sáb"],"A":["domingo","lunes","martes","miércoles","jueves","viernes","sábado"],"b":["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"],"B":["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"],"c":"%a, %d %b %Y %l:%M:%S %p %Z","p":["A.M.","P.M."],"P":["a.m.","p.m."],"x":"%m/%d/%y","X":"%l:%M:%S %p"});},"3.1.1");YUI.add("lang/datatype-date_es-US",function(A){},"3.1.1",{use:["lang/datatype-date-format_es-US"]});
module.exports = { name: 'lmbase-collection', preset: '../../jest.config.js', coverageDirectory: '../../coverage/libs/lmbase-collection', snapshotSerializers: [ 'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js', 'jest-preset-angular/build/AngularSnapshotSerializer.js', 'jest-preset-angular/build/HTMLCommentSerializer.js', ], };
(window.webpackJsonp=window.webpackJsonp||[]).push([[60],{409:function(s,e,t){"use strict";t.r(e);var o=t(42),a=Object(o.a)({},(function(){var s=this,e=s.$createElement,t=s._self._c||e;return t("ContentSlotsDistributor",{attrs:{"slot-key":s.$parent.slotKey}},[t("h1",{attrs:{id:"session-分布式方案"}},[t("a",{staticClass:"header-anchor",attrs:{href:"#session-分布式方案"}},[s._v("#")]),s._v(" Session 分布式方案")]),s._v(" "),t("h2",{attrs:{id:"基于-nfs-net-filesystem-的-session-共享"}},[t("a",{staticClass:"header-anchor",attrs:{href:"#基于-nfs-net-filesystem-的-session-共享"}},[s._v("#")]),s._v(" 基于 nfs(net filesystem) 的 Session 共享")]),s._v(" "),t("p",[s._v("将共享服务器目录 mount 各服务器的本地 session 目录,session 读写受共享服务器 io 限制,"),t("strong",[s._v("不能满足高并发")]),s._v("。")]),s._v(" "),t("h2",{attrs:{id:"基于关系数据库的-session-共享"}},[t("a",{staticClass:"header-anchor",attrs:{href:"#基于关系数据库的-session-共享"}},[s._v("#")]),s._v(" 基于关系数据库的 Session 共享")]),s._v(" "),t("p",[s._v("这种方案普遍使用。使用关系数据库存储 session 数据,对于 mysql 数据库,建议使用 heap 引擎。这种方案性能取决于数据库的性能,在高并发下容易造成表锁(虽然可以采用行锁的存储引擎,性能会下降),并且需要自己实现 session 过期淘汰机制。")]),s._v(" "),t("h2",{attrs:{id:"基于-cookie-的-session-共享"}},[t("a",{staticClass:"header-anchor",attrs:{href:"#基于-cookie-的-session-共享"}},[s._v("#")]),s._v(" 基于 Cookie 的 Session 共享")]),s._v(" "),t("p",[s._v("这种方案也在大型互联网中普遍使用,将用户的 session 加密序列化后以 cookie 的方式保存在网站根域名下(比如 taobao.com),当用户访问所有二级域名站点式,浏览器会传递所有匹配的根域名的 cookie 信息,这样实现了用户 cookie 化 session 的多服务共享。此方案能够节省大量服务器资源,缺点是存储的信息长度受到 http 协议限制;cookie 的信息还需要做加密解密;请求任何资源时都会将 cookie 附加到 http 头上传到服务器,占用了一定带宽。")]),s._v(" "),t("h2",{attrs:{id:"基于-web-容器的-session-机制"}},[t("a",{staticClass:"header-anchor",attrs:{href:"#基于-web-容器的-session-机制"}},[s._v("#")]),s._v(" 基于 Web 容器的 Session 机制")]),s._v(" "),t("p",[s._v("利用容器机制,通过配置即可实现。")]),s._v(" "),t("h2",{attrs:{id:"基于-zookeeper-的分布式-session-存储"}},[t("a",{staticClass:"header-anchor",attrs:{href:"#基于-zookeeper-的分布式-session-存储"}},[s._v("#")]),s._v(" 基于 Zookeeper 的分布式 Session 存储")]),s._v(" "),t("h2",{attrs:{id:"基于-redis-memcached-的-session-共享存储"}},[t("a",{staticClass:"header-anchor",attrs:{href:"#基于-redis-memcached-的-session-共享存储"}},[s._v("#")]),s._v(" 基于 Redis/Memcached 的 Session 共享存储")]),s._v(" "),t("p",[s._v("这些 key/value 非关系存储有较高的性能,轻松达到 2000 左右的 qps,内置的过期机制正好满足 session 的自动实效特性。")])])}),[],!1,null,null,null);e.default=a.exports}}]);
import styled from "styled-components"; const HeaderFooterWrapper = styled.div` max-width: 500px; margin: 0 auto; display: grid; grid-template-rows: max-content auto max-content; min-height: 100vh; `; const Header = styled.div` padding: 2rem 1rem 1rem; `; const Page = styled.div` padding: 1rem; `; const Place = styled.div` padding: 1rem; `; const Footer = styled.div` padding: 1rem; text-align: center; opacity: 0.3; `; export { HeaderFooterWrapper, Header, Page, Place, Footer };
const path = require('path') const HTMLPlugin = require('html-webpack-plugin') const webpack = require('webpack') const ExtractPlugin = require('extract-text-webpack-plugin') const isDev = process.env.NODE_ENV === 'development' const config = { target: 'web', entry: path.join(__dirname, 'src/index.js'), output: { filename: 'bundle.[hash:8].js', path: path.join(__dirname, 'dist') }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader' }, { test: /\.jsx$/, loader: 'babel-loader' }, { test: /\.(gif|jpg|jpeg|png|svg)$/, use: [ { loader: 'url-loader', // 是对file-loader的封装 options: { limit: 1024, // 如果图片小于1024,就转化成base64位 name: '[name].[ext]' } } ] } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: isDev ? '"development"' : '"production"' } }), new HTMLPlugin() ], // externals: { // 'vue': 'Vue' // } } if (isDev) { // 开发环境的css代码可以内联 config.module.rules.push({ test: /\.styl$/, use: [ 'style-loader', 'css-loader', { loader: 'postcss-loader', options: { sourceMap: true // stylus-loader会生成sourceMap,postcss-loader也会,加上这个选项表示用生成的sourceMap,提示编译效率 } }, 'stylus-loader' ] }) config.devtool = '#cheap-module-eval-source-map' // devServer 在webpack2.0后才有的 config.devServer = { port: 8000, // host: '127.0.0.1', // 好处: 可以在别人电脑上通过ip访问,或者手机 host: '0.0.0.0', // 好处: 可以在别人电脑上通过ip访问,或者手机 overlay: { // 编译的时候出现错误,就显示到网页上 errors: true }, hot: true, // 热更新,只更新修改的页面,不会刷新整个页面 // open: true // 自动打开网页 } // 热更新的相关插件 config.plugins.push( new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin() ) } else { // 第三方的类库,一般比较稳定,不会和业务代码一样经常变动,所以要单独打包 config.entry = { app: path.join(__dirname, 'src/index.js'), vendor: ['vue'] } // 如果是hash,那么每次打包,各个带有hash的文件,他们的hash都是相同的, // 这样,每次生成环境打包后,vendor也是每次都变化了,每次都会重新加载,就没有单独打包的意义了 // 使用chunkhash的话,每个单独文件的hash都不同 config.output.filename = '[name].[chunkhash:8].js' // 生产环境的css需要外联 config.module.rules.push({ test: /\.styl$/, use: ExtractPlugin.extract({ fallback: 'style-loader', use: [ 'css-loader', { loader: 'postcss-loader', options: { sourceMap: true } }, 'stylus-loader' ] }) }) config.plugins.push( new ExtractPlugin('styles.[contentHash:8].css'), // css相关插件 new webpack.optimize.CommonsChunkPlugin({ // 第三方类库打包,单独打包到vendor.js中 name: 'vendor' }), // FIXME: 这边还是不大明白,再看看https://www.imooc.com/video/16410 new webpack.optimize.CommonsChunkPlugin({ name: 'runtime' }) ) } module.exports = config
// @flow import * as React from 'react' import { AppRegistry } from 'react-native' import App from './modules/app/components/App' import 'moment/min/locales' AppRegistry.registerComponent('Integreat', () => () => <App />)
/** * Copyright (c) 2014, 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ "use strict"; /** * Copyright (c) 2015, Oracle and/or its affiliates. * All rights reserved. */ define(['ojs/ojcore', 'jquery', 'ojs/ojcomponentcore', 'promise', 'ojdnd', 'ojs/ojdomscroller', 'ojs/ojeditablevalue', 'ojs/ojmenu', 'ojs/ojdatasource-common', 'ojs/ojpagingtabledatasource', 'ojs/ojflattenedtreetabledatasource'], function(oj, $, compCore) { /** * Copyright (c) 2014, Oracle and/or its affiliates. * All rights reserved. */ /** * @preserve Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ /** * @ojcomponent oj.ojTable * @augments oj.baseComponent * * @classdesc * The ojTable component enhances a HTML table element into one that supports all * the features in JET Table. </p> * * <h3 id="touch-section"> * Touch End User Information * <a class="bookmarkable-link" title="Bookmarkable Link" href="#touch-section"></a> * </h3> * * {@ojinclude "name":"touchDoc"} * * <h3 id="keyboard-section"> * Keyboard End User Information * <a class="bookmarkable-link" title="Bookmarkable Link" href="#keyboard-section"></a> * </h3> * * {@ojinclude "name":"keyboardDoc"} * * <h3 id="a11y-section"> * Accessibility * <a class="bookmarkable-link" title="Bookmarkable Link" href="#a11y-section"></a> * </h3> * * <p>Developers should always either specify the <code class="prettyprint">summary</code> attribute or <code class="prettyprint">caption</code> child tag for the table element to conform to accessibility guidelines.</p> * * <h3 id="styling-section"> * Styling * <a class="bookmarkable-link" title="Bookmarkable Link" href="#styling-section"></a> * </h3> * * {@ojinclude "name":"stylingDoc"} * * <h3 id="perf-section"> * Performance * <a class="bookmarkable-link" title="Bookmarkable Link" href="#perf-section"></a> * </h3> * * <h4>Data Set Size</h4> * <p>As a rule of thumb, it's recommended that applications limit the amount of data to display. Displaying large * number of items in Table makes it hard for users to find what they are looking for, but affects the * rendering performance as well. If displaying large number of items is neccessary, consider use a paging control with Table * to limit the number of items to display at a time. Also consider setting <code class="prettyprint">scrollPolicy</code> to * 'loadMoreOnScroll' to enable infinite scrolling to reduce the number of elements in the DOM at any given time .</p> * * <h4>Cell Content</h4> * <p>Table allows developers to specify arbitrary content inside its cells. In order to minimize any negative effect on * performance, you should avoid putting a large number of heavy-weight components inside a cell because as you add more complexity * to the structure, the effect will be multiplied because there can be many items in the Table.</p> * * <!-- - - - - Above this point, the tags are for the class. * Below this point, the tags are for the constructor (initializer). - - - - - - --> * * * @desc Creates a JET Table. * * @param {Object=} options a map of option-value pairs to set on the component * * @example <caption>Initialize the table via the JET <code class="prettyprint">ojComponent</code> binding:</caption> * &lt;table id="table" summary="Department List" aria-label="Departments Table" * data-bind="ojComponent: {component: 'ojTable', data: datasource, columns: * [{headerText: 'Department Id', field: 'DepartmentId'}, * {headerText: 'Department Name', field: 'DepartmentName'}, * {headerText: 'Location Id', field: 'LocationId'}, * {headerText: 'Manager Id', field: 'ManagerId'}]}"&gt; * * @example <caption>Initialize the table with column templates via the JET <code class="prettyprint">ojComponent</code> binding:</caption> * &lt;table id="table" summary="Department List" aria-label="Departments Table" * data-bind="ojComponent: {component: 'ojTable', data: datasource, columns: * [{headerText: 'Department Id', field: 'DepartmentId'}, * {headerText: 'Department Name', field: 'DepartmentName'}, * {headerText: 'Location Id', field: 'LocationId'}, * {headerText: 'Manager Id', field: 'ManagerId'}]}, * {headerTemplate: 'oracle_link_hdr', template: 'oracle_link'}]}"&gt; * &lt;script type="text/html" id="oracle_link_hdr"&gt; * &lt;th style="padding-left: 5px; padding-right: 5px;"&gt; * Oracle Link * &lt;/th&gt; * &lt;/script&gt; * &lt;script type="text/html" id="oracle_link"&gt; * &lt;td&gt; * &lt;a href="http://www.oracle.com"&gt;Oracle&lt;/a&gt; * &lt;/td&gt; * &lt;/script&gt; * * @example <caption>Initialize the table with rowTemplate via the JET <code class="prettyprint">ojComponent</code> binding:</caption> * &lt;table id="table" summary="Department List" aria-label="Departments Table" * data-bind="ojComponent: {component: 'ojTable', data: datasource, columns: * [{headerText: 'Department Id', field: 'DepartmentId'}, * {headerText: 'Department Name', field: 'DepartmentName'}, * {headerText: 'Location Id', field: 'LocationId'}, * {headerText: 'Manager Id', field: 'ManagerId'}], * rowTemplate: 'row_tmpl'}"&gt; * &lt;script type="text/html" id="row_tmpl"&gt; * &lt;tr&gt; * &lt;td data-bind="text: DepartmentId"&gt; * &lt;/td&gt; * &lt;td data-bind="text: DepartmentName"&gt; * &lt;/td&gt; * &lt;td data-bind="text: LocationId"&gt; * &lt;/td&gt; * &lt;td data-bind="text: ManagerId"&gt; * &lt;/td&gt; * &lt;/tr&gt; * &lt;/script&gt; */ (function() { oj.__registerWidget("oj.ojTable", $['oj']['baseComponent'], { version: '1.0.0', defaultElement: '<table>', widgetEventPrefix: 'oj', options: { /** * Accessibility options. * <p> * The following options are supported: * <ul> * <li>rowHeader: columnId</li> * </ul> * The td cells in the column specified by the rowHeader * attribute will be assigned an id and then referenced by the * headers attribute in the rest of the cells in the row. * This is required by screenReaders. By default the first column * will be taken as the rowHeader. * @expose * @public * @instance * @memberof! oj.ojTable * @type {Object.<string, string>|null} * @property {string} rowHeader the column id to be used as the row header by screen readers * @default <code class="prettyprint">null</code> */ accessibility: null, /** * The current row the user has navigated to. Can be an index and/or key value. * When both are specified, the index is used as a hint. * Returns the current row or null if there is none. * @expose * @public * @instance * @memberof! oj.ojTable * @type {Object} * @default <code class="prettyprint">null</code> * * @example <caption>Get the current row:</caption> * $( ".selector" ).ojTable("option", "currentRow"); * * @example <caption>Set the current row on the table during initialization:</caption> * $(".selector").ojTable({"currentRow", {rowKey: '123'}}); * * @example <caption>Set the current row on the table during initialization:</caption> * $(".selector").ojTable({"currentRow", {rowIndex: 1}}); * * @example <caption>Set the current row on the table after initialization:</caption> * $(".selector").ojTable("option", "currentRow", {rowKey: '123'}); * * @example <caption>Set the current row on the table after initialization:</caption> * $(".selector").ojTable("option", "currentRow", {rowIndex: 1}); */ currentRow: null, /** * The data to bind to the component. * <p> * Must be of type oj.TableDataSource {@link oj.TableDataSource} * @expose * @public * @instance * @memberof! oj.ojTable * @type {oj.TableDataSource|null} * @default <code class="prettyprint">null</code> */ data: null, /** * Whether to display table in list or grid mode. Setting a value of grid * will cause the table to display in grid mode. The default value of this * option is set through the theme. * @expose * @public * @instance * @memberof! oj.ojTable * @type {string} * @ojvalue {string} "list" Display table in list mode. * @ojvalue {string} "grid" Display table in grid mode. This is a more compact look than list mode. */ display: 'list', /** * Enable drag and drop functionality.<br><br> * JET provides support for HTML5 Drag and Drop events. Please refer to {@link https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Drag_and_drop third party documentation} * on HTML5 Drag and Drop to learn how to use it. * * @type {Object} * * @property {Object} drag An object that describes drag functionlity. * @property {Object} drag.rows If this object is specified, the table will initiate drag operation when the user drags on selected rows. * @property {string | Array.string} drag.rows.dataTypes (optional) The MIME types to use for the dragged data in the dataTransfer object. This can be a string if there is only one * type, or an array of strings if multiple types are needed.<br><br> * For example, if selected rows of employee data are being dragged, dataTypes could be "application/employees+json". Drop targets can examine the data types and decide * whether to accept the data. A text input may only accept "text" data type, while a chart for displaying employee data may be configured to accept the "application/employees+json" type.<br><br> * For each type in the array, dataTransfer.setData will be called with the specified type and the JSON version of the selected rows data as the value. The selected rows data * is an array of objects, with each object representing one selected row in the format returned by TableDataSource.get().<br><br> * This property is required unless the application calls setData itself in a dragStart callback function. * @property {function} drag.rows.dragStart (optional) A callback function that receives the "dragstart" event and context information as arguments:<br><br> * <code class="prettyprint">function(event, ui)</code><br><br> * Parameters:<br><br> * <code class="prettyprint">event</code>: The jQuery event object<br><br> * <code class="prettyprint">ui</code>: Context object with the following properties:<br> * <ul> * <li><code class="prettyprint">rows</code>: An array of objects, with each object representing the data of one selected row in the structure below: * <table> * <tbody> * <tr><td><b>data</b></td><td>The raw row data</td></tr> * <tr><td><b>index</b></td><td>The index for the row</td></tr> * <tr><td><b>key</b></td><td>The key value for the row</td></tr> * </tbody> * </table> * </li> * </ul><br><br> * This function can set its own data and drag image as needed. If dataTypes is specified, event.dataTransfer is already populated with the default data when this function is invoked. * If dataTypes is not specified, this function must call event.dataTransfer.setData to set the data or else the drag operation will be cancelled. In either case, the drag image is * set to an image of the selected rows visible on the table. * @property {function} drag.rows.drag (optional) A callback function that receives the "drag" event as argument:<br><br> * <code class="prettyprint">function(event)</code><br><br> * Parameters:<br><br> * <code class="prettyprint">event</code>: The jQuery event object * @property {function} drag.rows.dragEnd (optional) A callback function that receives the "dragend" event as argument:<br><br> * <code class="prettyprint">function(event)</code><br><br> * Parameters:<br><br> * <code class="prettyprint">event</code>: The jQuery event object<br> * * @property {Object} drop An object that describes drop functionality. * @property {Object} drop.columns An object that specifies callback functions to handle dropping columns<br><br> * For all callback functions, the following arguments will be passed:<br><br> * <code class="prettyprint">event</code>: The jQuery event object<br><br> * <code class="prettyprint">ui</code>: Context object with the following properties: * <ul> * <li><code class="prettyprint">columnIndex</code>: The index of the column being dropped on</li> * </ul> * @property {string | Array.string} drop.columns.dataTypes A data type or an array of data types this component can accept.<br><br> * This property is required unless dragEnter, dragOver, and drop callback functions are specified to handle the corresponding events. * @property {function} drop.columns.dragEnter (optional) A callback function that receives the "dragenter" event and context information as arguments:<br><br> * <code class="prettyprint">function(event, ui)</code><br><br> * This function should return false to indicate the dragged data can be accepted or true otherwise. Any explict return value will be passed back to jQuery. Returning false * will cause jQuery to call stopPropagation and preventDefault on the event, and calling preventDefault is required by HTML5 Drag and Drop to indicate acceptance of data.<br><br> * If this function doesn't return a value, dataTypes will be matched against the drag data types to determine if the data is acceptable. If there is a match, event.preventDefault * will be called to indicate that the data can be accepted. * @property {function} drop.columns.dragOver (optional) A callback function that receives the "dragover" event and context information as arguments:<br><br> * <code class="prettyprint">function(event, ui)</code><br><br> * Similar to dragEnter, this function should return false to indicate the dragged data can be accepted or true otherwise. If this function doesn't return a value, * dataTypes will be matched against the drag data types to determine if the data is acceptable. * @property {function} drop.columns.dragLeave (optional) A callback function that receives the "dragleave" event and context information as arguments:<br><br> * <code class="prettyprint">function(event, ui)</code> * @property {function} drop.columns.drop (required) A callback function that receives the "drop" event and context information as arguments:<br><br> * <code class="prettyprint">function(event, ui)</code><br><br> * This function should return false to indicate the dragged data is accepted or true otherwise. * @property {Object} drop.rows An object that specifies callback functions to handle dropping rows<br><br> * For all callback functions, the following arguments will be passed:<br><br> * <code class="prettyprint">event</code>: The jQuery event object<br><br> * <code class="prettyprint">ui</code>: Context object with the following properties: * <ul> * <li><code class="prettyprint">rowIndex</code>: The index of the row being dropped on</li> * </ul> * @property {string | Array.string} drop.rows.dataTypes A data type or an array of data types this component can accept.<br><br> * This property is required unless dragEnter, dragOver, and drop callback functions are specified to handle the corresponding events. * @property {function} drop.rows.dragEnter (optional) A callback function that receives the "dragenter" event and context information as arguments:<br><br> * <code class="prettyprint">function(event, ui)</code><br><br> * This function should return false to indicate the dragged data can be accepted or true otherwise. Any explict return value will be passed back to jQuery. Returning false * will cause jQuery to call stopPropagation and preventDefault on the event, and calling preventDefault is required by HTML5 Drag and Drop to indicate acceptance of data.<br><br> * If this function doesn't return a value, dataTypes will be matched against the drag data types to determine if the data is acceptable. If there is a match, event.preventDefault * will be called to indicate that the data can be accepted. * @property {function} drop.rows.dragOver (optional) A callback function that receives the "dragover" event and context information as arguments:<br><br> * <code class="prettyprint">function(event, ui)</code><br><br> * Similar to dragEnter, this function should return false to indicate the dragged data can be accepted or true otherwise. If this function doesn't return a value, * dataTypes will be matched against the drag data types to determine if the data is acceptable. * @property {function} drop.rows.dragLeave (optional) A callback function that receives the "dragleave" event and context information as arguments:<br><br> * <code class="prettyprint">function(event, ui)</code> * @property {function} drop.rows.drop (required) A callback function that receives the "drop" event and context information as arguments:<br><br> * <code class="prettyprint">function(event, ui)</code><br><br> * This function should return false to indicate the dragged data is accepted or true otherwise.<br><br> * If the application needs to look at the data for the row being dropped on, it can use the getDataForVisibleRow method. * * @property {Object} reorder An object with property columns<br><br> * Enable or disable reordering the columns within the same table using drag and drop.<br><br> * Specify an object with the property "reorder" set to <code class="prettyprint">{'columns':'enabled'}</code> to enable * reordering. Setting the <code class="prettyprint">"reorder"</code> property to <code class="prettyprint">{'columns':'disabled'}</code>, * or setting the <code class="prettyprint">"dnd"</code> property to <code class="prettyprint">null</code> (or omitting * it), disables reordering support. Re-ordering is supported one column at a time. In addition, re-ordering will not re-order * any cells which have the colspan attribute with value > 1. Such cells will need to be re-ordered manually by listening to * the option change event on the columns option. * @property {string} reorder.columns column reordering within the table: "enabled", "disabled" * * @default <code class="prettyprint">{reorder: {columns :'disabled'}, drag: null, drop: null}</code> * @expose * @instance * @memberof! oj.ojTable * * @example <caption>Initialize the table to enable column reorder:</caption> * $( ".selector" ).ojTable({ "data":data, "dnd" : {"reorder":{"columns":"enabled"}}}); * * @example <caption>Initialize the table to enable dragging of selected rows using default behavior:</caption> * $( ".selector" ).ojTable({ "data":data, "dnd" : {"drag":{"rows":{"dataTypes":"application/ojtablerows+json"}}}}); */ dnd : {'drag': null, 'drop': null, 'reorder': {'columns' :'disabled'}}, /** * Determine if the table is read only or editable. Use 'none' if the table is strictly read only and will be a single Tab stop on the page. * Use 'rowEdit' if you want single row at a time editability. The table will initially render with all rows in read only mode. Pressing Enter/F2 or double click will make the current row editable and pressing Tab navigates to the next cell. Pressing ESC/F2 while in this mode will switch the table back to all rows in read only mode and will be a single Tab stop the page. * * @expose * @memberof! oj.ojTable * @instance * @type {string|null} * @ojvalue {string} "none" The table is read only and is a single Tab stop. * @ojvalue {string} "rowEdit" The table has single row at a time editability and the cells within the editable row are tabbable. * @default <code class="prettyprint">"none"</code> * @example <caption>Initialize the table with the <code class="prettyprint">editMode</code> option specified:</caption> * &lt;table id="table" summary="Department List" aria-label="Departments Table" * data-bind="ojComponent: {component: 'ojTable', data: datasource, editMode: 'rowEdit', columns: * [{headerText: 'Department Id', field: 'DepartmentId'}, * {headerText: 'Department Name', field: 'DepartmentName']}"&gt; */ editMode: 'none', /** * The text to display when there are no data in the Table. If it is not defined, * then a default empty text is extracted from the resource bundle. * * @expose * @memberof! oj.ojTable * @instance * @type {string|null} * @default <code class="prettyprint">"No data to display."</code> * @example <caption>Initialize the table with the <code class="prettyprint">emptyText</code> option specified:</caption> * &lt;table id="table" summary="Department List" aria-label="Departments Table" * data-bind="ojComponent: {component: 'ojTable', data: datasource, emptyText: 'No data', columns: * [{headerText: 'Department Id', field: 'DepartmentId'}, * {headerText: 'Department Name', field: 'DepartmentName']}"&gt; */ emptyText: null, /** * Whether the horizontal gridlines are to be drawn. Can be enabled or disabled. * The default value of auto means it's determined by the display option. * @expose * @public * @instance * @memberof! oj.ojTable * @type {string} * @ojvalue {string} "auto" Determined by display option. * @ojvalue {string} "enabled" Enabled. * @ojvalue {string} "disabled" Disabled. * @default <code class="prettyprint">"auto"</code> */ horizontalGridVisible: 'auto', /** * The row renderer function to use. * <p> * The renderer function will be passed in an Object which contains the fields: * <ul> * <li>component: A reference to the ojTable widgetConstructor</li> * <li>row: Key/value pairs of the row</li> * <li>status: Contains the rowIndex, rowKey, and currentRow</li> * <li>parentElement: Empty rendered TR element</li> * </ul> * The function returns either a String or * a DOM element of the content inside the row. If the developer chooses * to manipulate the row element directly, the function should return * nothing. * @expose * @public * @instance * @memberof! oj.ojTable * @type {Function|null} * @default <code class="prettyprint">null</code> */ rowRenderer: null, /** * Specifies the mechanism used to scroll the data inside the table. Possible values are: auto and loadMoreOnScroll. * When loadMoreOnScroll is specified, additional data are fetched when the user scrolls to the bottom of the table. * * @expose * @memberof! oj.ojTable * @instance * @type {string|null} * @ojvalue {string} "auto" Determined by component. The default is to display all data. * @ojvalue {string} "loadMoreOnScroll" Additional data are fetched when the user scrolls to the bottom of the table. * @default <code class="prettyprint">"auto"</code> * * @example <caption>Initialize the table with the <code class="prettyprint">scrollPolicy</code> option specified:</caption> * &lt;table id="table" ummary="Department List" aria-label="Departments Table" * data-bind="ojComponent: {component: 'ojTable', data: datasource, scrollPolicy: 'loadMoreOnScroll', columns: * [{headerText: 'Department Id', field: 'DepartmentId'}, * {headerText: 'Department Name', field: 'DepartmentName']}"&gt; */ scrollPolicy: "auto", /** * scrollPolicy options. * <p> * The following options are supported: * <ul> * <li>fetchSize: Fetch size for scroll.</li> * <li>maxCount: Maximum rows which will be displayed before fetching more rows will be stopped.</li> * </ul> * When scrollPolicy is loadMoreOnScroll, the next block of rows is fetched * when the user scrolls to the end of the table. The fetchSize option * determines how many rows are fetched in each block. * @expose * @public * @instance * @memberof! oj.ojTable * @type {Object.<string, string>|null} * @property {string} fetchSize the number of rows to fetch in each block of rows * @property {string} maxCount the number of rows which will be displayed before fetching more rows will be stopped * @default <code class="prettyprint">{'fetchSize': 25, 'maxCount': 500}</code> */ scrollPolicyOptions: {'fetchSize': 25, 'maxCount': 500}, /** * Specifies the current selections in the table. Can be either an index or key value. * When both are specified, the index is used as a hint. * Returns an array of range objects, or an empty array if there's no selection. * * @expose * @public * @instance * @memberof! oj.ojTable * @type {Array.<Object>} * @default <code class="prettyprint">[]</code> * * @example <caption>Get the current selection:</caption> * $( ".selector" ).ojTable("option", "selection"); * * @example <caption>Set a row selection on the table during initialization:</caption> * $(".selector").ojTable({"selection", [{startIndex: {"row":1}, endIndex:{"row":3}}]}); * * @example <caption>Set a column selection on the table during initialization:</caption> * $(".selector").ojTable({"selection", [{startIndex: {"column":2}, endIndex: {"column":4}}]}); * * @example <caption>Set a row selection on the table after initialization:</caption> * $(".selector").ojTable("option", "selection", [{startIndex: {"row":1}, endIndex:{"row":3}}]); * * @example <caption>Set a column selection on the table after initialization:</caption> * $(".selector").ojTable("option", "selection", [{startIndex: {"column":1}, endIndex: {"column":3}}]); * * @example <caption>Set a row selection on the table after initialization:</caption> * $(".selector").ojTable("option", "selection", [{startKey: {"row":10}, endKey:{"row":30}}]); * * @example <caption>Set a column selection on the table after initialization:</caption> * $(".selector").ojTable("option", "selection", [{startKey: {"column": column1}, endKey: {"column": column2}}]); */ selection: [], /** * The row and column selection modes. Both can be either single or multiple. * @expose * @public * @instance * @memberof! oj.ojTable * @type {Object.<string, string>|null} * @property {string} row single or multiple selection for rows * @property {string} column single or multiple selection for columns * @default <code class="prettyprint">null</code> * @example <caption>Initialize the table with the <code class="prettyprint">selectionMode</code> option specified:</caption> * &lt;table id="table" summary="Department List" aria-label="Departments Table" * data-bind="ojComponent: {component: 'ojTable', data: datasource, selectionMode: {row: 'multiple', column: 'multiple'}, columns: * [{headerText: 'Department Id', field: 'DepartmentId'}, * {headerText: 'Department Name', field: 'DepartmentName']}"&gt; */ selectionMode: null, /** * Whether the vertical gridlines are to be drawn. Can be enabled or disabled. * The default value of auto means it's determined by the display option. * @expose * @public * @instance * @memberof! oj.ojTable * @type {string} * @ojvalue {string} "auto" Determined by display option. * @ojvalue {string} "enabled" Enabled. * @ojvalue {string} "disabled" Disabled. * @default <code class="prettyprint">"auto"</code> */ verticalGridVisible: 'auto', /** * An array of column definitions. * @expose * @public * @instance * @memberof! oj.ojTable * @type {Array.<Object>|null} * @default <code class="prettyprint">null</code> * @example <caption>Initialize the table with the <code class="prettyprint">columns</code> option specified:</caption> * &lt;table id="table" summary="Department List" aria-label="Departments Table" * data-bind="ojComponent: {component: 'ojTable', data: datasource, columns: * [{headerText: 'Department Id', field: 'DepartmentId'}, * {headerText: 'Department Name', field: 'DepartmentName']}"&gt; */ columns: [{ /** * The renderer function that renders the content of the cell. * The function will be passed a context object which contains * the following objects: * <ul> * <li>data: The cell data</li> * <li>columnIndex: The column index</li> * <li>component: A reference to the ojTable widgetConstructor</li> * <li>datasource: Instance of the datasource used by the table </li> * <li>row: Key/value pairs of the row</li> * <li>status: Contains the rowIndex, rowKey, and currentRow</li> * <li>parentElement: Empty rendered <td> element</li> * </ul> * The function returns either a String or * a DOM element of the content inside the header. If the developer chooses * to manipulate the cell element directly, the function should return * nothing. If no renderer is specified, the Table will treat the cell data as a String. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columns[].renderer * @type {Function|null} * @default <code class="prettyprint">null</code> */ renderer: null, /** * The CSS class to apply to the column cells * @expose * @public * @instance * @memberof! oj.ojTable * @alias columns[].className * @type {string|null} * @default <code class="prettyprint">null</code> */ className: null, /** * The data field this column refers to. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columns[].field * @type {string|null} * @default <code class="prettyprint">null</code> */ field: null, /** * The CSS class to apply to the footer cell. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columns[].footerClassName * @type {string|null} * @default <code class="prettyprint">null</code> */ footerClassName: null, /** * The renderer function that renders the content of the footer. * The function will be passed a context object which contains * the following objects: * <ul> * <li>columnIndex: The column index</li> * <li>component: A reference to the ojTable widgetConstructor</li> * <li>datasource: Instance of the datasource used by the table </li> * <li>status: Contains the rowIndex, rowKey, and currentRow</li> * <li>parentElement: Empty rendered <td> element</li> * </ul> * The function returns either a String or * a DOM element of the content inside the footer. If the developer chooses * to manipulate the footer element directly, the function should return * nothing. If no renderer is specified, the Table will treat the footer data as a String. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columns[].footerRenderer * @type {Function|null} * @default <code class="prettyprint">null</code> */ footerRenderer: null, /** * The CSS styling to apply to the footer cell. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columns[].footerStyle * @type {string|null} * @default <code class="prettyprint">null</code> */ footerStyle: null, /** * The CSS class to apply to the column header text. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columns[].headerClassName * @type {string|null} * @default <code class="prettyprint">null</code> */ headerClassName: null, /** * The renderer function that renders the content of the header. * The function will be passed a context object which contains * the following objects: * <ul> * <li>columnIndex: The column index</li> * <li>component: A reference to the ojTable widgetConstructor</li> * <li>parentElement: Empty rendered TH element</li> * <li>columnHeaderDefaultRenderer(options, delegateRenderer): If the column * is not sortable then this function will be included in the context. * The options parameter specifies the options (future use) for the renderer while the * delegateRenderer parameter specifies the function which the developer would * like to be called during rendering of the column header.</li> * <li>columnHeaderSortableIconRenderer(options, delegateRenderer): If the column * is sortable then this function will be included in the context. * The options parameter specifies the options (future use) for the renderer while the * delegateRenderer parameter specifies the function which the developer would * like to be called during rendering of the sortable column header. Calling the * columnHeaderSortableIconRenderer function enables rendering custom header content * while also preserving the sort icons.</li> * </ul> * The function returns either a String or * a DOM element of the content inside the header. If the developer chooses * to manipulate the cell element directly, the function should return * nothing. If no renderer is specified, the Table will treat the header data as a String. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columns[].headerRenderer * @type {Function|null} * @default <code class="prettyprint">null</code> */ headerRenderer: null, /** * The CSS styling to apply to the column header text. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columns[].headerStyle * @type {string|null} * @default <code class="prettyprint">null</code> */ headerStyle: null, /** * Text to display in the header of the column. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columns[].headerText * @type {string|null} * @default <code class="prettyprint">null</code> */ headerText: null, /** * The identifier for the column * @expose * @public * @instance * @memberof! oj.ojTable * @alias columns[].id * @type {string|null} * @default <code class="prettyprint">null</code> */ id: null, /** * Whether or not the column is sortable. * <p> * A sortable column has a clickable header that (when clicked) * sorts the table by that column's property. Note that * in order for a column to be sortable, this attribute * must be set to "enabled" and the underlying model must * support sorting by this column's property. If this attribute * is set to "auto" then the column will be sortable if the * underlying model supports sorting. A value of "disabled" will * disable sorting on the column. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columns[].sortable * @type {string|null} * @ojvalue {string} "auto" Column will be sortable if the underlying model supports sorting. * @ojvalue {string} "enabled" Enabled. * @ojvalue {string} "disabled" Disabled. * @default <code class="prettyprint">"auto"</code> */ sortable: 'auto', /** * Indicates the row attribute used for sorting when sort is invoked on this * column. Useful for concatenated columns, where the sort is done by only a subset * of the concatenated items. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columns[].sortProperty * @type {string|null} * @default <code class="prettyprint">null</code> */ sortProperty: null, /** * The CSS styling to apply to the column cells * @expose * @public * @instance * @memberof! oj.ojTable * @alias columns[].style * @type {string|null} * @default <code class="prettyprint">null</code> */ style: null /** * The knockout template used to render the content of the column header. * * This attribute is only exposed via the <code class="prettyprint">ojComponent</code> binding, and is not a * component option. The following * variables are also passed into the template * <ul> * <li>$columnIndex: The column index</li> * <li>$data: The header text</li> * <li>$headerContext: The header context</li> * </ul> * </li> * * @ojbindingonly * @name columns[].headerTemplate * @memberof! oj.ojTable * @instance * @type {string|null} * @default <code class="prettyprint">null</code> * * @example <caption>Specify the column header <code class="prettyprint">template</code> when initializing Table:</caption> * // set the template * &lt;table id="table" summary="Department List" aria-label="Departments Table" * data-bind="ojComponent: {component: 'ojTable', data: dataSource, columns: * [{headerText: 'Department Id', field: 'DepartmentId'}, * {headerText: 'Department Name', field: 'DepartmentName'}, * {headerText: 'Location Id', field: 'LocationId'}, * {headerText: 'Manager Id', field: 'ManagerId'}, * {headerTemplate: 'oracle_link_hdr'}]}"&gt;&lt;/table&gt; */ /** * The knockout template used to render the content of the column footer. * * This attribute is only exposed via the <code class="prettyprint">ojComponent</code> binding, and is not a * component option. The following * variables are also passed into the template * <ul> * <li>$columnIndex: The column index</li> * <li>$footerContext: The header context</li> * </ul> * </li> * * @ojbindingonly * @name columns[].footerTemplate * @memberof! oj.ojTable * @instance * @type {string|null} * @default <code class="prettyprint">null</code> * * @example <caption>Specify the column footer <code class="prettyprint">template</code> when initializing Table:</caption> * // set the template * &lt;table id="table" summary="Department List" aria-label="Departments Table" * data-bind="ojComponent: {component: 'ojTable', data: dataSource, columnsDefault: * [{headerText: 'Department Id', field: 'DepartmentId'}, * {headerText: 'Department Name', field: 'DepartmentName'}, * {headerText: 'Location Id', field: 'LocationId'}, * {headerText: 'Manager Id', field: 'ManagerId'}, * {footerTemplate: 'oracle_link_ftr'}]}"&gt;&lt;/table&gt; */ }], /** * Default values to apply to all columns objects. * @expose * @public * @instance * @memberof! oj.ojTable * @type {Object.<string, string|null>} * @default <code class="prettyprint">null</code> * @example <caption>Initialize the table with the <code class="prettyprint">columnsDefault</code> option specified:</caption> * &lt;table id="table" summary="Department List" aria-label="Departments Table" * data-bind="ojComponent: {component: 'ojTable', data: datasource, columnsDefault: {headerStyle: 'text-align: left; white-space:nowrap;'}, columns: * [{headerText: 'Department Id', field: 'DepartmentId'}, * {headerText: 'Department Name', field: 'DepartmentName']}"&gt; */ columnsDefault: { /** * The renderer function that renders the content of the cell. * The function will be passed a context object which contains * the following objects: * <ul> * <li>data: The cell data</li> * <li>columnIndex: The column index</li> * <li>component: A reference to the ojTable widgetConstructor</li> * <li>datasource: Instance of the datasource used by the table </li> * <li>row: Key/value pairs of the row</li> * <li>status: Contains the rowIndex, rowKey, and currentRow</li> * <li>parentElement: Empty rendered <td> element</li> * </ul> * The function returns either a String or * a DOM element of the content inside the header. If the developer chooses * to manipulate the cell element directly, the function should return * nothing. If no renderer is specified, the Table will treat the cell data as a String. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columnsDefault.renderer * @type {Function|null} * @default <code class="prettyprint">null</code> */ renderer: null, /** * The default CSS class for column cells * @expose * @public * @instance * @memberof! oj.ojTable * @alias columnsDefault.className * @type {string|null} * @default <code class="prettyprint">null</code> */ className: null, /** * The default data field for column. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columnsDefault.field * @type {string|null} * @default <code class="prettyprint">null</code> */ field: null, /** * The CSS class to apply to the footer cell. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columnsDefault.footerClassName * @type {string|null} * @default <code class="prettyprint">null</code> */ footerClassName: null, /** * The renderer function that renders the content of the footer. * The function will be passed a context object which contains * the following objects: * <ul> * <li>columnIndex: The column index</li> * <li>component: A reference to the ojTable widgetConstructor</li> * <li>datasource: Instance of the datasource used by the table </li> * <li>status: Contains the rowIndex, rowKey, and currentRow</li> * <li>parentElement: Empty rendered <td> element</li> * </ul> * The function returns either a String or * a DOM element of the content inside the footer. If the developer chooses * to manipulate the footer element directly, the function should return * nothing. If no renderer is specified, the Table will treat the footer data as a String. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columnsDefault.footerRenderer * @type {Function|null} * @default <code class="prettyprint">null</code> */ footerRenderer: null, /** * The CSS styling to apply to the footer cell. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columnsDefault.footerStyle * @type {string|null} * @default <code class="prettyprint">null</code> */ footerStyle: null, /** * The default CSS class to apply to the column header. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columnsDefault.headerClassName * @type {string|null} * @default <code class="prettyprint">null</code> */ headerClassName: null, /** * The renderer function that renders the content of the header. * The function will be passed a context object which contains * the following objects: * <ul> * <li>columnIndex: The column index</li> * <li>component: A reference to the ojTable widgetConstructor</li> * <li>parentElement: Empty rendered TH element</li> * <li>columnHeaderDefaultRenderer(options, delegateRenderer): If the column * is not sortable then this function will be included in the context. * The options parameter specifies the options (future use) for the renderer while the * delegateRenderer parameter specifies the function which the developer would * like to be called during rendering of the column header.</li> * <li>columnHeaderSortableIconRenderer(options, delegateRenderer): If the column * is sortable then this function will be included in the context. * The options parameter specifies the options (future use) for the renderer while the * delegateRenderer parameter specifies the function which the developer would * like to be called during rendering of the sortable column header. Calling the * columnHeaderSortableIconRenderer function enables rendering custom header content * while also preserving the sort icons.</li> * </ul> * The function returns either a String or * a DOM element of the content inside the header. If the developer chooses * to manipulate the cell element directly, the function should return * nothing. If no renderer is specified, the Table will treat the header data as a String. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columnsDefault.headerRenderer * @type {Function|null} * @default <code class="prettyprint">null</code> */ headerRenderer: null, /** * The default CSS styling to apply to the column header. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columnsDefault.headerStyle * @type {string|null} * @default <code class="prettyprint">null</code> */ headerStyle: null, /** * Default text to display in the header of the column. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columnsDefault.headerText * @type {string|null} * @default <code class="prettyprint">null</code> */ headerText: null, /** * Whether or not the column is sortable. * <p> * A sortable column has a clickable header that (when clicked) * sorts the table by that column's property. Note that * in order for a column to be sortable, this attribute * must be set to "enabled" and the underlying model must * support sorting by this column's property. If this attribute * is set to "auto" then the column will be sortable if the * underlying model supports sorting. A value of "disabled" will * disable sorting on the column. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columnsDefault.sortable * @type {string|null} * @ojvalue {string} "auto" Column will be sortable if the underlying model supports sorting. * @ojvalue {string} "enabled" Enabled. * @ojvalue {string} "disabled" Disabled. * @default <code class="prettyprint">"auto"</code> */ sortable: 'auto', /** * Indicates the row attribute used for sorting when sort is invoked on this * column. Useful for concatenated columns, where the sort is done by only a subset * of the concatenated items. * @expose * @public * @instance * @memberof! oj.ojTable * @alias columnsDefault.sortProperty * @type {string|null} * @default <code class="prettyprint">null</code> */ sortProperty: null, /** * Default CSS styling to apply to the column cells * @expose * @public * @instance * @memberof! oj.ojTable * @alias columnsDefault.style * @type {string|null} * @default <code class="prettyprint">null</code> */ style: null /** * The default knockout template used to render the content of the column header. * * This attribute is only exposed via the <code class="prettyprint">ojComponent</code> binding, and is not a * component option. The following * variables are also passed into the template * <ul> * <li>$columnIndex: The column index</li> * <li>$data: The header text</li> * <li>$headerContext: The header context</li> * </ul> * </li> * * @ojbindingonly * @name columnsDefault.headerTemplate * @memberof! oj.ojTable * @instance * @type {string|null} * @default <code class="prettyprint">null</code> * * @example <caption>Specify the column header <code class="prettyprint">template</code> when initializing Table:</caption> * // set the template * &lt;table id="table" summary="Department List" aria-label="Departments Table" * data-bind="ojComponent: {component: 'ojTable', data: dataSource, columnsDefault: * [{headerText: 'Department Id', field: 'DepartmentId'}, * {headerText: 'Department Name', field: 'DepartmentName'}, * {headerText: 'Location Id', field: 'LocationId'}, * {headerText: 'Manager Id', field: 'ManagerId'}, * {headerTemplate: 'oracle_link_hdr'}]}"&gt;&lt;/table&gt; */ /** * The default knockout template used to render the content of the column footer. * * This attribute is only exposed via the <code class="prettyprint">ojComponent</code> binding, and is not a * component option. The following * variables are also passed into the template * <ul> * <li>$columnIndex: The column index</li> * <li>$footerContext: The header context</li> * </ul> * </li> * * @ojbindingonly * @name columnsDefault.footerTemplate * @memberof! oj.ojTable * @instance * @type {string|null} * @default <code class="prettyprint">null</code> * * @example <caption>Specify the column footer <code class="prettyprint">template</code> when initializing Table:</caption> * // set the template * &lt;table id="table" summary="Department List" aria-label="Departments Table" * data-bind="ojComponent: {component: 'ojTable', data: dataSource, columnsDefault: * [{headerText: 'Department Id', field: 'DepartmentId'}, * {headerText: 'Department Name', field: 'DepartmentName'}, * {headerText: 'Location Id', field: 'LocationId'}, * {headerText: 'Manager Id', field: 'ManagerId'}, * {footerTemplate: 'oracle_link_ftr'}]}"&gt;&lt;/table&gt; */ }, /** * Triggered before the current row is changed via the <code class="prettyprint">currentRow</code> option or via the UI. * * @expose * @event * @memberof! oj.ojTable * @instance * @property {Event} event <code class="prettyprint">jQuery</code> event object * @property {Object} ui Parameters * @property {Object} ui.currentRow the new current row * @property {number} ui.currentRow.rowIndex current row index * @property {string} ui.currentRow.rowKey current row key * @property {number} ui.previousCurrentRow the previous current row * @property {number} ui.previousCurrentRow.rowIndex previous current row index * @property {string} ui.previousCurrentRow.rowKey previous current row key * * @example <caption>Initialize the table with the <code class="prettyprint">beforeCurrentRow</code> callback specified:</caption> * $( ".selector" ).ojTable({ * "beforeCurrentRow": function( event, ui ) {} * }); * * @example <caption>Bind an event listener to the <code class="prettyprint">ojbeforecurrentrow</code> event:</caption> * $( ".selector" ).on( "ojbeforecurrentrow", function( event, ui ) * { * // verify that the component firing the event is a component of interest * if ($(event.target).is(".mySelector")) {} * } * ); */ beforeCurrentRow: null, /** * Triggered before the table is going to enter edit mode. To prevent editing the row return false. * * @expose * @event * @memberof! oj.ojTable * @instance * @property {Event} event <code class="prettyprint">jQuery</code> event object * @property {Object} ui Parameters * @property {Object} ui.rowContext the rowContext of the row that editing is going to be performed on. * * @example <caption>Initialize the table with the <code class="prettyprint">beforeEdit</code> callback specified:</caption> * $( ".selector" ).ojTable({ * "beforeRowEdit": function( event, ui ) {} * }); * * @example <caption>Bind an event listener to the <code class="prettyprint">ojbeforerowedit</code> event:</caption> * $( ".selector" ).on( "ojbeforerowedit", function( event, ui ) * { * // verify that the component firing the event is a component of interest * if ($(event.target).is(".mySelector")) {} * } * ); */ beforeRowEdit: null, /** * Triggered before the table is going to exit edit mode. To prevent exit editing return false. * There is a provided beforeRowEditEnd function, oj.DataCollectionEditUtils.basicHandleRowEditEnd, which can be specified. * This function will handle canceling edits as well as invoking validation on input components. * * @expose * @event * @memberof! oj.ojTable * @instance * @property {Event} event <code class="prettyprint">jQuery</code> event object * @property {Object} ui Parameters * @property {Object} ui.rowContext the rowContext of the row that editing is going to be performed on. * @property {Object} ui.cancelEdit true if the edit should be negated based on actions (i.e. escape key). * * @example <caption>Initialize the table with the <code class="prettyprint">beforeRowEditEnd</code> callback specified:</caption> * $( ".selector" ).ojTable({ * "beforeRowEditEnd": function( event, ui ) {} * }); * * @example <caption>Bind an event listener to the <code class="prettyprint">ojbeforeroweditend</code> event:</caption> * $( ".selector" ).on( "ojbeforeroweditend", function( event, ui ) * { * // verify that the component firing the event is a component of interest * if ($(event.target).is(".mySelector")) {} * } * ); */ beforeRowEditEnd: null, /** * Triggered when the table has finished rendering * * @expose * @event * @memberof! oj.ojTable * @instance * * @example <caption>Initialize the table with the <code class="prettyprint">ready</code> callback specified:</caption> * $( ".selector" ).ojTable({ * "ready": function() {} * }); * * @example <caption>Bind an event listener to the <code class="prettyprint">ojready</code> event:</caption> * $( ".selector" ).on( "ojready", function() * { * // verify that the component firing the event is a component of interest * if ($(event.target).is(".mySelector")) {} * } * ); */ ready: null, /** * Triggered when a sort is performed on the table * * @expose * @event * @memberof! oj.ojTable * @instance * @property {Event} event <code class="prettyprint">jQuery</code> event object * @property {Object} ui Parameters * @property {Element} ui.header the key of the header which was sorted on * @property {string} ui.direction the direction of the sort ascending/descending * * @example <caption>Initialize the table with the <code class="prettyprint">sort</code> callback specified:</caption> * $( ".selector" ).ojTable({ * "sort": function( event, ui ) {} * }); * * @example <caption>Bind an event listener to the <code class="prettyprint">ojsort</code> event:</caption> * $( ".selector" ).on( "ojsort", function( event, ui ) * { * // verify that the component firing the event is a component of interest * if ($(event.target).is(".mySelector")) {} * } * ); */ sort: null /** * The knockout template used to render the content of the row. * * This attribute is only exposed via the <code class="prettyprint">ojComponent</code> binding, and is not a * component option. The following * variables are also passed into the template * <ul> * <li>$rowContext: The row context</li> * </ul> * </li> * * @ojbindingonly * @name rowTemplate * @memberof! oj.ojTable * @instance * @type {string|null} * @default <code class="prettyprint">null</code> * * @example <caption>Specify the row <code class="prettyprint">template</code> when initializing Table:</caption> * // set the template * &lt;table id="table" summary="Department List" aria-label="Departments Table" * data-bind="ojComponent: {component: 'ojTable', data: dataSource, rowTemplate: 'row_tmpl'}"&gt;&lt;/table&gt; */ }, /** * @const * @private */ _BUNDLE_KEY: { _MSG_FETCHING_DATA: 'msgFetchingData', _MSG_NO_DATA: 'msgNoData', _MSG_INITIALIZING: 'msgInitializing', _MSG_STATUS_SORT_ASC: 'msgStatusSortAscending', _MSG_STATUS_SORT_DSC: 'msgStatusSortDescending', _LABEL_SELECT_COLUMN: 'labelSelectColumn', _LABEL_SELECT_ROW: 'labelSelectRow', _LABEL_EDIT_ROW: 'labelEditRow', _LABEL_SELECT_AND_EDIT_ROW: 'labelSelectAndEditRow' }, /** * @const * @private */ _LOGGER_MSG: { _ERR_PRECURRENTROW_ERROR_SUMMARY: 'Did not change current row due to error.', _ERR_PRECURRENTROW_ERROR_DETAIL: 'Error detail: {error}.', _ERR_CURRENTROW_UNAVAILABLE_INDEX_SUMMARY: 'Did not change current row due to unavailable row index.', _ERR_CURRENTROW_UNAVAILABLE_INDEX_DETAIL: 'Unavailable row index: {rowIdx}.', _ERR_REFRESHROW_INVALID_INDEX_SUMMARY: 'Invalid row index value.', _ERR_REFRESHROW_INVALID_INDEX_DETAIL: 'Row index: {rowIdx}.', _ERR_DATA_INVALID_TYPE_SUMMARY: 'Invalid data type.', _ERR_DATA_INVALID_TYPE_DETAIL: 'Please specify the appropriate data type.', _ERR_ELEMENT_INVALID_TYPE_SUMMARY: 'Invalid element type.', _ERR_ELEMENT_INVALID_TYPE_DETAIL: 'Only a <table> element can be specified for ojTable.', _ERR_DOM_SCROLLER_MAX_COUNT_SUMMARY: 'Exceeded maximum rows for table scrolling.', _ERR_DOM_SCROLLER_MAX_COUNT_DETAIL: 'Please reload with smaller data set.' }, /** * @private * @const * @type {string} */ _FIELD_ID: 'id', /** * @private * @const * @type {string} */ _CONST_DATA: 'data', /** * @private * @const * @type {string} */ _CONST_METADATA: 'metadata', /** * @private * @const * @type {string} */ _CONST_INDEXES: 'indexes', /** * @private * @const * @type {string} */ _CONST_KEY: 'key', /** * @private * @const * @type {string} */ _CONST_KEYS: 'keys', /** * @private * @const * @type {string} */ _CONST_STARTINDEX: 'startIndex', /** * @private * @const * @type {string} */ _CONST_ENDINDEX: 'endIndex', /** * @private * @const * @type {string} */ _CONST_PAGESIZE: 'pageSize', /** * @private * @const * @type {string} */ _CONST_COLUMN: 'column', /** * @private * @const * @type {string} */ _CONST_ROW: 'row', /** * @private * @const * @type {string} */ _COLUMN_HEADER_ID: '_headerColumn', /** * @private * @const * @type {string} */ _COLUMN_HEADER_TEXT_ID: '_headerColumnText', /** * @private * @const * @type {string} */ _COLUMN_HEADER_ASC_ID: '_headerColumnAsc', /** * @private * @const * @type {string} */ _COLUMN_HEADER_DSC_ID: '_headerColumnDsc', /** * @private * @const * @type {string} */ _COLUMN_HEADER_ID_PREFIX: '_hdrCol', /** * @private * @const * @type {string} */ _FOCUS_CALLED: '_focusedCalled', /** * @private * @const * @type {string} */ _OPTION_AUTO: 'auto', /** * @private * @const * @type {string} */ _OPTION_ENABLED: 'enabled', /** * @private * @const * @type {string} */ _OPTION_DISABLED: 'disabled', /** * @private * @const */ _OPTION_EDIT_MODE: { _NONE: 'none', _ROW_EDIT: 'rowEdit' }, /** * @private * @const */ _OPTION_SELECTION_MODES: { _SINGLE: 'single', _MULTIPLE: 'multiple' }, /** * @private * @const */ _OPTION_SCROLL_POLICY: { _AUTO: 'auto', _LOADMORE_ON_SCROLL: 'loadMoreOnScroll' }, /** * @private * @const */ _COLUMN_SORT_ORDER: { _ASCENDING: 'ascending', _DESCENDING: 'descending' }, /** * @private * @const */ _DND_REORDER_TABLE_ID_DATA_KEY: 'oj-table-dnd-reorder-table-id', /** * @private * @const */ _KEYBOARD_CODES: { _KEYBOARD_CODE_SPACEBAR: 32, _KEYBOARD_CODE_ENTER: 13, _KEYBOARD_CODE_UP: 38, _KEYBOARD_CODE_DOWN: 40, _KEYBOARD_CODE_LEFT: 37, _KEYBOARD_CODE_RIGHT: 39, _KEYBOARD_CODE_HOME: 36, _KEYBOARD_CODE_END: 35, _KEYBOARD_CODE_TAB: 9, _KEYBOARD_CODE_ESC: 27, _KEYBOARD_CODE_F2: 113, _KEYBOARD_MODIFIER_SHIFT: 'shiftKey' }, /**** start Public APIs ****/ /** * {@ojinclude "name":"nodeContextDoc"} * @param {!Element} node - {@ojinclude "name":"nodeContextParam"} * @returns {Object|null} {@ojinclude "name":"nodeContextReturn"} * * @example {@ojinclude "name":"nodeContextExample"} * * @expose * @instance * @memberof oj.ojTable */ getContextByNode: function(node) { // context objects are documented with @ojnodecontext var context = this.getSubIdByNode(node, true); if (context) { if (context['subId'] == 'oj-table-cell') { var rowIdx = context['rowIndex']; var rowKey = this._getRowKeyForRowIdx(rowIdx); context['key'] = rowKey; } } return context; }, /** * Return the row data for a rendered row in the table. * @param {Number} rowIndex row index * @returns {Object | null} a compound object which has the structure below. If the row has not been rendered, returns null.<p> * <table> * <tbody> * <tr><td><b>data</b></td><td>The raw row data</td></tr> * <tr><td><b>index</b></td><td>The index for the row</td></tr> * <tr><td><b>key</b></td><td>The key value for the row</td></tr> * </tbody> * </table> * @export * @expose * @memberof! oj.ojTable * @instance * @example <caption>Invoke the <code class="prettyprint">getDataForVisibleRow</code> method:</caption> * $( ".selector" ).ojTable( "getDataForVisibleRow", 2 ); */ 'getDataForVisibleRow': function(rowIndex) { var tableBodyRow = this._getTableDomUtils().getTableBodyRow(rowIndex); if (tableBodyRow != null) { return {'key': tableBodyRow.data('rowKey'), 'data': tableBodyRow.data('rowData'), 'index': rowIndex}; } return null; }, //** @inheritdoc */ 'getNodeBySubId': function(locator) { if (locator == null) { return this.element ? this.element[0] : null; } var subId = locator['subId']; if (subId === 'oj-table-cell') { var rowIdx = parseInt(locator['rowIndex'], 10); var columnIdx = parseInt(locator['columnIndex'], 10); return this._getTableDomUtils().getTableBodyLogicalCells(rowIdx)[columnIdx]; } else if (subId === 'oj-table-header' || subId === 'oj-table-sort-ascending' || subId === 'oj-table-sort-descending') { var columnIdx = locator['index']; var tableHeaderColumn = $(this._getTableDomUtils().getTableHeaderLogicalColumns()[columnIdx]); if (tableHeaderColumn != null) { if (subId === 'oj-table-header') { return tableHeaderColumn[0]; } else if (subId === 'oj-table-sort-ascending') { var tableHeaderColumnSortAsc = tableHeaderColumn.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ASC_LINK_CLASS); if (tableHeaderColumnSortAsc.length > 0) { return tableHeaderColumnSortAsc[0]; } } else { var tableHeaderColumnSortDsc = tableHeaderColumn.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DSC_LINK_CLASS); if (tableHeaderColumnSortDsc.length > 0) { return tableHeaderColumnSortDsc[0]; } } } } else if (subId === 'oj-table-footer') { var columnIdx = locator['index']; var tableFooterCell = this._getTableDomUtils().getTableFooterLogicalCells()[columnIdx]; if (tableFooterCell != null) { return tableFooterCell; } } // Non-null locators have to be handled by the component subclasses return null; }, //** @inheritdoc */ 'getSubIdByNode': function(node, ignoreSortIcons) { var cell = $(node).closest('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_CELL_CLASS); if (cell.length > 0) { return {'subId': 'oj-table-cell', 'rowIndex': this._getTableDomUtils().getElementRowIdx(cell), 'columnIndex': this._getTableDomUtils().getElementColumnIdx(cell)}; } var headerSortAsc = $(node).closest('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ASC_LINK_CLASS); if (headerSortAsc.length > 0) { return {'subId': ignoreSortIcons ? 'oj-table-header' : 'oj-table-sort-ascending', 'index': this._getTableDomUtils().getElementColumnIdx(headerSortAsc)}; } var headerSortDsc = $(node).closest('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DSC_LINK_CLASS); if (headerSortDsc.length > 0) { return {'subId': ignoreSortIcons ? 'oj-table-header' : 'oj-table-sort-descending', 'index': this._getTableDomUtils().getElementColumnIdx(headerSortDsc)}; } var header = $(node).closest('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_CELL_CLASS); if (header.length > 0) { return {'subId': 'oj-table-header', 'index': this._getTableDomUtils().getElementColumnIdx(header)}; } var footer = $(node).closest('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_FOOTER_CELL_CLASS); if (footer.length > 0) { return {'subId': 'oj-table-footer', 'index': this._getTableDomUtils().getElementColumnIdx(footer)}; } return null; }, /** * Refresh the table. * @export * @expose * @memberof! oj.ojTable * @instance * @example <caption>Invoke the <code class="prettyprint">refresh</code> method:</caption> * $( ".selector" ).ojTable( "refresh" ); */ 'refresh': function() { this._super(); this._refresh(); }, /** * Refresh a row in the table. * @param {number} rowIdx Index of the row to refresh. * @return {Promise} Promise resolves when done to true if refreshed, false if not * @throws {Error} * @export * @expose * @memberof! oj.ojTable * @instance * @example <caption>Invoke the <code class="prettyprint">refreshRow</code> method:</caption> * $( ".selector" ).ojTable( "refreshRow", 1 ); */ 'refreshRow': function(rowIdx) { var data = this._getData(); // if no data then bail if (!data) { return Promise.resolve(false); } var tableBodyRows = this._getTableDomUtils().getTableBodyRows(); if (isNaN(rowIdx) || rowIdx < 0 || (tableBodyRows != null && rowIdx >= tableBodyRows.length)) { // validate rowIdx value var errSummary = this._LOGGER_MSG._ERR_REFRESHROW_INVALID_INDEX_SUMMARY; var errDetail = oj.Translations.applyParameters(this._LOGGER_MSG._ERR_REFRESHROW_INVALID_INDEX_DETAIL, {'rowIdx': rowIdx.toString()}); throw new RangeError(errSummary + '\n' + errDetail); } // get row at rowIdx var rowKey = this._getRowKeyForRowIdx(rowIdx); var row = data.get(rowKey); if (row == null) { return Promise.resolve(false); } var self = this; return new Promise(function(resolve, reject) { // refresh table row DOM with row row.then(function(row) { if (row == null) { resolve(false); } self._queueTask(function() { self._refreshTableBodyRow(rowIdx, row); self = null; }); resolve(true); }); }); }, /** * Returns a jQuery object containing the root dom element of the table * * <p>This method does not accept any arguments. * * @expose * @override * @memberof oj.ojTable * @instance * @return {jQuery} the root DOM element of table */ 'widget' : function () { var tableContainer = this._getTableDomUtils().getTableContainer(); if (tableContainer != null) { return tableContainer; } return this.element; }, /**** end Public APIs ****/ /**** start internal widget functions ****/ /** * @override * @protected * @instance * @memberof! oj.ojTable */ _ComponentCreate : function () { this._super(); this._draw(); this._registerCustomEvents(); this._on(this._events); if (this._isTouchDevice()) { var tableContainer = this._getTableDomUtils().getTableContainer(); this._on(tableContainer, this._eventsContainer); } this._registerDomEventListeners(); // cache the options this._cachedOptions = $.extend(true, {}, this.options); this._setEditableRowIdx(null); }, /** * Initialize the table after creation * @protected * @override * @memberof! oj.ojTable */ _AfterCreate: function () { this._super(); // create the context menu this._getTableDomUtils().createContextMenu(this._handleContextMenuSelect.bind(this)); this._isInitFetch = true; }, /** * Sets up needed resources for table, for example, add * listeners. * @protected * @override * @memberof! oj.ojTable */ _SetupResources: function () { this._super(); this._registerResizeListener(); // register event listeners for table on the datasource so that the table // component is notified when rows are added, deleted, etc from the datasource. this._registerDataSourceEventListeners(); if (this._isInitFetch) { this._initFetch(); this._isInitFetch = false; } else { this._invokeDataFetchRows(); } }, /** * Releases resources for table. * @protected * @override * @memberof! oj.ojTable */ _ReleaseResources: function () { this._super(); // unregister the listeners on the datasource this._unregisterDataSourceEventListeners(); this._unregisterResizeListener(); }, /** * <p>Notifies the component that its subtree has been connected to the document programmatically after the component has * been created. * * @memberof! oj.ojTable * @instance * @protected * @override */ _NotifyAttached: function() { this._super(); this._getTableDomUtils().refreshTableDimensions(); }, /** * <p>Notifies the component that its subtree has been made visible programmatically after the component has * been created. * * @memberof! oj.ojTable * @instance * @protected * @override */ _NotifyShown: function() { this._super(); this._getTableDomUtils().refreshTableDimensions(); }, /** * @param {Object} contextMenu The JET Menu to open as a context menu * @param {Event} event What triggered the menu launch * @param {string} eventType "mouse", "touch", "keyboard" * @private */ _NotifyContextMenuGesture: function(contextMenu, event, eventType) { var openOptions = {}; this._contextMenuEvent = event['originalEvent']; // first check if we are invoking on an editable or clickable element, or draggable element on touch event. If so bail if (this._isNodeEditable($(this._contextMenuEvent['target'])) || this._isNodeClickable($(this._contextMenuEvent['target'])) || (eventType == 'touch' && this._isNodeDraggable($(this._contextMenuEvent['target'])))) { return; } var headerColumn = this._getTableDomUtils().getFirstAncestor($(this._contextMenuEvent['target']), 'oj-table-column-header-cell'); headerColumn = headerColumn == null ? this._getTableDomUtils().getTableHeaderColumn(this._activeColumnIndex) : headerColumn; var tableBodyCell = this._getTableDomUtils().getFirstAncestor($(this._contextMenuEvent['target']), 'oj-table-data-cell'); if (tableBodyCell != null) { var columnIdx = this._getTableDomUtils().getElementColumnIdx(tableBodyCell); headerColumn = this._getTableDomUtils().getTableHeaderColumn(columnIdx); } if (this._contextMenuEvent['type'] === 'keydown') { var table = this._tableDomUtils.getTable(); if (this._contextMenuEvent['target'] == table[0]) { if (headerColumn != null && headerColumn[0] != null) { openOptions['position'] = {"my": "start top", "at": "start bottom", "of": headerColumn[0]}; } else { var focusedRowIdx = this._getFocusedRowIdx(); if (focusedRowIdx >= 0) { var tableBodyRow = this._getTableDomUtils().getTableBodyRow(focusedRowIdx); openOptions['position'] = {"my": "start top", "at": "start bottom", "of": tableBodyRow[0]}; } else { openOptions['position'] = {"my": "start top", "at": "start bottom", "of": this._contextMenuEvent['target']}; } } } else { openOptions['position'] = {"my": "start top", "at": "start bottom", "of": this._contextMenuEvent['target']}; } } if (headerColumn.attr('data-oj-sortable') == this._OPTION_ENABLED) { $(contextMenu['element']).find('[data-oj-command=oj-table-sortAsc]').removeClass('oj-disabled'); $(contextMenu['element']).find('[data-oj-command=oj-table-sortDsc]').removeClass('oj-disabled'); } else { $(contextMenu['element']).find('[data-oj-command=oj-table-sortAsc]').addClass('oj-disabled'); $(contextMenu['element']).find('[data-oj-command=oj-table-sortDsc]').addClass('oj-disabled'); } this._OpenContextMenu(event, eventType, openOptions); }, /** * @override * @private */ _destroy: function() { this._getTableDomUtils().getTableBody().removeAttr(oj.Components._OJ_CONTAINER_ATTR); this.element.children().remove('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_HEADER_CLASS); this.element.children().remove('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_BODY_CLASS); this.element.children().remove('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_FOOTER_CLASS); this.element.children().remove('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_STATUS_MESSAGE_CLASS); this.element.children().remove('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_BODY_MESSAGE_ROW_CLASS); // - DomUtils.unwrap() will avoid unwrapping if the node is being destroyed by Knockout oj.DomUtils.unwrap(this.element, this._getTableDomUtils().getTableContainer()); this.element.removeClass(oj.TableDomUtils.CSS_CLASSES._TABLE_CLASS); // Remove any pending busy states if (this._readyResolveFunc) { this._readyResolveFunc(); this._readyResolveFunc = null; } if (this._dataResolveFunc) { this._dataResolveFunc(); this._dataResolveFunc = null; } this._componentDestroyed = true; }, /** * @override * @private */ _draw: function() { var options = this.options; this._setFinalTask(function() { this._getTableDomUtils().refreshTableDimensions(); this._setSelection(this.options['selection']); if (this._hasEditableRow()) { // set the editable row class if editable var editableRowIdx = this._getEditableRowIdx(); var editableTableBodyRow = this._getTableDomUtils().getTableBodyRow(editableRowIdx); if (editableTableBodyRow != null) { editableTableBodyRow.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_EDIT_CLASS); } } // if loadMoreOnScroll then check if we have underflow and do a // fetch if we do if (this._isLoadMoreOnScroll() && !this._dataFetching) { this._domScroller.checkViewport().then(this._domScrollerMaxCountFunc, null); } }); if (!this.element.is('table')) { var errSummary = this._LOGGER_MSG._ERR_ELEMENT_INVALID_TYPE_SUMMARY; var errDetail = this._LOGGER_MSG._ERR_ELEMENT_INVALID_TYPE_DETAIL; throw new RangeError(errSummary + '\n' + errDetail); } // add css class to element this.element.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_ELEMENT_CLASS); // create the initial table structure this._getTableDomUtils().createInitialTable(this._isTableHeaderless(), this._isTableFooterless()); // style the initial table structure this._getTableDomUtils().styleInitialTable(); // populate the table header DOM with header content this._refreshTableHeader(); // populate the table footer DOM with footer content this._refreshTableFooter(); this._refreshTableBody(); // resize the table dimensions to accomodate the completed tableheader this._getTableDomUtils().refreshTableDimensions(); // initialize a DomScroller if loadMoreOnScroll if (this._isLoadMoreOnScroll()) { this._registerDomScroller(); } if (this.options.disabled) { this.disable(); } }, /** * @override * @private */ _events: { /** * Reset the keyboard state on focusout and set the inactive * selected rows */ 'focusout': function(event) { // make sure the focusout isn't for a focus to an element within // the table var table = this._getTableDomUtils().getTable(); var focusElement = null; if (event.relatedTarget != null) { // In Chrome we can check relatedTarget focusElement = event.relatedTarget; } else if (event.originalEvent != null && event.originalEvent.explicitOriginalTarget != null) { // In FF we check explicitOriginalTarget focusElement = event.originalEvent.explicitOriginalTarget; } else if (this._getTableDomUtils()._isIE() && document.activeElement != null) { // In IE we check document.activeElement focusElement = document.activeElement; } if (focusElement != null && (focusElement == table[0] || table.has(focusElement).length > 0)) { return; } this._clearKeyboardKeys(); this._clearFocusedHeaderColumn(); this._clearFocusedRow(false); this._setTableActionableMode(false); }, /** * Remove the cell edit class on cell focus when row is editable. */ 'blur .oj-table-data-cell': function(event) { if ($(event.currentTarget).hasClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_CELL_EDIT_CLASS)) { $(event.currentTarget).removeClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_CELL_EDIT_CLASS); } }, /** * Check the keyboard state on focus */ 'focus': function(event) { this._checkRowOrHeaderColumnFocus(event); }, /** * Handle focus on child row elements */ 'focusin': function(event) { var tableBody = this._getTableDomUtils().getTableBody(); if (tableBody.has(event.target).length > 0) { var focusedRowIdx = this._getFocusedRowIdx(); var focusedHeaderColumnIdx = this._getFocusedHeaderColumnIdx(); if (!this._isNodeEditable($(event.target)) && !this._isTableActionableMode() && !this._hasEditableRow() && !this._temporaryTableChildElementFocus && focusedRowIdx == null && focusedHeaderColumnIdx == null) { // when table is not in editable/actionable mode there shouldn't be // focus to child row elements. Delay the focus to prevent a race // condition with menu launcher re-focus var self = this; setTimeout(function () { self._getTableDomUtils().getTable().focus(); }, 0); } } }, /** * Check the keyboard state on focus */ 'focus .oj-table-column-header-acc-asc-link': function(event) { var self = this; setTimeout(function() { // delay the column/row focus just in case a column/row is clicked. self._checkRowOrHeaderColumnFocus(event); self = null; }, 0); }, /** * Set the cell edit class on cell focus when row is editable. */ 'focus .oj-table-data-cell': function(event) { var rowIdx = this._getTableDomUtils().getElementRowIdx($(event.currentTarget)); if (rowIdx == this._getEditableRowIdx()) { $(event.currentTarget).addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_CELL_EDIT_CLASS); } }, /** * Capture acc selected column event */ 'click .oj-table-checkbox-acc-select-column': function(event) { var columnIdx = this._getTableDomUtils().getElementColumnIdx($(event.currentTarget)); var selected = $(event.currentTarget).is(':checked'); // if selected then focus on the column if (selected) { this._setHeaderColumnFocus(columnIdx, true, true, null); } this._setHeaderColumnSelection(columnIdx, selected, event.currentTarget, event, true); event.stopPropagation(); }, /** * Capture acc selected row event */ 'click .oj-table-checkbox-acc-select-row': function(event) { var rowIdx = this._getTableDomUtils().getElementRowIdx($(event.currentTarget)); var selected = $(event.currentTarget).is(':checked'); var focused = false; // if selected then focus on the row if (selected) { focused = this._setRowFocus(rowIdx, true, true, null, event, true); } else { this._setTableEditable(false, false, 0, true, event); } if (focused) { this._setRowSelection(rowIdx, selected, event.currentTarget, event, true); this._setTableEditable(true, false, 0, true, event); } event.stopPropagation(); }, /** * Capture keyboard down events */ 'keydown': function(event) { this._addKeyboardKey(event.keyCode); // ignore key event on the footer or target is editable var keyboardCode1 = this._getKeyboardKeys()[0]; if (keyboardCode1 != this._KEYBOARD_CODES._KEYBOARD_CODE_TAB && (this._isNodeEditable($(event.target)) || this._getTableDomUtils().getTableFooter() != null && this._getTableDomUtils().getTableFooter().has(event.target).length > 0)) { return; } // process single or two key events if (this._getKeyboardKeys().length == 1 || (this._getKeyboardKeys().length == 2 && event[this._KEYBOARD_CODES._KEYBOARD_MODIFIER_SHIFT])) { if (this._isKeyboardKeyPressed(this._KEYBOARD_CODES._KEYBOARD_CODE_UP) || this._isKeyboardKeyPressed(this._KEYBOARD_CODES._KEYBOARD_CODE_DOWN) || this._isKeyboardKeyPressed(this._KEYBOARD_CODES._KEYBOARD_CODE_SPACEBAR) || this._isKeyboardKeyPressed(this._KEYBOARD_CODES._KEYBOARD_CODE_HOME) || this._isKeyboardKeyPressed(this._KEYBOARD_CODES._KEYBOARD_CODE_END)) { // need to do this so that these keys don't act on the page. e.g. pressing Down would cause the // page to go down as well as the row to change event.preventDefault(); event.stopPropagation(); } if (this._isKeyboardKeyPressed(this._KEYBOARD_CODES._KEYBOARD_CODE_UP) || this._isKeyboardKeyPressed(this._KEYBOARD_CODES._KEYBOARD_CODE_DOWN)) { this._handleKeydownUpDown(event); } else if (this._isKeyboardKeyPressed(this._KEYBOARD_CODES._KEYBOARD_CODE_LEFT) || this._isKeyboardKeyPressed(this._KEYBOARD_CODES._KEYBOARD_CODE_RIGHT)) { this._handleKeydownLeftRight(event); } else if (this._isKeyboardKeyPressed(this._KEYBOARD_CODES._KEYBOARD_CODE_TAB)) { this._handleKeydownTab(event); } } }, /** * Capture keyboard up events */ 'keyup': function(event) { // process single or 2 key events if (this._getKeyboardKeys().length == 1) { var keyboardCode1 = this._getKeyboardKeys()[0]; // ignore key event on the footer or target is editable if (keyboardCode1 != this._KEYBOARD_CODES._KEYBOARD_CODE_ESC && keyboardCode1 != this._KEYBOARD_CODES._KEYBOARD_CODE_ENTER && keyboardCode1 != this._KEYBOARD_CODES._KEYBOARD_CODE_F2 && keyboardCode1 != this._KEYBOARD_CODES._KEYBOARD_CODE_TAB && (this._isNodeEditable($(event.target)) || this._getTableDomUtils().getTableFooter() != null && this._getTableDomUtils().getTableFooter().has(event.target).length > 0)) { this._removeKeyboardKey(keyboardCode1); return; } if (keyboardCode1 == this._KEYBOARD_CODES._KEYBOARD_CODE_SPACEBAR) { this._handleKeyupSpacebar(event); } else if (keyboardCode1 == this._KEYBOARD_CODES._KEYBOARD_CODE_ENTER) { this._handleKeyupEnter(event); } else if (keyboardCode1 == this._KEYBOARD_CODES._KEYBOARD_CODE_HOME) { this._handleKeyupHome(event); } else if (keyboardCode1 == this._KEYBOARD_CODES._KEYBOARD_CODE_END) { this._handleKeyupEnd(event); } else if (keyboardCode1 == this._KEYBOARD_CODES._KEYBOARD_CODE_ESC) { this._handleKeyupEsc(event); } else if (keyboardCode1 == this._KEYBOARD_CODES._KEYBOARD_CODE_F2) { this._handleKeyupF2(event); } this._removeKeyboardKey(keyboardCode1); } // remove the keycode from our internal list of pressed keys. this._removeKeyboardKey(event.keyCode); }, /** * Keep track of mousedown/mouseup for multiple selection */ 'mousedown .oj-table-body': function(event) { // get the row index if the mousedown was on a row this._mouseDownRowIdx = this._getTableDomUtils().getElementRowIdx($(event.target)); if (this._mouseDownRowIdx == null) { return; } var tableBodyRow = this._getTableDomUtils().getTableBodyRow(this._mouseDownRowIdx); if (tableBodyRow != null && tableBodyRow.prop('draggable')) { // do not do row selection if we are dragging this._mouseDownRowIdx = null; return; } // Only clear if Shift or Ctrl are not pressed since this // could be multiple selection if (this._mouseDownRowIdx != null && !event[this._KEYBOARD_CODES._KEYBOARD_MODIFIER_SHIFT] && !oj.DomUtils.isMetaKeyPressed(event)) { var rowSelected = this._getRowSelection(this._mouseDownRowIdx); // check if the row which we clicked on is already selected // if it is and it's the only selected row, then don't clear if (rowSelected && this._getSelectedRowIdxs().length == 1) { return; } // only clear if non-contiguous selection is not enabled for touch if (!this._nonContiguousSelection) { this._clearSelectedRows(); } } }, /** * Keep track of mousedown/mouseup for multiple selection */ 'mouseup .oj-table-body': function(event) { this._mouseDownRowIdx = null; }, /** * show the row hover when the mouse enters a table row */ 'mouseenter .oj-table-body-row': function(event) { $(event.currentTarget).addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._HOVER); this._handleMouseEnterSelection(event.target); }, /** * hide the row hover when the mouse leaves a table row */ 'mouseleave .oj-table-body-row': function(event) { $(event.currentTarget).removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._HOVER); }, /** * set the column header focus. */ 'mousedown .oj-table-column-header-cell': function(event) { // get the column index var columnIdx = this._getTableDomUtils().getElementColumnIdx($(event.currentTarget)); // set the column focus this._setHeaderColumnFocus(columnIdx, true, true, event); $(event.target).data(this._FOCUS_CALLED, true); }, /** * show the ascending/descending links when the mouse * enters a column header */ 'mouseenter .oj-table-column-header-cell': function(event) { $(event.currentTarget).addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._HOVER); // get the column index of the header element var columnIdx = this._getTableDomUtils().getElementColumnIdx($(event.currentTarget)); // show the asc/dsc links for the header this._showTableHeaderColumnSortLink(columnIdx); }, /** * hide the ascending/descending links when the mouse * leaves a column header */ 'mouseleave .oj-table-column-header-cell': function(event) { $(event.currentTarget).removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._HOVER); // get the column index of the header element var columnIdx = this._getTableDomUtils().getElementColumnIdx($(event.currentTarget)); // hide the asc/dsc links for the header this._hideTableHeaderColumnSortLink(columnIdx, true); this._hideTableHeaderColumnSortLink(columnIdx, false); }, /** * set the row focus when the mouse clicks on a cell. */ 'mousedown .oj-table-data-cell': function(event) { // get the row index of the cell element var rowIdx = this._getTableDomUtils().getElementRowIdx($(event.currentTarget)); var focused = false; // set the row focus focused = this._setRowFocus(rowIdx, true, true, event.currentTarget, event); $(event.target).data(this._FOCUS_CALLED, true); if (!focused) { return; } }, /** * show the cell hover when the mouse enters a table cell */ 'mouseenter .oj-table-data-cell': function(event) { $(event.currentTarget).addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._HOVER); }, /** * hide the cell hover when the mouse leaves a table cell */ 'mouseleave .oj-table-data-cell': function(event) { $(event.currentTarget).removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._HOVER); }, /** * invoke a sort on the column data when the mouse clicks the ascending link */ 'click .oj-table-column-header-asc-link': function(event) { var columnIdx = this._getTableDomUtils().getElementColumnIdx($(event.target)); var tableHeaderColumn = this._getTableDomUtils().getTableHeaderColumn(columnIdx); if (!tableHeaderColumn) { return; } // check if the column is currently sorted var sorted = tableHeaderColumn.data('sorted'); if (sorted == this._COLUMN_SORT_ORDER._ASCENDING) { this._handleSortTableHeaderColumn(columnIdx, false, event); } else { this._handleSortTableHeaderColumn(columnIdx, true, event); } event.preventDefault(); event.stopPropagation(); }, 'click .oj-table-column-header-acc-asc-link': function(event) { if (this._getKeyboardKeys().length > 0) { var keyboardCode1 = this._getKeyboardKeys()[0]; if (keyboardCode1 == this._KEYBOARD_CODES._KEYBOARD_CODE_ENTER) { // An Enter key press can cause a click event event.preventDefault(); event.stopPropagation(); return; } } var columnIdx = this._getTableDomUtils().getElementColumnIdx($(event.target)); var tableHeaderColumn = this._getTableDomUtils().getTableHeaderColumn(columnIdx); if (!tableHeaderColumn) { return; } var sorted = tableHeaderColumn.data('sorted'); if (sorted == this._COLUMN_SORT_ORDER._DESCENDING) { this._handleSortTableHeaderColumn(columnIdx, true, event); } else { this._handleSortTableHeaderColumn(columnIdx, false, event); } event.preventDefault(); event.stopPropagation(); }, /** * invoke a sort on the column data when the mouse clicks the descending link */ 'click .oj-table-column-header-dsc-link': function(event) { var columnIdx = this._getTableDomUtils().getElementColumnIdx($(event.target)); var tableHeaderColumn = this._getTableDomUtils().getTableHeaderColumn(columnIdx); if (!tableHeaderColumn) { return; } // check if the column is currently sorted var sorted = tableHeaderColumn.data('sorted'); if (sorted == this._COLUMN_SORT_ORDER._DESCENDING) { this._handleSortTableHeaderColumn(columnIdx, true, event); } else { this._handleSortTableHeaderColumn(columnIdx, false, event); } event.preventDefault(); event.stopPropagation(); }, 'click .oj-table-column-header-acc-dsc-link': function(event) { if (this._getKeyboardKeys().length > 0) { var keyboardCode1 = this._getKeyboardKeys()[0]; if (keyboardCode1 == this._KEYBOARD_CODES._KEYBOARD_CODE_ENTER) { // An Enter key press can cause a click event event.preventDefault(); event.stopPropagation(); return; } } var columnIdx = this._getTableDomUtils().getElementColumnIdx($(event.target)); var tableHeaderColumn = this._getTableDomUtils().getTableHeaderColumn(columnIdx); if (!tableHeaderColumn) { return; } var sorted = tableHeaderColumn.data('sorted'); if (sorted == this._COLUMN_SORT_ORDER._DESCENDING) { this._handleSortTableHeaderColumn(columnIdx, true, event); } else { this._handleSortTableHeaderColumn(columnIdx, false, event); } event.preventDefault(); event.stopPropagation(); }, /** * set the row focus or selection when the mouse clicks on a cell. * Ctrl + click results in selection and focus. Plain click results in focus. * Plain click on a selected row removes the selection. */ 'click .oj-table-data-cell': function(event) { // get the row index of the cell element var rowIdx = this._getTableDomUtils().getElementRowIdx($(event.currentTarget)); var focusCalled = $(event.target).data(this._FOCUS_CALLED); if (!focusCalled) { var focused = this._setRowFocus(rowIdx, true, true, event.currentTarget, event); $(event.target).data(this._FOCUS_CALLED, false); if (!focused) { return; } } // check if we are selecting if (event[this._KEYBOARD_CODES._KEYBOARD_MODIFIER_SHIFT]) { var lastSelectedRowIdx = this._getLastRowSelection(); if (lastSelectedRowIdx != null) { // remove the selection highlight window.getSelection().removeAllRanges() // shift selection is always from the last selected row if (rowIdx < lastSelectedRowIdx) { var i; for (i = rowIdx; i <= lastSelectedRowIdx; i++) { this._setRowSelection(i, true, event.currentTarget, event, true); } } else { var i; for (i = lastSelectedRowIdx; i <= rowIdx; i++) this._setRowSelection(i, true, event.currentTarget, event, true); } } } else if (oj.DomUtils.isMetaKeyPressed(event)) { this._setRowSelection(rowIdx, !this._getRowSelection(rowIdx), event.currentTarget, event, true); } else if (this._getKeyboardKeys().length == 0) { var rowSelected = this._getRowSelection(rowIdx); this._setRowSelection(rowIdx, !rowSelected, event.currentTarget, event, true); if (this._isTouchDevice() && this._getRowSelectionMode() == this._OPTION_SELECTION_MODES._MULTIPLE && !rowSelected) { this._getTableDomUtils().createTableBodyRowTouchSelectionAffordance(rowIdx); } } }, /** * Set row to editable. */ 'dblclick .oj-table-data-cell': function(event) { var columnIdx = this._getTableDomUtils().getElementColumnIdx($(event.target)); this._setTableEditable(true, false, columnIdx, true, event); }, /** * set current row when the mouse right clicks on a cell. */ 'contextmenu .oj-table-data-cell': function(event) { // get the row index of the cell element var rowIdx = this._getTableDomUtils().getElementRowIdx($(event.currentTarget)); var rowKey = this._getRowKeyForRowIdx(rowIdx); this._setCurrentRow({'rowKey': rowKey}, event, false); }, /** * set the column header selection and focus. Plain click results in * focus and selection. If Ctrl is not pressed then we have single column selection. */ 'click .oj-table-column-header-cell': function(event) { // get the column index var columnIdx = this._getTableDomUtils().getElementColumnIdx($(event.currentTarget)); // check if we need to focus var focusCalled = $(event.target).data(this._FOCUS_CALLED); if (!focusCalled) { // set the column focus this._setHeaderColumnFocus(columnIdx, true, true, event); $(event.target).data(this._FOCUS_CALLED, false); } // check if we are selecting if (event[this._KEYBOARD_CODES._KEYBOARD_MODIFIER_SHIFT]) { var lastSelectedColumnIdx = this._getLastHeaderColumnSelection(); if (lastSelectedColumnIdx != null) { // shift selection is always from the last selected column if (columnIdx < lastSelectedColumnIdx) { var i; for (i = columnIdx; i <= lastSelectedColumnIdx; i++) { this._setHeaderColumnSelection(i, true, event.currentTarget, event, true); } } else { var i; for (i = lastSelectedColumnIdx; i <= columnIdx; i++) this._setHeaderColumnSelection(i, true, event.currentTarget, event, true); } } } else if (oj.DomUtils.isMetaKeyPressed(event)) { this._setHeaderColumnSelection(columnIdx, !this._getHeaderColumnSelection(columnIdx), event.currentTarget, event, true); } else if (this._getKeyboardKeys().length == 0) { this._clearSelectedHeaderColumns(); this._setHeaderColumnSelection(columnIdx, !this._getHeaderColumnSelection(columnIdx), event.currentTarget, event, true); this._getTableDndContext().setTableHeaderColumnDraggable(columnIdx, true); } }, /** * Set dragstart handler for column DnD. */ 'dragstart .oj-table-column-header-cell': function(event) { return this._getTableDndContext().handleColumnDragStart(event); }, /** * Set dragenter handler for column DnD. */ 'dragenter .oj-table-column-header-cell': function(event) { return this._getTableDndContext().handleColumnDragEnter(event); }, /** * Set dragover handler for column DnD. */ 'dragover .oj-table-column-header-cell': function(event) { return this._getTableDndContext().handleColumnDragOver(event); }, /** * Set dragleave handler for column DnD. */ 'dragleave .oj-table-column-header-cell': function(event) { return this._getTableDndContext().handleColumnDragLeave(event); }, /** * Set drop handler for column DnD. */ 'drop .oj-table-column-header-cell': function(event) { return this._getTableDndContext().handleColumnDrop(event); }, /** * Set dragend handler for column DnD. */ 'dragend .oj-table-column-header-cell': function(event) { return this._getTableDndContext().handleColumnDragEnd(event); }, /** * handle the dragstart event on rows and invoke event callback. */ 'dragstart .oj-table-body-row': function(event) { return this._getTableDndContext().handleRowDragStart(event); }, /** * handle the drag event on rows and invoke event callback. */ 'drag .oj-table-body-row': function(event) { return this._getTableDndContext().handleRowDrag(event); }, /** * handle the dragend event on rows and invoke event callback. */ 'dragend .oj-table-body-row': function(event) { return this._getTableDndContext().handleRowDragEnd(event); }, /** * handle the dragenter event and invoke event callback. */ 'dragenter .oj-table-body': function(event) { return this._getTableDndContext().handleRowDragEnter(event); }, /** * handle the dragover event and invoke event callback. */ 'dragover .oj-table-body': function(event) { return this._getTableDndContext().handleRowDragOver(event); }, /** * handle the dragleave event and invoke event callback. */ 'dragleave .oj-table-body': function(event) { return this._getTableDndContext().handleRowDragLeave(event); }, /** * handle the drop event and invoke event callback. */ 'drop .oj-table-body': function(event) { return this._getTableDndContext().handleRowDrop(event); } }, /** * @override * @private */ _eventsContainer: { /** * Keep track of touchstart on selection affordance */ 'touchstart': function(event) { var fingerCount = event.originalEvent.touches.length; if (fingerCount == 1 && this._getRowSelectionMode() == this._OPTION_SELECTION_MODES._MULTIPLE) { if ($(event.target).hasClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_TOUCH_SELECTIOM_AFFORDANCE_TOP_CLASS) || $(event.target).hasClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_TOUCH_SELECTIOM_AFFORDANCE_TOP_ICON_CLASS)) { event.preventDefault(); this._mouseDownRowIdx = this._getTableDomUtils().getTableBodyRowTouchSelectionAffordanceBottom().data('rowIdx'); } else if ($(event.target).hasClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_TOUCH_SELECTIOM_AFFORDANCE_BOTTOM_CLASS) || $(event.target).hasClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_TOUCH_SELECTIOM_AFFORDANCE_BOTTOM_ICON_CLASS)) { event.preventDefault(); this._mouseDownRowIdx = this._getTableDomUtils().getTableBodyRowTouchSelectionAffordanceTop().data('rowIdx'); } } }, /** * Keep track of touchmove for multiple selection */ 'touchmove': function(event) { if (this._mouseDownRowIdx != null) { event.preventDefault(); var eventTarget = this._getTouchEventTargetElement(event); this._handleMouseEnterSelection(eventTarget); } }, /** * Keep track of touchend for multiple selection */ 'touchend': function(event) { if (this._mouseDownRowIdx != null) { var eventTarget = this._getTouchEventTargetElement(event); this._handleMouseEnterSelection(eventTarget); } this._mouseDownRowIdx = null; }, /** * Keep track of touchend for edit */ 'touchend .oj-table-body': function(event) { var eventTarget = $(event.target); if (this._lastTapTime != null && ((new Date()).getTime() - this._lastTapTime) < 250 && this._lastTapTarget[0] == eventTarget[0]) { this._lastTapTime = null; this._lastTapTarget = null; var columnIdx = this._getTableDomUtils().getElementColumnIdx($(eventTarget)); this._setTableEditable(true, false, columnIdx, true, event); event.preventDefault(); } else { this._lastTapTarget = eventTarget; this._lastTapTime = (new Date()).getTime(); } }, /** * Keep track of touchcancel for multiple selection */ 'touchcancel': function(event) { this._mouseDownRowIdx = null; } }, /** * @private */ _refresh: function() { var startIndex = null; var initFetch = false; if (this._data != this.options[this._CONST_DATA]) { this._clearCachedDataMetadata(); if (this._data == null) { // need to do an initial fetch initFetch = true } else { startIndex = 0; } if (this._isLoadMoreOnScroll()) { this._registerDomScroller(); } } if (this._contextMenuId != this._getTableDomUtils().getContextMenuId()) { this._getTableDomUtils().createContextMenu(this._handleContextMenuSelect.bind(this)); } this._getTableDomUtils().clearCachedDom(); this._getTableDomUtils().refreshContextMenu(); this._refreshTableStatusMessage(); if (initFetch) { return this._initFetch(); } else { var self = this; this._queueTask(function() { var result = self._invokeDataFetchRows(startIndex); startIndex = null; self = null; return result; }); } }, /** * @override * @private */ _setOption: function(key, value) { this._superApply(arguments); var shouldRefresh = this._isTableRefreshNeeded(key, value); if (shouldRefresh) { if (key == 'columns') { this._clearCachedMetadata(); } else if (key == 'scrollPolicy' || key == 'scrollPolicyOptions') { if (this._isLoadMoreOnScroll()) { this._registerDomScroller(); } } this._refresh(); } else { if (key == 'selection') { this._clearSelectedRows(); this._clearSelectedHeaderColumns(); this._setSelection(value); } else if (key == 'currentRow') { this._setCurrentRow(value, null, true); } } }, /**** end internal widget functions ****/ /**** start internal functions ****/ /** * Add a keyCode to internally track pressed keys. keyCodes should be added on * mouse down and then later removed on mouse up. * @param {number} keyCode KeyCode of the keyboard key. * @private */ _addKeyboardKey: function(keyCode) { var foundCode = false; for (var prop in this._KEYBOARD_CODES) { if (this._KEYBOARD_CODES.hasOwnProperty(prop)) { if (this._KEYBOARD_CODES[prop] == keyCode) { foundCode = true; } } } if (!foundCode) { // only add keys we are interested in return; } var keyboardKeys = this._getKeyboardKeys(); var found = false; var i, keyboardKeysCount = keyboardKeys.length; for (i = 0; i < keyboardKeysCount; i++) { if (keyboardKeys[i] == keyCode) { found = true; break; } } if (!found) { keyboardKeys.push(keyCode); } }, /** * Called by component to add a busy state and return the resolve function * to call when the busy state can be removed. * @private */ _addComponentBusyState: function(msg) { var busyContext = oj.Context.getContext(this.element[0]).getBusyContext(); var options = {'description' : "The component identified by '" + this._getTableDomUtils().getTableId() + "' " + msg}; return busyContext.addBusyState(options); }, /** * Add a new tr and refresh the DOM at the row index and refresh the table * dimensions to accomodate the new row * @param {number} rowIdx row index relative to the start of the table * @param {Object} row row * @param {Object} docFrag document fragment * @param {number} docFragStartIdx document fragment row start index * * @private */ _addSingleTableBodyRow: function(rowIdx, row, docFrag, docFragStartIdx) { var tableBodyRow = this._getTableDomUtils().createTableBodyRow(rowIdx, row[this._CONST_KEY]); this._getTableDomUtils().styleTableBodyRow(tableBodyRow, true); // insert the <tr> element in to the table body DOM this._getTableDomUtils().insertTableBodyRow(rowIdx, tableBodyRow, row, docFrag); this._refreshTableBodyRow(rowIdx, row, tableBodyRow, docFrag, docFragStartIdx, true); }, /** * Check and set the row or header column focus * @private */ _checkRowOrHeaderColumnFocus: function(event) { var focusedRowIdx = this._getFocusedRowIdx(); var focusedHeaderColumnIdx = this._getFocusedHeaderColumnIdx(); if (focusedRowIdx == null && focusedHeaderColumnIdx == null) { var focusRowIdx = null; var currentRow = this._getCurrentRow(); var currentRowKey = currentRow != null ? currentRow['rowKey'] : null; if (currentRowKey != null) { focusRowIdx = this._getRowIdxForRowKey(currentRowKey); } // if no row or column is focused // and currentRow is null then set the focus on the first column or row if (focusRowIdx == null) { if (this._isTableHeaderless()) { this._setRowFocus(0, true, true, null, event); } else { this._setHeaderColumnFocus(0, true, false, event); } } else { this._setRowFocus(focusRowIdx, true, true, null, event); } } }, /** * Clear any cached metadata * @private */ _clearCachedMetadata: function() { this._columnDefArray = null; this._setTableActionableMode(false); }, /** * Clear any cached data metadata * @private */ _clearCachedDataMetadata: function() { if (this._data != null) { this._unregisterDataSourceEventListeners(); } this._data = null; }, /** * Clear waiting state and hide the Fetching Data... status message. * @private */ _clearDataWaitingState: function() { this._hideInlineMessage(); this._hideStatusMessage(); this._dataFetching = false; if (this._dataResolveFunc) { this._dataResolveFunc(); this._dataResolveFunc = null; } }, /** * Clear any keyboard keys * @private */ _clearKeyboardKeys: function() { this._keyboardKeys = []; }, /** * Clear the focused column header * @private */ _clearFocusedHeaderColumn: function() { var focusedHeaderColumnIdx = this._getFocusedHeaderColumnIdx(); if (focusedHeaderColumnIdx != null) { this._setHeaderColumnFocus(focusedHeaderColumnIdx, false, false, null); } this._activeColumnIndex = -1; }, /** * Clear the focused row * @param {boolean} updateCurrentRow whether to update the currentRow * @private */ _clearFocusedRow: function(updateCurrentRow) { var focusedRowIdx = this._getFocusedRowIdx(); if (focusedRowIdx != null) { this._setRowFocus(-1, true, updateCurrentRow, null, null); } }, /** * Clear the selected column headers * @private */ _clearSelectedHeaderColumns: function() { var selectedHeaderColumnIdxs = this._getSelectedHeaderColumnIdxs(); var i, selectedHeaderColumnIdxsCount = selectedHeaderColumnIdxs.length; for (i = 0; i < selectedHeaderColumnIdxsCount; i++) { this._setHeaderColumnSelection(selectedHeaderColumnIdxs[i], false, null, null, false); } }, /** * Clear the selected rows * @private */ _clearSelectedRows: function() { var selectedRowIdxs = this._getSelectedRowIdxs(); var i, selectedRowIdxsCount = selectedRowIdxs.length; for (i = 0; i < selectedRowIdxsCount; i++) { this._setRowSelection(selectedRowIdxs[i], false, null, null, false); } if (this._isTouchDevice() && this._getRowSelectionMode() == this._OPTION_SELECTION_MODES._MULTIPLE) { this._getTableDomUtils().removeTableBodyRowTouchSelectionAffordance(); } }, /** * Clear the sorted column header indicator. Note this does not affect the order * of the data. This is just to clear the UI indication. * @param {number} columnIdx column index * @private */ _clearSortedHeaderColumn: function(columnIdx) { var sortedTableHeaderColumnIdx = this._getSortedTableHeaderColumnIdx(); if (sortedTableHeaderColumnIdx != null) { var sortedTableHeaderColumn = this._getTableDomUtils().getTableHeaderColumn(sortedTableHeaderColumnIdx); var sorted = sortedTableHeaderColumn.data('sorted'); sortedTableHeaderColumn.data('sorted', null); if (sortedTableHeaderColumnIdx != columnIdx) { if (sorted == this._COLUMN_SORT_ORDER._ASCENDING) { this._hideTableHeaderColumnSortLink(sortedTableHeaderColumnIdx, true); } else { this._hideTableHeaderColumnSortLink(sortedTableHeaderColumnIdx, false); } } else { var sortedTableHeaderColumnAscLink = sortedTableHeaderColumn.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ASC_LINK_CLASS); sortedTableHeaderColumnAscLink.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._SELECTED); var sortedTableHeaderColumnDscLink = sortedTableHeaderColumn.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DSC_LINK_CLASS); sortedTableHeaderColumnDscLink.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._SELECTED); } } }, /** * Add all the rows contained in the input array. * @param {Array} rows Array of row contexts to add * @private */ _executeTableBodyRowsAdd: function(rows) { var self = this; this._queueTask(function() { // see if we should batch add // only batch if we are adding a block of contiguous rows var batchAdd = false; if (rows.length > 1) { var i, rowsCount = rows.length; var isContiguous = true; for (i = 0; i < rowsCount; i++) { if (i != 0) { if (rows[i - 1].rowIdx != rows[i].rowIdx - 1) { isContiguous = false; break; } } } if (isContiguous) { var tableBody = self._getTableDomUtils().getTableBody(); var tableBodyDocFrag = $(document.createDocumentFragment()); rowsCount = rows.length; for (i = 0; i < rowsCount; i++) { self._addSingleTableBodyRow(rows[i].rowIdx, rows[i].row, tableBodyDocFrag, rows[0].rowIdx); } if (rows[0].rowIdx == 0) { tableBody.prepend(tableBodyDocFrag); //@HTMLUpdateOK } else { var tableBodyRowBefore = self._getTableDomUtils().getTableBodyRow(rows[0].rowIdx); if (tableBodyRowBefore != null) { tableBody[0].insertBefore(tableBodyDocFrag[0], tableBodyRowBefore[0]);//@HTMLUpdateOK } else { tableBody[0].insertBefore(tableBodyDocFrag[0], null);//@HTMLUpdateOK } } self._getTableDomUtils().clearCachedDomRowData(); oj.Components.subtreeAttached(tableBody[0]); batchAdd = true; } } if (!batchAdd) { rowsCount = rows.length; for (i = 0; i < rowsCount; i++) { self._addSingleTableBodyRow(rows[i].rowIdx, rows[i].row); } } self._getTableDomUtils().clearCachedDomRowData(); // row values may have changed so refresh the footer self._refreshTableFooter(); self = null; }); }, /** * Change all the rows contained in the input array. * @param {Array} rows Array of row contexts to change * @param {number} startIndex index of first row in the table in the data source * @private */ _executeTableBodyRowsChange: function(rows, startIndex) { var self = this; this._queueTask(function() { var i, rowsCount = rows.length; for (i = 0; i < rowsCount; i++) { self._refreshTableBodyRow(rows[i].rowIdx, rows[i].row); } // row values may have changed so refresh the footer self._refreshTableFooter(); self = null; }); }, /** * Change all the rows contained in the input array. * @param {Array} rows Array of row contexts to change * @private */ _executeTableBodyRowsRemove: function(rows) { var self = this; var currentRow = this._getCurrentRow(); var currentRowKey = currentRow != null ? currentRow['rowKey'] : null; this._queueTask(function() { // first check if we are removing all rows. If so, we can do a removeAll var rowIdxArray = []; var i, j, rowKey, rowsCount = rows.length; var removeAll = false; var tableBodyRows = self._getTableDomUtils().getTableBodyRows(); if (tableBodyRows != null && tableBodyRows.length > 0) { for (i = 0; i < tableBodyRows.length; i++) { rowIdxArray.push(i); } for (i = 0; i < rowsCount; i++) { for (j = 0; j < rowIdxArray.length; j++) { if (rowIdxArray[j] == rows[i].rowIdx) { rowIdxArray.splice(j, 1); break; } } } if (rowIdxArray.length == 0) { removeAll = true; } } var tableBody = this._getTableDomUtils().getTableBody(); var checkFocus = $.contains(tableBody[0], document.activeElement); var tableBodyRow, resetFocus = false; if (removeAll) { if (checkFocus) { resetFocus = true; } self._getTableDomUtils().removeAllTableBodyRows(); // Clear out all the existing selection state self._setSelection(null); self.option('selection', null, {'_context': {writeback: true, internalSet: true}}); } else { for (i = 0; i < rowsCount; i++) { if (checkFocus) { tableBodyRow = this._getTableDomUtils().getTableBodyRow(rows[i].rowIdx); if (tableBodyRow != null && $.contains(tableBodyRow[0], document.activeElement)) { resetFocus = true; checkFocus = false; } } self._getTableDomUtils().removeTableBodyRow(rows[i].rowIdx); } } // reset the currentRow if needed if (currentRowKey != null) { for (i = 0; i < rowsCount; i++) { rowKey = rows[i].row[self._CONST_KEY]; if (oj.Object.compareValues(rowKey, currentRowKey)) { self._setCurrentRow(null, null, false); break; } } } // row values may have changed so refresh the footer self._refreshTableFooter(); tableBodyRows = self._getTableDomUtils().getTableBodyRows(); if (tableBodyRows == null || tableBodyRows.length == 0) { self._showNoDataMessage(); } if (resetFocus) { this._getTableDomUtils().getTable().focus(); } self = null; }); }, /** * Return the column definitions * @return {Array} array of column metadata Objects. * @private */ _getColumnDefs: function() { // cache the columns array in this._columnDefArray if (!this._columnDefArray) { this._columnDefArray = this._getColumnMetadata(); } return this._columnDefArray; }, /** * Return the column metadata in sorted oder. * @return {Array} array of column metadata Objects. * @private */ _getColumnMetadata: function() { // get the columns metadata var columns = this.options['columns']; var columnsDefault = this.options['columnsDefault']; if ((columns.length == 0 || (columns.length == 1 && columns[0].id == null && columns[0].headerText == null && columns[0].field == null)) && (columnsDefault.headerText == null && columnsDefault.field == null)) { return []; } var defaultedColumns = []; var i, columnsCount = columns.length; for (i = 0; i < columnsCount; i++) { defaultedColumns[i] = $.extend({}, columnsDefault, columns[i]); } var columnsSortedArray = []; // add the rest of the columns in the array var defaultedColumnsCount = defaultedColumns.length; for (i = 0; i < defaultedColumnsCount; i++) { columnsSortedArray.push(defaultedColumns[i]); } var data = this._getData(); var sortSupportedData = false; if (data != null && data.getCapability('sort') == 'full') { sortSupportedData = true; } for (i = 0; i < defaultedColumnsCount; i++) { // generate ids for columns which don't have it specified if (columnsSortedArray[i][this._FIELD_ID] == null) { columnsSortedArray[i][this._FIELD_ID] = this._COLUMN_HEADER_ID_PREFIX + i; } // for the columns which have sortable = 'auto' check the datasource // and enable or disable if ((columnsSortedArray[i]['sortable'] == null || columnsSortedArray[i]['sortable'] == this._OPTION_AUTO) && sortSupportedData) { columnsSortedArray[i]['sortable'] = this._OPTION_ENABLED; } } return columnsSortedArray; }, /** * Return the column index for column key. * @param {Object} columnKey column key * @return {number|null} column index * @private */ _getColumnIdxForColumnKey: function(columnKey) { var columns = this._getColumnDefs(); if (columns != null) { var i, column, columnsCount = columns.length; for (i = 0; i < columnsCount; i++) { column = columns[i]; if (oj.Object.compareValues(column.id, columnKey)) { return i; } } } return null; }, /** * Return all the column indexes for elements with a particular style class * @param {string} styleClass style class * @return {Array} Array of column indexes * @private */ _getColumnIdxsForElementsWithStyleClass: function(styleClass) { var elements = this._getTableDomUtils().getTable().find(styleClass); var columnIdxs = []; if (elements && elements.length > 0) { var i, j, alreadyAdded, columnIdx, columnIdxsCount, elementsCount = elements.length; for (i = 0; i < elementsCount; i++) { columnIdx = this._getTableDomUtils().getElementColumnIdx($(elements.get(i))); alreadyAdded = false; columnIdxsCount = columnIdxs.length; for (j = 0; j < columnIdxsCount; j++) { if (columnIdxs[j] == columnIdx) { alreadyAdded = true; } } if (!alreadyAdded) { columnIdxs.push(columnIdx); } } } return columnIdxs; }, /** * Return the column key for column index. * @param {number} columnIdx column index * @return {Object} column key * @private */ _getColumnKeyForColumnIdx: function(columnIdx) { var columns = this._getColumnDefs(); if (columns != null && columnIdx < columns.length) { return columns[columnIdx][this._FIELD_ID]; } return null; }, /** * Return the column renderer * @param {number} columnIdx column index * @param {String} type renderer type * @return {Object} renderer * @private */ _getColumnRenderer: function(columnIdx, type) { var columns = this._getColumnDefs(); var column = columns[columnIdx]; if (type == 'cell') { return column['renderer']; } else if (type == 'footer') { return column['footerRenderer']; } else if (type == 'header') { return column['headerRenderer']; } return null; }, /** * Get the current row. * @return {Object|null} current row object or null if none. * @throws {Error} * @private */ _getCurrentRow: function() { var data = this._getData(); // if no data then bail if (!data) { return null; } return this._currentRow; }, /** * Return the datasource object defined for this table * @return {Object} Datasource object. * @throws {Error} * @private */ _getData: function() { if (!this._data && this.options.data != null) { var data = this.options.data; if (data instanceof oj.TableDataSource || data instanceof oj.PagingTableDataSource) { if (this._isLoadMoreOnScroll() && !(data instanceof oj.PagingTableDataSource)) { // if loadMoreOnScroll then we need to use a PagingTableDataSource this._data = new oj.PagingTableDataSource(data, null); } else { this._data = data; } } else { // we only support TableDataSource var errSummary = this._LOGGER_MSG._ERR_DATA_INVALID_TYPE_SUMMARY; var errDetail = this._LOGGER_MSG._ERR_DATA_INVALID_TYPE_DETAIL; throw new Error(errSummary + '\n' + errDetail); } this._dataMetadata = this.options.data; this._registerDataSourceEventListeners(); } return this._data; }, /** * Get the focused column header index * @return {number|null} the column index * @private */ _getFocusedHeaderColumnIdx: function() { // focused column headers have the focused style class. There should only be one focused header return this._getColumnIdxsForElementsWithStyleClass('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_CELL_CLASS + '.' + oj.TableDomUtils.MARKER_STYLE_CLASSES._FOCUS)[0]; }, /** * Get the focused row index * @return {number|null} the row index * @private */ _getFocusedRowIdx: function() { // focused rows have cells with focused style class. There should only be one focused row return this._getRowIdxsForElementsWithStyleClass('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_CLASS + '.' + oj.TableDomUtils.MARKER_STYLE_CLASSES._FOCUS)[0]; }, /** * Return whether the column header at the index is focused * @param {number} columnIdx column index * @return {boolean} whether it's focused * @private */ _getHeaderColumnFocus: function(columnIdx) { return this._getHeaderColumnState(columnIdx).focused; }, /** * Return whether the column header at the index is selected * @param {number} columnIdx column index * @return {boolean} whether it's selected * @private */ _getHeaderColumnSelection: function(columnIdx) { return this._getHeaderColumnState(columnIdx).selected; }, /** * Return the column selection mode * @return {string|null} single, multiple, or null * @private */ _getColumnSelectionMode: function() { var columnSelectionMode = this.options.selectionMode == null ? null : this.options.selectionMode[this._CONST_COLUMN]; return columnSelectionMode; }, /** * Return the state of the column header at a partiocular index * @param {number} columnIdx column index * @return {Object} Object which contains booleans focused and selected * @private */ _getHeaderColumnState: function(columnIdx) { var headerColumn = this._getTableDomUtils().getTableHeaderColumn(columnIdx); return {focused: headerColumn.hasClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._FOCUS), selected: headerColumn.hasClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._SELECTED)}; }, /** * Return the currently pressed keyboard keys * @return {Array} Array of keyCodes * @private */ _getKeyboardKeys: function() { if (!this._keyboardKeys) { this._keyboardKeys = []; } // reverse the array since we want the keybaord keys to be a LIFO stack return this._keyboardKeys.reverse(); }, /** * Return the last column which was selected (chronologically) * @return {number|null} last selected column * @private */ _getLastHeaderColumnSelection: function() { if (this._lastSelectedColumnIdxArray != null && this._lastSelectedColumnIdxArray.length > 0) { return this._lastSelectedColumnIdxArray[0]; } return null; }, /** * Return the last row which was selected (chronologically) * @return {number|null} last selected row * @private */ _getLastRowSelection: function() { if (this._lastSelectedRowIdxArray != null && this._lastSelectedRowIdxArray.length > 0) { return this._lastSelectedRowIdxArray[0]; } return null; }, /** * Return an array with row and row indices relative to the table row indices * @param {Object} resultObject Object containing data array, key array, and index array * @param {number} startIndex start index * @return {Array} Array of rows and row index * @private */ _getRowIdxRowArray: function(resultObject, startIndex) { var rowIdxRowArray = []; if (resultObject != null) { var i, indexesCount = resultObject[this._CONST_INDEXES].length; for (i = 0; i < indexesCount; i++) { rowIdxRowArray.push({row: {'data': resultObject[this._CONST_DATA][i], 'metadata': resultObject[this._CONST_METADATA] ? resultObject[this._CONST_METADATA][i] : null, 'key': resultObject[this._CONST_KEYS][i], 'index': resultObject[this._CONST_INDEXES][i]}, rowIdx: startIndex + i}); } } return rowIdxRowArray; }, /** * Return the row index for row key. Only loop through displayed rows. * @param {Object} rowKey row key * @return {number|null} row index * @private */ _getRowIdxForRowKey: function(rowKey) { var tableBodyRows = this._getTableDomUtils().getTableBodyRows(); if (tableBodyRows != null && tableBodyRows.length > 0) { var i, tableBodyRowsCount = tableBodyRows.length; for (i = 0; i < tableBodyRowsCount; i++) { if (oj.Object.compareValues($(tableBodyRows[i]).data('rowKey'), rowKey)) { return i; } } } return null; }, /** * Return the datasource's row index for the row key. * @param {Object} rowKey row key * @return {number|null} row index * @private */ _getDataSourceRowIndexForRowKey: function(rowKey) { var tableBodyRows = this._getTableDomUtils().getTableBodyRows(); if (tableBodyRows != null && tableBodyRows.length > 0) { var i, tableBodyRowsCount = tableBodyRows.length;; for (i = 0; i < tableBodyRowsCount; i++) { if (oj.Object.compareValues($(tableBodyRows[i]).data('rowKey'), rowKey)) { var data = this._getData(); var startIndex = 0; if (data instanceof oj.PagingTableDataSource) { startIndex = data.getStartItemIndex(); } return i + startIndex; } } } return null; }, /** * Return the editable row index if there is one * @return {number|null} row index * @private */ _getEditableRowIdx: function() { var rowIdx = null; if (this._getEditableRowKey() != null) { rowIdx = this._getRowIdxForRowKey(this._getEditableRowKey()); if (rowIdx !== null) { return rowIdx; } } return this._editableRowIdx; }, /** * Return the editable row key if there is one * @return {Object|null} row key * @private */ _getEditableRowKey: function() { return this._editableRowKey; }, /** * Return all the row indexes for elements with a particular style class * @param {string} styleClass style class * @return {Array} Array of row indexes * @private */ _getRowIdxsForElementsWithStyleClass: function(styleClass) { var elements = this._getTableDomUtils().getTable().find(styleClass); var rowIdxs = []; if (elements && elements.length > 0) { var i, j, rowIdx, rowIdxsCount, alreadyAdded, elementsCount = elements.length; for (i = 0; i < elementsCount; i++) { rowIdx = this._getTableDomUtils().getElementRowIdx($(elements.get(i))); alreadyAdded = false; rowIdxsCount = rowIdxs.length; for (j = 0; j < rowIdxsCount; j++) { if (rowIdxs[j] == rowIdx) { alreadyAdded = true; } } if (!alreadyAdded) { rowIdxs.push(rowIdx); } } } return rowIdxs; }, /** * Return the row key for datasource's row index. * @param {number} rowIndex row index * @return {*} row key * @private */ _getRowKeyForDataSourceRowIndex: function(rowIndex) { var tableBodyRows = this._getTableDomUtils().getTableBodyRows(); if (tableBodyRows != null && tableBodyRows.length > 0) { var data = this._getData(); var startIndex = 0; if (data instanceof oj.PagingTableDataSource) { startIndex = data.getStartItemIndex(); } var i, tableBodyRowsCount = tableBodyRows.length; for (i = 0; i < tableBodyRowsCount; i++) { if (startIndex + i == rowIndex) { return $(tableBodyRows[i]).data('rowKey'); } } } return null; }, /** * Return the row key for row index. * @param {number} rowIdx row index * @return {Object|null} row key * @private */ _getRowKeyForRowIdx: function(rowIdx) { var tableBodyRow = this._getTableDomUtils().getTableBodyRow(rowIdx); if (tableBodyRow != null) { return tableBodyRow.data('rowKey'); } return null; }, /** * Return the row renderer * @return {Object} renderer * @private */ _getRowRenderer: function() { return this.options['rowRenderer']; }, /** * Return whether the row is selected * @param {number} rowIdx row index * @return {boolean} whether the row is selected * @private */ _getRowSelection: function(rowIdx) { return this._getTableDomUtils().getTableBodyRow(rowIdx).hasClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._SELECTED); }, /** * Return the row selection mode * @return {string|null} single, multiple, or null * @private */ _getRowSelectionMode: function() { var rowSelectionMode = this.options['selectionMode'] == null ? null : this.options['selectionMode'][this._CONST_ROW]; return rowSelectionMode; }, /** * Return the selected column header indexes * @return {Array} array of column header indexes * @private */ _getSelectedHeaderColumnIdxs: function() { // selected column headers have the selected css class return this._getColumnIdxsForElementsWithStyleClass('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_CELL_CLASS + '.' + oj.TableDomUtils.MARKER_STYLE_CLASSES._SELECTED); }, /** * Return the selected row indexes * @return {Array} array of row indexes * @private */ _getSelectedRowIdxs: function() { // selected rows have the selected css class return this._getRowIdxsForElementsWithStyleClass('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_CLASS + '.' + oj.TableDomUtils.MARKER_STYLE_CLASSES._SELECTED); }, /** * Gets the selection * @private */ _getSelection: function() { var selectedRowIdxs = this._getSelectedRowIdxs(); var selectedColumnIdxs = this._getSelectedHeaderColumnIdxs(); var selectionIdxs = null; var rowSelection = true; if (selectedRowIdxs != null && selectedRowIdxs.length > 0) { selectionIdxs = selectedRowIdxs; } else if (selectedColumnIdxs != null && selectedColumnIdxs.length > 0) { selectionIdxs = selectedColumnIdxs; rowSelection = false; } else { return null; } var rangeArray = []; // first count the number of ranges we have by seeing how many // non-continguous selections we have var rangeCount = 0; var previousIdx = null; var rangeObj, selectionIndex, selectionIdx, selectionKey; var i, selectionIdxsCount = selectionIdxs.length; for (i = 0; i < selectionIdxsCount; i++) { selectionIdx = selectionIdxs[i]; if (i == 0) { rangeObj = {}; rangeObj[this._CONST_STARTINDEX] = {}; rangeObj[this._CONST_ENDINDEX] = {}; rangeObj['startKey'] = {}; rangeObj['endKey'] = {}; if (rowSelection) { selectionKey = this._getRowKeyForRowIdx(selectionIdx); selectionIndex = this._getDataSourceRowIndexForRowKey(selectionKey); rangeObj['startKey'][this._CONST_ROW] = selectionKey; rangeObj['endKey'][this._CONST_ROW] = selectionKey; rangeObj[this._CONST_STARTINDEX][this._CONST_ROW] = selectionIndex; rangeObj[this._CONST_ENDINDEX][this._CONST_ROW] = selectionIndex; } else { rangeObj[this._CONST_STARTINDEX][this._CONST_COLUMN] = selectionIdx; rangeObj[this._CONST_ENDINDEX][this._CONST_COLUMN] = selectionIdx; selectionKey = this._getColumnKeyForColumnIdx(selectionIdx); rangeObj['startKey'][this._CONST_COLUMN] = selectionKey; rangeObj['endKey'][this._CONST_COLUMN] = selectionKey; } rangeArray[0] = rangeObj; } else { rangeObj = rangeArray[rangeCount]; if (rowSelection) { selectionKey = this._getRowKeyForRowIdx(selectionIdx); selectionIndex = this._getDataSourceRowIndexForRowKey(selectionKey); rangeObj['endKey'][this._CONST_ROW] = selectionKey; rangeObj[this._CONST_ENDINDEX][this._CONST_ROW] = selectionIndex; } else { rangeObj[this._CONST_ENDINDEX][this._CONST_COLUMN] = selectionIdx; selectionKey = this._getColumnKeyForColumnIdx(selectionIdx); rangeObj['endKey'][this._CONST_COLUMN] = selectionKey; } if (selectionIdx != previousIdx + 1) { if (rowSelection) { selectionKey = this._getRowKeyForRowIdx(previousIdx); selectionIndex = this._getDataSourceRowIndexForRowKey(selectionKey); rangeObj['endKey'][this._CONST_ROW] = selectionKey; rangeObj[this._CONST_ENDINDEX][this._CONST_ROW] = selectionIndex; rangeObj = {}; rangeObj[this._CONST_STARTINDEX] = {}; rangeObj[this._CONST_ENDINDEX] = {}; rangeObj['startKey'] = {}; rangeObj['endKey'] = {}; selectionKey = this._getRowKeyForRowIdx(selectionIdx); selectionIndex = this._getDataSourceRowIndexForRowKey(selectionKey); rangeObj['startKey'][this._CONST_ROW] = selectionKey; rangeObj['endKey'][this._CONST_ROW] = selectionKey; rangeObj[this._CONST_STARTINDEX][this._CONST_ROW] = selectionIndex; rangeObj[this._CONST_ENDINDEX][this._CONST_ROW] = selectionIndex; } else { rangeObj[this._CONST_ENDINDEX][this._CONST_COLUMN] = previousIdx; selectionKey = this._getColumnKeyForColumnIdx(previousIdx); rangeObj['endKey'][this._CONST_COLUMN] = selectionKey; rangeObj = {}; rangeObj[this._CONST_STARTINDEX] = {}; rangeObj[this._CONST_ENDINDEX] = {}; rangeObj['startKey'] = {}; rangeObj['endKey'] = {}; rangeObj[this._CONST_STARTINDEX][this._CONST_COLUMN] = selectionIdx; rangeObj[this._CONST_ENDINDEX][this._CONST_COLUMN] = selectionIdx; selectionKey = this._getColumnKeyForColumnIdx(selectionIdx); rangeObj['startKey'][this._CONST_COLUMN] = selectionKey; rangeObj['endKey'][this._CONST_COLUMN] = selectionKey; } rangeCount++; rangeArray[rangeCount] = rangeObj; } } previousIdx = selectionIdx; } return rangeArray; }, /** * Return the currnetly sorted column index * @return {number|null} column index * @private */ _getSortedTableHeaderColumnIdx: function() { var tableHeaderColumns = this._getTableDomUtils().getTableHeaderColumns(); var i, sorted, tableHeaderColumnsCount = tableHeaderColumns ? tableHeaderColumns.length : 0; for (i = 0; i < tableHeaderColumnsCount; i++) { // sorted column will have the sorted data attr sorted = $(tableHeaderColumns[i]).data('sorted'); if (sorted != null) { return i; } } return null; }, /** * Get tabbable elements within the element * @param {jQuery} element DOM element * @return {jQuery|null} jQuery array of DOM elements * @private */ _getTabbableElements: function(element) { var tabbableElements = element.find(':tabbable').not('.oj-helper-hidden-accessible'); if (tabbableElements != null && tabbableElements.length > 0) { return tabbableElements; } return null; }, /** * Return table DnD utils instance * @return {Object} instance of table DnD utils * @private */ _getTableDndContext: function() { if (!this._tableDndContext) { this._tableDndContext = new oj.TableDndContext(this); } return this._tableDndContext; }, /** * Return table DOM utils instance * @return {Object} instance of table DOM utils * @private */ _getTableDomUtils: function() { if (!this._tableDomUtils) { this._tableDomUtils = new oj.TableDomUtils(this); } return this._tableDomUtils; }, /** * Get the target element at the touch event * @param {Object} event DOM touch event * @return {jQuery} element DOM element * @private */ _getTouchEventTargetElement: function(event) { var eventLocation = event.originalEvent.changedTouches[0]; return $(document.elementFromPoint(eventLocation.clientX, eventLocation.clientY)); }, /** * Handle an ojselect event on a menu item, if sort call the handler on the core. * If resize prompt the user with a dialog box * @private */ _handleContextMenuSelect: function(event, ui) { var menuItemCommand = ui.item.attr('data-oj-command'); var headerColumn = this._getTableDomUtils().getFirstAncestor($(this._contextMenuEvent['target']), 'oj-table-column-header-cell'); var tableBodyCell = this._getTableDomUtils().getFirstAncestor($(this._contextMenuEvent['target']), 'oj-table-data-cell'); var columnIdx = null; if (headerColumn != null) { columnIdx = this._getTableDomUtils().getElementColumnIdx(headerColumn); } if (tableBodyCell != null) { columnIdx = this._getTableDomUtils().getElementColumnIdx(tableBodyCell); } if (columnIdx === null) { return; } if (menuItemCommand == 'oj-table-sortAsc') { this._handleSortTableHeaderColumn(columnIdx, true, event); } else if (menuItemCommand == 'oj-table-sortDsc') { this._handleSortTableHeaderColumn(columnIdx, false, event); } else if (menuItemCommand == 'oj-table-enableNonContiguousSelection') { this._nonContiguousSelection = true; // update to disable command ui.item.attr('data-oj-command', 'oj-table-disableNonContiguousSelection'); ui.item.children().first().text(this.getTranslatedString('labelDisableNonContiguousSelection')); //@HTMLUpdateOK } else if (menuItemCommand == 'oj-table-disableNonContiguousSelection') { this._nonContiguousSelection = false; // update to enable command ui.item.attr('data-oj-command', 'oj-table-enableNonContiguousSelection'); ui.item.children().first().text(this.getTranslatedString('labelEnableNonContiguousSelection')); //@HTMLUpdateOK } }, /** * Callback handler for data error. * @param {Object} error * @private */ _handleDataError: function(error) { this._clearDataWaitingState(); oj.Logger.error(error); }, /** * Callback handler for fetch start in the datasource. * @param {Object} event * @private */ _handleDataFetchStart: function(event) { this._setDataWaitingState(); }, /** * Callback handler for fetch completed in the datasource. Refresh entire * table body DOM and refresh the table dimensions if refresh == true. Hide the Fetching Data... * status message. * @param {Object} event * @private */ _handleDataFetchEnd: function(event) { try { var self = this; this._queueTask(function() { var data = self._getData(); if (data['sortCriteria'] != null) { var sortCriteriaKey = data['sortCriteria']['key']; var sortCriteriaDirection = data['sortCriteria']['direction']; if (sortCriteriaKey != null && sortCriteriaDirection != null) { // update the sort direction if the data is sorted self._refreshSortTableHeaderColumn(sortCriteriaKey, sortCriteriaDirection == self._COLUMN_SORT_ORDER._ASCENDING); } } var offset = 0; if (data instanceof oj.PagingTableDataSource) { // when paging, this contains the page start index. In loadMore // mode this is always zero. offset = data.getStartItemIndex(); } var indexArray = []; var i, eventDataCount = event[self._CONST_DATA].length; for (i = 0; i < eventDataCount; i++) { // event['startIndex'] contains the offset at which the data should be inserted in the table. In paging mode // this is always zero. In loadMore mode it contains an offset. // Therefore we have to add both. e.g. in paging mode offset is non-zero while in loadMore event['startIndex'] is non-zero. // The indexArray will contain the indexes as contained in the datasource. indexArray[i] = i + offset + event[self._CONST_STARTINDEX]; } self._refreshAll({'data': event[self._CONST_DATA], 'keys' : event[self._CONST_KEYS], 'indexes': indexArray}, event[self._CONST_STARTINDEX]); self = null; }); } catch (e) { oj.Logger.error(e); } finally { this._clearDataWaitingState(); } }, /** * Callback handler for refresh in the datasource. Refresh entire * table body DOM and refresh the table dimensions. * @param {Object} event * @private */ _handleDataRefresh: function (event) { try { var self = this; this._queueTask(function () { // first clear the table self._getTableDomUtils().removeAllTableBodyRows(); self._getTableDomUtils().clearCachedDomRowData(); var fetchPromise = self._invokeDataFetchRows(); self._setCurrentRow(null, null, false); self = null; return fetchPromise; }); } catch (e) { oj.Logger.error(e); } finally { this._clearDataWaitingState(); } }, /** * Callback handler for reset in the datasource. Do an initial fetch * @param {Object} event * @private */ _handleDataReset: function (event) { try { var self = this; this._queueTask(function() { // first clear the table self._getTableDomUtils().removeAllTableBodyRows(); self._getTableDomUtils().clearCachedDomRowData(); self._initFetch(); self._setCurrentRow(null, null, false); self = null; }); } catch (e) { oj.Logger.error(e); } finally { this._clearDataWaitingState(); } }, /** * Callback handler for rows added into the datasource. Add a new tr and refresh the DOM * at the row index and refresh the table dimensions to accomodate the new * row * @param {Object} event * @private */ _handleDataRowAdd: function(event) { try { var data = this._getData(); var eventData = event[this._CONST_DATA]; var eventIndexes = event[this._CONST_INDEXES]; var eventKeys = event[this._CONST_KEYS]; if (!(eventData instanceof Array)) { eventData = [eventData]; } var startIndex = 0; if (data instanceof oj.PagingTableDataSource) { startIndex = data.getStartItemIndex(); } var rowArray = []; var i, eventDataCount = eventData.length; for (i = 0; i < eventDataCount; i++) { var rowIdx = eventIndexes[i] - startIndex; if (rowIdx !== undefined) { var row = {'data': eventData[i], 'metadata': (data instanceof oj.FlattenedTreeTableDataSource) ? data._getMetadata(rowIdx) : null, 'key': eventKeys[i], 'index': eventIndexes[i]}; rowArray.push({row: row, rowIdx: rowIdx}); } } if (rowArray.length > 0) { this._executeTableBodyRowsAdd(rowArray); } } catch (e) { oj.Logger.error(e); } finally { this._clearDataWaitingState(); } }, /** * Callback handler for row change in the datasource. Refresh the changed * row. * @param {Object} event * @private */ _handleDataRowChange: function(event) { try { var data = this._getData(); var eventData = event[this._CONST_DATA]; var eventIndexes = event[this._CONST_INDEXES]; var eventKeys = event[this._CONST_KEYS]; if (!(eventData instanceof Array)) { eventData = [eventData]; } var startIndex = 0; if (data instanceof oj.PagingTableDataSource) { startIndex = data.getStartItemIndex(); } var rowArray = []; var i, eventDataCount = eventData.length; for (i = 0; i < eventDataCount; i++) { var rowIdx = eventIndexes[i] - startIndex; if (rowIdx !== undefined) { var row = {'data': eventData[i], 'key': eventKeys[i], 'index': eventIndexes[i]}; rowArray.push({row: row, rowIdx: rowIdx}); } } if (rowArray.length > 0) { this._executeTableBodyRowsChange(rowArray); } } catch (e) { oj.Logger.error(e); } finally { this._clearDataWaitingState(); } }, /** * Callback handler for row removed in the datasource. Remove the row DOM from the * table body by searching for the matching rowKey. New rows will have null rowKey. * After removing the row, refresh all the remaining row indexes since * they will have shifted. Lastly, refresh the table dimensions * @param {Object} event * @private */ _handleDataRowRemove: function(event) { try { var data = this._getData(); var eventData = event[this._CONST_DATA]; var eventIndexes = event[this._CONST_INDEXES]; var eventKeys = event[this._CONST_KEYS]; if (!(eventData instanceof Array)) { eventData = [eventData]; } var startIndex = 0; if (data instanceof oj.PagingTableDataSource) { startIndex = data.getStartItemIndex(); } var rowArray = []; var i, eventDataCount = eventData.length; for (i = eventDataCount - 1; i >= 0; i--) { var rowIdx = eventIndexes[i] - startIndex; if (rowIdx !== undefined) { var row = {'data': eventData[i], 'key': eventKeys[i], 'index': eventIndexes[i]}; rowArray.push({row: row, rowIdx: rowIdx}); } } if (rowArray.length > 0) { this._executeTableBodyRowsRemove(rowArray); } } catch (e) { oj.Logger.error(e); } finally { this._clearDataWaitingState(); } }, /** * Callback handler for sort completed in the datasource. Refresh entire * table body DOM and refresh the table dimensions. Set row focus to the * current row. * @param {Object} event * @private */ _handleDataSort: function(event) { try { var columnIdx = null; var columns = this._getColumnDefs(); var i, column, sortField, columnsCount = columns.length; for (i = 0; i < columnsCount; i++) { column = columns[i]; sortField = column['sortProperty'] == null ? column['field'] : column['sortProperty']; if (event['header'] == sortField) { columnIdx = i; break; } } if (event != null) { this._refreshSortTableHeaderColumn(event['header'], event['direction'] == this._COLUMN_SORT_ORDER._ASCENDING); } // clear selection if not single selection var existingSelection = this['options']['selection']; if (existingSelection != null) { var clearSelection = false; if (existingSelection.length > 1) { clearSelection = true; } else if (existingSelection[0] != null) { var startIndex = existingSelection[0][this._CONST_STARTINDEX]; var endIndex = existingSelection[0][this._CONST_ENDINDEX]; if (!oj.Object.compareValues(startIndex, endIndex) && endIndex != null) { clearSelection = true; } } if (clearSelection) { this._setSelection(null); this.option('selection', null, {'_context': {writeback: true, internalSet: true}}); } } // set the current row this._setCurrentRow(this.options['currentRow'], null, false); var self = this; this._queueTask(function() { if (self._isLoadMoreOnScroll()) { return self._invokeDataFetchRows(0, null); } return self._invokeDataFetchRows(null); }).then(function() { if (columnIdx != null) { setTimeout(function() { self._scrollColumnIntoViewport(columnIdx); self = null; columnIdx = null; }, 0); } }); } catch (e) { oj.Logger.error(e); } finally { this._clearDataWaitingState(); } }, /** * Handler for Left/Right keydown. * @param {Object} event * @private */ _handleKeydownLeftRight: function(event) { if (this._isTableActionableMode()) { // ignore in actionable mode return; } // pressing left/right navigates the column headers var focusedHeaderColumnIdx = this._getFocusedHeaderColumnIdx(); var columns = this._getColumnDefs(); if (focusedHeaderColumnIdx != null) { var newFocusedHeaderColumnIdx = focusedHeaderColumnIdx; if (this._isKeyboardKeyPressed(this._KEYBOARD_CODES._KEYBOARD_CODE_LEFT)) { newFocusedHeaderColumnIdx = focusedHeaderColumnIdx > 0 ? focusedHeaderColumnIdx - 1 : focusedHeaderColumnIdx; } else if (this._isKeyboardKeyPressed(this._KEYBOARD_CODES._KEYBOARD_CODE_RIGHT)) { newFocusedHeaderColumnIdx = focusedHeaderColumnIdx < columns.length - 1 ? focusedHeaderColumnIdx + 1 : focusedHeaderColumnIdx; } if (newFocusedHeaderColumnIdx != focusedHeaderColumnIdx) { this._setHeaderColumnFocus(newFocusedHeaderColumnIdx, true, false, null); if (event[this._KEYBOARD_CODES._KEYBOARD_MODIFIER_SHIFT]) { // if shift is also pressed then we need to select too var newFocusedHeaderColumnSelection = this._getHeaderColumnSelection(newFocusedHeaderColumnIdx); // we may be clearing or setting the selection this._setHeaderColumnSelection(newFocusedHeaderColumnIdx, !newFocusedHeaderColumnSelection, null, event, true); // if we are clearing the selection, then clear the previous column too. if (newFocusedHeaderColumnSelection) { if (this._getHeaderColumnSelection(focusedHeaderColumnIdx)) { this._setHeaderColumnSelection(focusedHeaderColumnIdx, false, null, event, true); } } } } } }, /** * Handler for Tab keydown. * @param {Object} event * @private */ _handleKeydownTab: function(event) { // if Tab is pressed while a row has focus and we are in actionable/editable // mode then want to Tab within that row until Esc or F2 is pressed var tabHandled = false; var focusedRowIdx = this._getFocusedRowIdx(); var focusedHeaderColumnIdx = this._getFocusedHeaderColumnIdx(); if ((focusedRowIdx != null || focusedHeaderColumnIdx != null) && (this._isTableActionableMode() || this._hasEditableRow())) { var currentFocusElement = document.activeElement; var tableBody = this._getTableDomUtils().getTableBody(); var tableHeader = this._getTableDomUtils().getTableHeader(); if (this._getEditableRowIdx() === focusedRowIdx) { // If we are on an editable row and there are no more editable // elements to focus to then go to the next row var tableBodyRow = this._getTableDomUtils().getTableBodyRow(focusedRowIdx); var tabbableElementsInRow = this._getTabbableElements(tableBodyRow); var tabbableElementsInRowCount = tabbableElementsInRow != null ? tabbableElementsInRow.length : 0; var rowElementTabIndex = tabbableElementsInRow.index(currentFocusElement); if (rowElementTabIndex == tabbableElementsInRowCount - 1 && !event[this._KEYBOARD_CODES._KEYBOARD_MODIFIER_SHIFT]) { // last tabbable element in row so go to the next row this._setNextRowEditable(0, event); } else if (rowElementTabIndex == 0 && event[this._KEYBOARD_CODES._KEYBOARD_MODIFIER_SHIFT]) { // first tabbable element in row and Shift+Tab so go to the previous row var tableHeaderColumns = this._getTableDomUtils().getTableHeaderColumns(); var tableHeaderColumnsCount = tableHeaderColumns.length; this._setPreviousRowEditable(tableHeaderColumnsCount - 1, event); } else { return; } } else if ($.contains(tableBody[0], currentFocusElement) || $.contains(tableHeader[0], currentFocusElement)) { var focusedElement = null; if ($.contains(tableBody[0], currentFocusElement)) { focusedElement = this._getTableDomUtils().getTableBodyRow(focusedRowIdx); } else if ($.contains(tableHeader[0], currentFocusElement)) { focusedElement = this._getTableDomUtils().getTableHeader(); } var tabbableElementsInFocusedElement = this._getTabbableElements(focusedElement); if (tabbableElementsInFocusedElement.length > 0) { // If only one tabbable element then stay on it if (tabbableElementsInFocusedElement.length > 1) { if (!event[this._KEYBOARD_CODES._KEYBOARD_MODIFIER_SHIFT]) { // Tabbing on the last tabbable element will wrap back var lastTabbableElementFocusedElement = tabbableElementsInFocusedElement[tabbableElementsInFocusedElement.length - 1]; if (currentFocusElement == lastTabbableElementFocusedElement) { $(tabbableElementsInFocusedElement[0]).focus(); event.preventDefault(); event.stopPropagation(); } else { // find which element it is var i; for (i = 0; i < tabbableElementsInFocusedElement.length; i++) { if (currentFocusElement == tabbableElementsInFocusedElement[i]) { tabbableElementsInFocusedElement[i + 1].focus(); event.preventDefault(); event.stopPropagation(); break; } } } } else { // Shift+Tabbing on the first tabbable element in a row will wrap back var firstTabbableElementFocusedElement = tabbableElementsInFocusedElement[0]; if (currentFocusElement == firstTabbableElementFocusedElement) { $(tabbableElementsInFocusedElement[tabbableElementsInFocusedElement.length - 1]).focus(); event.preventDefault(); event.stopPropagation(); } else { // find which element it is var i; for (i = 0; i < tabbableElementsInFocusedElement.length; i++) { if (currentFocusElement == tabbableElementsInFocusedElement[i]) { tabbableElementsInFocusedElement[i - 1].focus(); event.preventDefault(); event.stopPropagation(); break; } } } } } else { event.preventDefault(); event.stopPropagation(); } return; } } if (focusedRowIdx != null && !this._hasEditableRow() || focusedHeaderColumnIdx != null) { if (!event[this._KEYBOARD_CODES._KEYBOARD_MODIFIER_SHIFT]) { tabHandled = true; var focusedElement = null; if (focusedRowIdx != null) { focusedElement = this._getTableDomUtils().getTableBodyRow(focusedRowIdx); } else if (focusedHeaderColumnIdx != null) { focusedElement = this._getTableDomUtils().getTableHeaderColumn(focusedHeaderColumnIdx); } var tabbableElementsInFocusedElement = this._getTabbableElements(focusedElement); if (tabbableElementsInFocusedElement != null) { $(tabbableElementsInFocusedElement[0]).focus(); } else { if (focusedRowIdx != null) { // if there are no tabbable elements // in the row then focus on the first // tabbable element in the body var tabbableElementsInBody = this._getTabbableElements(tableBody); $(tabbableElementsInBody[0]).focus(); } else if (focusedHeaderColumnIdx != null) { // if there are no tabbable elements // in the column then focus on the first // tabbable element in the thead var tabbableElementsInHeader = this._getTabbableElements(tableHeader); $(tabbableElementsInHeader[0]).focus(); } } event.preventDefault(); event.stopPropagation(); } } } if (!tabHandled) { // tab out of the component to the next tabbable // element on the page // clear all highlights etc, because we are tabbing out of the table this._clearKeyboardKeys(); this._clearFocusedHeaderColumn(); this._clearFocusedRow(false); this._setTableActionableMode(false); var table = this._getTableDomUtils().getTable(); var tabbableElementsInDocument = this._getTabbableElements($(document)); var tabbableElementsInDocumentCount = tabbableElementsInDocument.length; var tabbableElementsInTable = this._getTabbableElements(table); var tabbableElementsInTableCount = tabbableElementsInTable != null ? tabbableElementsInTable.length : 0; var tableTabIndex = tabbableElementsInDocument.index(this._getTableDomUtils().getTable()); if (!event[this._KEYBOARD_CODES._KEYBOARD_MODIFIER_SHIFT]) { if (tableTabIndex != tabbableElementsInDocumentCount - 1 && tableTabIndex + tabbableElementsInTableCount + 1 <= tabbableElementsInDocumentCount - 1) { $(tabbableElementsInDocument[tableTabIndex + tabbableElementsInTableCount + 1]).focus(); } else { // Table is the last element or we've exceeded the tabbable // elements in the document. Focus on the last tabbable element // in the table and let the browser handle the tab. if (tabbableElementsInTableCount > 0) { // Need to set this variable because the focus() call will // trigger a focusin which we do not want to handle. this._temporaryTableChildElementFocus = true; tabbableElementsInTable[tabbableElementsInTableCount - 1].focus(); var self = this; setTimeout(function() { self._temporaryTableChildElementFocus = false; }, 0); } return; } } else if (tableTabIndex >= 0) { if (tableTabIndex == 0) { // Table is the first element. Let the browser handle the tab. return; } else { $(tabbableElementsInDocument[tableTabIndex - 1]).focus(); } } else { return; } event.preventDefault(); event.stopPropagation(); } // we need to remove Tab on keydown because we may not // get a keyup for it if focus moves // outside of table this._removeKeyboardKey(event.keyCode); }, /** * Handler for Up/Down keydown. * @param {Object} event * @private */ _handleKeydownUpDown: function(event) { if (this._isTableActionableMode()) { // ignore in actionable mode return; } var focusedRowIdx = this._getFocusedRowIdx(); var focusedHeaderColumnIdx = this._getFocusedHeaderColumnIdx(); if (focusedRowIdx != null && !this._hasEditableRow()) { // if row is focused then up/down navigates the rows var tableBodyRows = this._getTableDomUtils().getTableBodyRows(); var rowCount = tableBodyRows != null ? tableBodyRows.length : 0; var newFocusedRowIdx = focusedRowIdx; if (this._isKeyboardKeyPressed(this._KEYBOARD_CODES._KEYBOARD_CODE_UP)) { if (focusedRowIdx > 0) { newFocusedRowIdx = focusedRowIdx - 1; } else if (!this._hasEditableRow()) { newFocusedRowIdx = focusedRowIdx; } } else if (this._isKeyboardKeyPressed(this._KEYBOARD_CODES._KEYBOARD_CODE_DOWN)) { newFocusedRowIdx = focusedRowIdx < rowCount - 1 ? focusedRowIdx + 1 : focusedRowIdx; } if (newFocusedRowIdx != focusedRowIdx) { var focused = this._setRowFocus(newFocusedRowIdx, true, true, null, event); if (!focused) { return; } this._getTableDomUtils().getTable().focus(); if (event[this._KEYBOARD_CODES._KEYBOARD_MODIFIER_SHIFT]) { // if shift is also pressed then we need to select too var newFocusedRowSelection = this._getRowSelection(newFocusedRowIdx); // we may be clearing or setting the selection this._setRowSelection(newFocusedRowIdx, !newFocusedRowSelection, null, event, true); // if we are clearing the selection, then clear the previous row too. if (newFocusedRowSelection) { if (this._getRowSelection(focusedRowIdx)) { this._setRowSelection(focusedRowIdx, false, null, event, true); } } } } // if user is on the first row and presses up the focus on the first column header else if (newFocusedRowIdx == focusedRowIdx && focusedRowIdx == 0 && this._isKeyboardKeyPressed(this._KEYBOARD_CODES._KEYBOARD_CODE_UP)) { this._setHeaderColumnFocus(0, true, false, null); } } // if user is on a column header and pressed down then focus on the first row else if (focusedHeaderColumnIdx != null && this._isKeyboardKeyPressed(this._KEYBOARD_CODES._KEYBOARD_CODE_DOWN)) { this._setRowFocus(0, true, true, null, event); } }, /** * Handler for End keyup. * @param {Object} event * @private */ _handleKeyupEnd: function(event) { if (this._isTableActionableMode()) { // ignore in actionable mode return; } // pressing End focuses on last column var focusedColumnIdx = this._getFocusedHeaderColumnIdx(); if (focusedColumnIdx != null && focusedColumnIdx != this._getColumnDefs().length - 1) { this._setHeaderColumnFocus(this._getColumnDefs().length - 1, true, false, null); } else if (!this._hasEditableRow()) { var focusedRowIdx = this._getFocusedRowIdx(); var tableBodyRows = this._getTableDomUtils().getTableBodyRows(); var rowCount = tableBodyRows != null ? tableBodyRows.length : 0; if (focusedRowIdx != null && focusedRowIdx != rowCount - 1 && rowCount > 0) { this._setRowFocus(rowCount - 1, true, true, null, event); } } }, /** * Handler for Enter keyup. * @param {Object} event * @private */ _handleKeyupEnter: function(event) { if (this._isTableActionableMode()) { // ignore in actionable mode return; } // pressing enter does sort on the focused column header var focusedColumnIdx = this._getFocusedHeaderColumnIdx(); if (focusedColumnIdx != null && this._getColumnDefs()[focusedColumnIdx]['sortable'] == this._OPTION_ENABLED) { var tableHeaderColumn = this._getTableDomUtils().getTableHeaderColumn(focusedColumnIdx); var sorted = tableHeaderColumn.data('sorted'); // if not already sorted then sort ascending. If already sorted // ascending then do descending sort and vice versa. if (sorted == null || sorted == this._COLUMN_SORT_ORDER._DESCENDING) { this._handleSortTableHeaderColumn(focusedColumnIdx, true, event); } else { this._handleSortTableHeaderColumn(focusedColumnIdx, false, event); } } else { var currentRow = this._getCurrentRow(); currentRow = currentRow || {}; var currentRowIdx = currentRow['rowIndex']; if (currentRowIdx >= 0) { var tableBodyRows = this._getTableDomUtils().getTableBodyRows(); var rowCount = tableBodyRows != null ? tableBodyRows.length : 0; if (this._isTableEditMode()) { if (!this._hasEditableRow()) { this._setTableEditable(true, false, 0, true, event); return; } var columnIdx = this._getTableDomUtils().getElementColumnIdx($(event.target)); if (!event[this._KEYBOARD_CODES._KEYBOARD_MODIFIER_SHIFT]) { this._setNextRowEditable(columnIdx, event); } else { this._setPreviousRowEditable(columnIdx, event); } } else { this._setTableActionableMode(true); } } } }, /** * Handler for Esc keyup. * @param {Object} event * @private */ _handleKeyupEsc: function(event) { // pressing Esc always returns focus back to the table. event.preventDefault(); event.stopPropagation(); this._setTableEditable(false, true, 0, true, event); this._getTableDomUtils().getTable().focus(); this._setTableActionableMode(false); }, /** * Handler for F2 keyup. * @param {Object} event * @private */ _handleKeyupF2: function(event) { event.preventDefault(); event.stopPropagation(); if (this._isTableEditMode()) { // pressing F2 toggles between editable modes. if (!this._hasEditableRow()) { this._setTableEditable(true, false, 0, true, event); } else { this._setTableEditable(false, false, 0, true, event); } } else { if (this._isTableActionableMode()) { this._setTableActionableMode(false); } else { this._setTableActionableMode(true); } } }, /** * Handler for Home keyup. * @param {Object} event * @private */ _handleKeyupHome: function(event) { if (this._isTableActionableMode()) { // ignore in actionable mode return; } // pressing Home focuses on first column var focusedColumnIdx = this._getFocusedHeaderColumnIdx(); if (focusedColumnIdx != null && focusedColumnIdx != 0) { this._setHeaderColumnFocus(0, true, false, null); } else if (!this._hasEditableRow()) { var focusedRowIdx = this._getFocusedRowIdx(); if (focusedRowIdx != null && focusedRowIdx != 0) { this._setRowFocus(0, true, true, null, event); } } }, /** * Handler for Spacebar keyup. * @param {Object} event * @private */ _handleKeyupSpacebar: function(event) { if (this._isTableActionableMode()) { // ignore in actionable mode return; } // pressing spacebar selects the focused row/column var focusedRowIdx = this._getFocusedRowIdx(); if (focusedRowIdx != null) { this._setRowSelection(focusedRowIdx, !this._getRowSelection(focusedRowIdx), null, event, true); } else if (!this._hasEditableRow()) { var focusedHeaderColumnIdx = this._getFocusedHeaderColumnIdx(); if (focusedHeaderColumnIdx != null) { this._clearSelectedRows(); this._setHeaderColumnSelection(focusedHeaderColumnIdx, !this._getHeaderColumnSelection(focusedHeaderColumnIdx), null, event, true); } } }, /** * Callback handler mouse move for selection. * @private */ _handleMouseEnterSelection: function(element) { var rowIdx = this._getTableDomUtils().getElementRowIdx($(element)); if (rowIdx != null && this._mouseDownRowIdx != null && this._mouseDownRowIdx != rowIdx) { var lastSelectedRowIdx = this._mouseDownRowIdx; var selectedRowIdxs = this._getSelectedRowIdxs(); if (rowIdx < lastSelectedRowIdx) { var i; for (i = 0; i < selectedRowIdxs.length; i++) { if (selectedRowIdxs[i] < rowIdx || selectedRowIdxs[i] > lastSelectedRowIdx) { this._setRowSelection(selectedRowIdxs[i], false, element, null, true); } } for (i = lastSelectedRowIdx; i >= rowIdx; i--) { this._setRowSelection(i, true, element, null, true); this._getTableDomUtils().moveTableBodyRowTouchSelectionAffordanceTop(i); } } else { var i; for (i = 0; i < selectedRowIdxs.length; i++) { if (selectedRowIdxs[i] > rowIdx || selectedRowIdxs[i] < lastSelectedRowIdx) { this._setRowSelection(selectedRowIdxs[i], false, element, null, true); } } for (i = lastSelectedRowIdx; i <= rowIdx; i++) { this._setRowSelection(i, true, element, null, true); this._getTableDomUtils().moveTableBodyRowTouchSelectionAffordanceBottom(i); } } } }, /** * Callback handler max fetch count. * @private */ _handleScrollerMaxRowCount: function() { // TODO: use inline messaging framwork when ready var errSummary = this._LOGGER_MSG._ERR_DOM_SCROLLER_MAX_COUNT_SUMMARY; var errDetail = this._LOGGER_MSG._ERR_DOM_SCROLLER_MAX_COUNT_DETAIL; this._showInlineMessage(errSummary, errDetail, oj.Message.SEVERITY_LEVEL['WARNING']); }, /** * Handle scrollLeft on scroller * @private */ _handleScrollerScrollLeft: function(scrollLeft) { var tableHeader = this._getTableDomUtils().getTableHeader(); var tableFooter = this._getTableDomUtils().getTableFooter(); if (!this._getTableDomUtils().isDivScroller()) { var tableHeaderRow = this._getTableDomUtils().getTableHeaderRow(); if (tableHeaderRow) { if (this._GetReadingDirection() === "rtl") { tableHeaderRow.css(oj.TableDomUtils.CSS_PROP._RIGHT, '-' + scrollLeft + oj.TableDomUtils.CSS_VAL._PX); } else { tableHeaderRow.css(oj.TableDomUtils.CSS_PROP._LEFT, '-' + scrollLeft + oj.TableDomUtils.CSS_VAL._PX); } } var tableFooterRow = this._getTableDomUtils().getTableFooterRow(); if (tableFooterRow) { if (this._GetReadingDirection() === "rtl") { tableFooterRow.css(oj.TableDomUtils.CSS_PROP._RIGHT, '-' + scrollLeft + oj.TableDomUtils.CSS_VAL._PX); } else { tableFooterRow.css(oj.TableDomUtils.CSS_PROP._LEFT, '-' + scrollLeft + oj.TableDomUtils.CSS_VAL._PX); } } } else { if (tableHeader) { if (this._GetReadingDirection() === "rtl") { tableHeader.css(oj.TableDomUtils.CSS_PROP._RIGHT, '-' + scrollLeft + oj.TableDomUtils.CSS_VAL._PX); } else { tableHeader.css(oj.TableDomUtils.CSS_PROP._LEFT, '-' + scrollLeft + oj.TableDomUtils.CSS_VAL._PX); } } if (tableFooter) { if (this._GetReadingDirection() === "rtl") { tableFooter.css(oj.TableDomUtils.CSS_PROP._RIGHT, '-' + scrollLeft + oj.TableDomUtils.CSS_VAL._PX); } else { tableFooter.css(oj.TableDomUtils.CSS_PROP._LEFT, '-' + scrollLeft + oj.TableDomUtils.CSS_VAL._PX); } } } }, /** * Handler for column sort * @param {number} columnIdx column index * @param {boolean} ascending sort order ascending * @param {Object} event * @private */ _handleSortTableHeaderColumn: function(columnIdx, ascending, event) { // clear the sorted indicator on any other column this._clearSortedHeaderColumn(columnIdx); // get the column metadata var column = this._getColumnDefs()[columnIdx]; // get which field to sort on var sortField = column['sortProperty'] == null ? column['field'] : column['sortProperty']; // invoke sort on the data this._invokeDataSort(sortField, ascending, event); this._sortColumn = column; this._refreshSortTableHeaderColumn(sortField, ascending); }, /** * Return whether the table currently has an editable row * @return {boolean} true or false * @private */ _hasEditableRow: function() { if (!this._isTableEditMode()) { return false; } return this._getEditableRowIdx() !== null; }, /** * Has row or cell renderer * @param {number|null} columnIdx column index * @return {boolean} true or false * @private */ _hasRowOrCellRenderer: function(columnIdx) { var rowRenderer = this._getRowRenderer(); if (rowRenderer != null) { return true; } else { var cellRenderer = null; if (columnIdx != null) { cellRenderer = this._getColumnRenderer(columnIdx, 'cell'); } else { var columns = this._getColumnDefs(); var i, columnsCount = columns.length; for (i = 0; i < columnsCount; i++) { cellRenderer = this._getColumnRenderer(i, 'cell'); if (cellRenderer != null) { break; } } } if (cellRenderer != null) { return true; } } return false; }, /** * Hide the inline message. * @private */ _hideInlineMessage: function() { var inlineMessage = this._getTableDomUtils().getTableInlineMessage(); if (inlineMessage.css(oj.TableDomUtils.CSS_PROP._DISPLAY) != oj.TableDomUtils.CSS_VAL._NONE) { var inlineMessageHeight = inlineMessage.outerHeight(); var tableContainer = this._getTableDomUtils().getTableContainer(); var tableContainerBorderBottom = parseInt(tableContainer.css(oj.TableDomUtils.CSS_PROP._BORDER_BOTTOM_WIDTH), 10); var tableContainerMarginBottom = parseInt(tableContainer.css(oj.TableDomUtils.CSS_PROP._MARGIN_BOTTOM), 10); tableContainerMarginBottom = tableContainerMarginBottom - tableContainerBorderBottom - inlineMessageHeight; tableContainer.css(oj.TableDomUtils.CSS_PROP._MARGIN_BOTTOM, tableContainerMarginBottom + oj.TableDomUtils.CSS_VAL._PX); tableContainer.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._WARNING); inlineMessage.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._WARNING); inlineMessage.css(oj.TableDomUtils.CSS_PROP._BOTTOM, ''); inlineMessage.css(oj.TableDomUtils.CSS_PROP._DISPLAY, oj.TableDomUtils.CSS_VAL._NONE); } }, /** * Hide the 'No data to display.' message. * @private */ _hideNoDataMessage: function() { var tableBodyMessageRow = this._getTableDomUtils().getTableBodyMessageRow(); if (tableBodyMessageRow != null) { tableBodyMessageRow.remove(); } }, /** * Hide the Fetching Data... status message. * @private */ _hideStatusMessage: function() { var statusMessage = this._getTableDomUtils().getTableStatusMessage(); statusMessage.css(oj.TableDomUtils.CSS_PROP._DISPLAY, oj.TableDomUtils.CSS_VAL._NONE); }, /** * Hide the column header sort link * @param {number} columnIdx column index * @param {boolean} ascending sort order ascending * @private */ _hideTableHeaderColumnSortLink: function(columnIdx, ascending) { // check if the column is sortable. If not, then there won't be any sort links if (this._getColumnDefs()[columnIdx]['sortable'] == this._OPTION_ENABLED) { var tableHeaderColumn = this._getTableDomUtils().getTableHeaderColumn(columnIdx); // check if the column is currently sorted var sorted = tableHeaderColumn.data('sorted'); // we should only hide the ascending sort link if the column is not sorted or // is sorted by descending order if (ascending && (sorted == null || sorted == this._COLUMN_SORT_ORDER._DESCENDING)) { var headerColumnAscLink = tableHeaderColumn.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ASC_LINK_CLASS); headerColumnAscLink.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DISABLED); headerColumnAscLink.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._ENABLED); headerColumnAscLink.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._SELECTED); } // we should only hide the descending sort link if the column is not sorted or // is sorted by ascending order else if (!ascending && (sorted == null || sorted == this._COLUMN_SORT_ORDER._ASCENDING)) { var headerColumnDscLink = tableHeaderColumn.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DSC_LINK_CLASS); headerColumnDscLink.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DISABLED); headerColumnDscLink.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._ENABLED); headerColumnDscLink.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._SELECTED); } } }, /** * Do an initial fetch * @private */ _initFetch: function() { var self = this; var data = this._getData(); // do an initial fetch if a TableDataSource // paging control should do the fetches for PagingTableDataSource if (data != null && ((data instanceof oj.TableDataSource && !(data instanceof oj.PagingTableDataSource)) || ((data instanceof oj.PagingTableDataSource) && this._isLoadMoreOnScroll()))) { // reset the scrollTop when we do an initial fetch this._getTableDomUtils().getScroller()[0].scrollTop = 0; this._queueTask(function() { var result = self._invokeDataFetchRows(0, {'fetchType': 'init'}); self = null; return result; }); } else if (data == null) { this._queueTask(function() { return Promise.resolve(); }); } }, /** * Fetch rows * @param {number|null} startIndex start index * @param {Object} options options for the fetch * @return {Promise} Promise resolves when done. * @private */ _invokeDataFetchRows: function(startIndex, options) { options = options || {}; options[this._CONST_STARTINDEX] = startIndex; if (!options[this._CONST_PAGESIZE] && this._isLoadMoreOnScroll()) { options[this._CONST_PAGESIZE] = this.options['scrollPolicyOptions']['fetchSize']; } options['silent'] = true; var initFetch = options['fetchType'] == 'init'? true : false; var data = this._getData(); var self = this; return new Promise(function(resolve, reject) { if (data != null) { self._setDataWaitingState(); data.fetch(options).then(function(result) { if (result != null) { if (result[self._CONST_DATA] != null) { if (data['sortCriteria'] != null) { var sortCriteriaKey = data['sortCriteria']['key']; var sortCriteriaDirection = data['sortCriteria']['direction']; if (sortCriteriaKey != null && sortCriteriaDirection != null) { // update the sort direction if the data is sorted self._refreshSortTableHeaderColumn(sortCriteriaKey, sortCriteriaDirection == self._COLUMN_SORT_ORDER._ASCENDING); // update the acc status notification if (sortCriteriaDirection == self._COLUMN_SORT_ORDER._ASCENDING) { self._getTableDomUtils().setTableStatusAccNotification(self.getTranslatedString(self._BUNDLE_KEY._MSG_STATUS_SORT_ASC, sortCriteriaKey)); } else { self._getTableDomUtils().setTableStatusAccNotification(self.getTranslatedString(self._BUNDLE_KEY._MSG_STATUS_SORT_DSC, sortCriteriaKey)); } } } var offset = 0; if (data instanceof oj.PagingTableDataSource) { offset = data.getStartItemIndex(); } var indexArray = []; var i, resultDataCount = result[self._CONST_DATA].length; for (i = 0; i < resultDataCount; i++) { indexArray[i] = i + offset + result[self._CONST_STARTINDEX]; } var j, metadataArray; if (data instanceof oj.FlattenedTreeTableDataSource) { metadataArray = []; for (j = 0; j < resultDataCount; j++) { metadataArray[j] = data._getMetadata(indexArray[j]); } } self._refreshAll({'data': result[self._CONST_DATA], 'metadata': metadataArray, 'keys' : result[self._CONST_KEYS], 'indexes': indexArray}, result[self._CONST_STARTINDEX], initFetch, initFetch); } } self._clearDataWaitingState(); self = null; resolve(null); }, function(error) { // TODO inline messaging framework self._clearDataWaitingState(); self = null; reject(error); }); } else { resolve(null); } }); }, /** * Invoke sort on a field. This function is called when a user clicks the * column header sort links * @param {string} sortField field name * @param {boolean} ascending sort order ascending * @param {Object} event * @private */ _invokeDataSort: function(sortField, ascending, event) { var data = this._getData(); // if no data then bail if (!data) { return null; } // show the Fetching Data... message this._showStatusMessage(); var sortCriteria = {}; sortCriteria[this._CONST_KEY] = sortField; // the sort function on the datasource takes comparators if (ascending) { sortCriteria['direction'] = this._COLUMN_SORT_ORDER._ASCENDING; } else { sortCriteria['direction'] = this._COLUMN_SORT_ORDER._DESCENDING; } this._trigger('sort', event, {'header': sortCriteria[this._CONST_KEY], 'direction': sortCriteria['direction']}); var sortPromise = data.sort(sortCriteria); this._queueTask(function() { return sortPromise; }); }, /** * Whether the columns have been updated * @return {boolean} true or false * @private */ _isColumnMetadataUpdated: function() { if (this._columnDefArray != null) { var columnsMetadata = this._getColumnMetadata(); if (this._columnDefArray.length != columnsMetadata.length) { return true; } else { var i, prop, columnsMetadataCount = columnsMetadata.length; for (i = 0; i < columnsMetadataCount; i++) { for (prop in columnsMetadata[i]) { if (columnsMetadata[i].hasOwnProperty(prop)) { if (columnsMetadata[i][prop] != this._columnDefArray[i][prop]) { if (prop != 'id' || columnsMetadata[i][prop] == null || columnsMetadata[i][prop].indexOf(this._COLUMN_HEADER_ID_PREFIX) != 0 || this._columnDefArray[i][prop] == null || this._columnDefArray[i][prop].indexOf(this._COLUMN_HEADER_ID_PREFIX) != 0) { // ignore generated ids return true; } } } } } } return false; } return true; }, /** * Is keybaord key pressed * @param {number} keyCode KeyCode of the keyboard key. * @return {boolean} true or false * @private */ _isKeyboardKeyPressed: function(keyCode) { var keyboardKeys = this._getKeyboardKeys(); var i, keyboardKeysCount = keyboardKeys.length; for (i = 0; i < keyboardKeysCount; i++) { if (keyboardKeys[i] == keyCode) { return true; } } return false; }, /** * Is loadMoreOnScroll * @return {boolean} true or false * @private */ _isLoadMoreOnScroll: function() { return this.options['scrollPolicy'] == this._OPTION_SCROLL_POLICY._LOADMORE_ON_SCROLL ? true: false; }, /** * Return whether the node is editable * @param {jQuery} node Node * @return {boolean} true or false * @private */ _isNodeEditable: function(node) { return this._isNodeType(node, /^INPUT|TEXTAREA/); }, /** * Return whether the node is clickable * @param {jQuery} node Node * @return {boolean} true or false * @private */ _isNodeClickable: function(node) { return this._isNodeType(node, /SELECT|OPTION|BUTTON|^A\b/); }, /** * Return whether the node or any of its ancestors is draggable * @param {jQuery} node Node * @return {boolean} true or false * @private */ _isNodeDraggable: function(node) { return (node.closest("[draggable='true']").length > 0); }, /** * Return whether the node is editable or clickable * @param {jQuery} node Node * @param {Object} type regex * @return {boolean} true or false * @private */ _isNodeType: function(node, type) { var nodeName; var table = this._getTableDomUtils().getTable(); while (null != node && node[0] != table[0] && (nodeName = node.prop("nodeName")) != "TD" && nodeName != "TH") { // If the node is a text node, move up the hierarchy to only operate on elements // (on at least the mobile platforms, the node may be a text node) if (node[0].nodeType == 3) // 3 is Node.TEXT_NODE { node = node[0].parentNode; continue; } var tabIndex = node.attr(oj.TableDomUtils.DOM_ATTR._TABINDEX); if (nodeName.match(type)) { // ignore elements with tabIndex == -1 if (tabIndex != -1) { return true; } } node = node.parentNode; } return false; }, /** * Return whether the component is in table actionable mode * @return {boolean} true or false * @private */ _isTableActionableMode: function() { return this._tableActionableMode; }, /** * Returns whether the table is editabe mode * @return {boolean} true or false * @private */ _isTableEditMode: function() { var editMode = this['options']['editMode']; if (editMode == this._OPTION_EDIT_MODE._ROW_EDIT) { return true; } return false; }, /** * Returns whether the table is footerless * @return {boolean} true or false * @private */ _isTableFooterless: function() { var columns = this._getColumnDefs(); var i, footerRenderer, columnsCount = columns.length; for (i = 0; i < columnsCount; i++) { footerRenderer = this._getColumnRenderer(i, 'footer'); if (footerRenderer != null) { return false } } return true; }, /** * Returns whether the table is headerless * @return {boolean} true or false * @private */ _isTableHeaderless: function() { var columns = this._getColumnDefs(); var i, j, columnsCount = columns.length; for (i = 0; i < columnsCount; i++) { if (columns[i]['headerText'] != null || columns[i]['headerStyle'] != null || (columns[i]['sortable'] != null && columns[i]['sortable'] != this._OPTION_DISABLED) || columns[i]['sortProperty'] != null || columns[i]['headerRenderer'] != null) { return false; } } return true; }, /** * Returns whether the table header columns were rendered * @return {boolean} true or false * @private */ _isTableHeaderColumnsRendered: function() { return this._renderedTableHeaderColumns == true; }, /** * Returns whether the table refresh is needed based on option change * @param {string} key option key * @param {Object} value option value * @return {boolean} true or false * @private */ _isTableRefreshNeeded: function(key, value) { var currentOptions = this._cachedOptions; var refresh = false; if (key == 'contextMenu' && value == '#' + this._getTableDomUtils().getTableId() + '_contextmenu') { refresh = false; } else if (key == 'columns' && !this._isColumnMetadataUpdated()) { // optimization for columns. Column re-order can change the columns options but we don't need to refresh refresh = false; } else if (key != 'selection' && key != 'currentRow' && !oj.Object.compareValues(value, currentOptions[key])) { refresh = true; } this._cachedOptions = $.extend(true, {}, this.options); return refresh; }, /** * Returns whether any of the table columns are sortable * @return {boolean} true or false * @private */ _isTableSortable: function() { var columns = this._getColumnDefs(); var i, columnsCount = columns.length; for (i = 0; i < columnsCount; i++) { if (columns[i]['sortable'] != null && columns[i]['sortable'] != this._DISABLED) { return true; } } return false; }, _isTouchDevice: function() { if (this._isTouch == undefined) { var agentName = navigator.userAgent.toLowerCase(); if (agentName.indexOf("mobile") != -1 || agentName.indexOf("android") != -1) { this._isTouch = true; } else { this._isTouch = false; } } return this._isTouch; }, /** * @param {Object} resultObject Object containing data array, key array, and index array * @param {number} startIndex start index * @param {boolean} resetScrollTop reset the scrollTop * @param {boolean} resetScrollLeft reset the scrollLeft * @private */ _refreshAll: function(resultObject, startIndex, resetScrollTop, resetScrollLeft) { if (this._isColumnMetadataUpdated() || (!this._isTableHeaderColumnsRendered() && !this._isTableHeaderless())) { this._clearCachedMetadata(); this._refreshTableHeader(); // see if we need to clear the sort. If the column we sorted on is no // longer there then clear it. if (this._sortColumn != null) { var i, column; var foundColumn = false; var columns = this._getColumnDefs(); if (columns != null) { var columnsCount = columns.length; for (i = 0; i < columnsCount; i++) { column = columns[i]; if (oj.Object.compareValues(column, this._sortColumn)) { foundColumn = true; break; } } if (!foundColumn) { this._getData().sort(null); } } } } this._refreshTableFooter(); this._refreshTableBody(resultObject, startIndex, resetScrollTop, resetScrollLeft); }, /** * Handler for column sort * @param {string} key sort key * @param {boolean} ascending sort order ascending * @private */ _refreshSortTableHeaderColumn: function(key, ascending) { var columns = this._getColumnDefs(); var i, column, columnIdx = null, columnsCount = columns.length, sortField; for (i = 0; i < columnsCount; i++) { column = columns[i]; sortField = column['sortProperty'] == null ? column['field'] : column['sortProperty']; if (key == sortField) { columnIdx = i; break; } } if (columnIdx == null) { return; } // clear the sorted indicator on any other column this._clearSortedHeaderColumn(columnIdx); // get the column header DOM element var tableHeaderColumn = this._getTableDomUtils().getTableHeaderColumn(columnIdx); if (tableHeaderColumn == null) { return; } var sorted = tableHeaderColumn.data('sorted'); if (ascending && sorted != this._COLUMN_SORT_ORDER._ASCENDING) { // store sort order on the DOM element tableHeaderColumn.data('sorted', this._COLUMN_SORT_ORDER._ASCENDING); var headerColumnAscLink = tableHeaderColumn.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ASC_LINK_CLASS); headerColumnAscLink.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._ENABLED); headerColumnAscLink.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DISABLED); var headerColumnAsc = tableHeaderColumn.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ASC_CLASS); headerColumnAsc.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DISABLED); var headerColumnDsc = tableHeaderColumn.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DSC_CLASS); headerColumnDsc.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DISABLED); this._hideTableHeaderColumnSortLink(columnIdx, !ascending); } else if (!ascending && sorted != this._COLUMN_SORT_ORDER._DESCENDING) { // store sort order on the DOM element tableHeaderColumn.data('sorted', this._COLUMN_SORT_ORDER._DESCENDING); var headerColumnDscLink = tableHeaderColumn.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DSC_LINK_CLASS); headerColumnDscLink.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._ENABLED); headerColumnDscLink.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DISABLED); var headerColumnDsc = tableHeaderColumn.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DSC_CLASS); headerColumnDsc.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DISABLED); var headerColumnAsc = tableHeaderColumn.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ASC_CLASS); headerColumnAsc.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DISABLED); } }, /** * Refresh the entire table body with data from the datasource * @param {Object} resultObject Object containing data array, key array, and index array * @param {number} startIndex start index * @param {boolean} resetScrollTop reset the scrollTop * @param {boolean} resetScrollLeft reset the scrollLeft * @private */ _refreshTableBody: function(resultObject, startIndex, resetScrollTop, resetScrollLeft) { var tableBody = this._getTableDomUtils().getTableBody(); if (tableBody == null) { return; } var rows = this._getRowIdxRowArray(resultObject, startIndex); var checkFocus = $.contains(tableBody[0], document.activeElement); var tableBodyRows, tableBodyRow, resetFocus = false; if (startIndex == 0) { if (checkFocus) { resetFocus = true; } this._getTableDomUtils().removeAllTableBodyRows(); } else { tableBodyRows = tableBody.children(); if (tableBodyRows != null && tableBodyRows.length > 0) { var i, tableBodyRowsCount = tableBodyRows.length; for (i = tableBodyRowsCount - 1; i >= startIndex; i--) { if (checkFocus) { tableBodyRow = this._getTableDomUtils().getTableBodyRow(i); if (tableBodyRow != null && $.contains(tableBodyRow[0], document.activeElement)) { resetFocus = true; checkFocus = false; } } this._getTableDomUtils().removeTableBodyRow(i); } } } if (resetFocus) { this._getTableDomUtils().getTable().focus(); } this._getTableDomUtils().clearCachedDomRowData(); this._hideNoDataMessage(); tableBodyRows = tableBody.children(); // if no data then bail if (rows.length == 0 && (tableBodyRows == null || tableBodyRows.length == 0)) { this._showNoDataMessage(); } else { var tableBodyDocFrag = $(document.createDocumentFragment()); var i, row, rowIdx, rowsCount = rows.length; for (i = 0; i < rowsCount; i++) { row = rows[i].row; rowIdx = rows[i].rowIdx; if (row != null) { tableBodyRow = this._getTableDomUtils().createTableBodyRow(rowIdx, row[this._CONST_KEY]); this._getTableDomUtils().styleTableBodyRow(tableBodyRow, true); this._getTableDomUtils().insertTableBodyRow(rowIdx, tableBodyRow, row, tableBodyDocFrag); this._refreshTableBodyRow(rowIdx, row, tableBodyRow, tableBodyDocFrag, startIndex, true); } } tableBody.append(tableBodyDocFrag); //@HTMLUpdateOK this._getTableDomUtils().clearCachedDomRowData(); // only bother calling subtree attached if there are potentially // components in our rows if (this._hasRowOrCellRenderer()) { // Re-size the table before calling subtree attached. subtreeAttached is a // potentially expensive call so we want table to be laid out before it. this._getTableDomUtils().refreshTableDimensions(null, null, resetScrollTop, resetScrollLeft); oj.Components.subtreeAttached(tableBody[0]); } } }, /** * Refresh the row at a particular index with the row data * @param {number} rowIdx row index relative to the start of the table * @param {Object} row row and key object * @param {Object} tableBodyRow tr element * @param {Object} docFrag document fragment * @param {number} docFragStartIdx document fragment row start index * @param {boolean} isNew is new row * @private */ _refreshTableBodyRow: function(rowIdx, row, tableBodyRow, docFrag, docFragStartIdx, isNew) { var options = this.options; var rowRenderer = this._getRowRenderer(); var columns = this._getColumnDefs(); var tableBody = this._getTableDomUtils().getTableBody(); if (isNaN(rowIdx) || rowIdx < 0) { // validate rowIdx value oj.Logger.error('Error: Invalid rowIdx value: ' + rowIdx); } var rowHashCode = this._getTableDomUtils().hashCode(row[this._CONST_KEY]); if (tableBodyRow == null) { // check if we already have a <tr> element at that index tableBodyRow = this._getTableDomUtils().getTableBodyRow(rowIdx); if (!tableBodyRow) { // if not return return; } else { tableBodyRow.empty(); isNew = true; this._getTableDomUtils().createTableBodyCellAccSelect(rowIdx, row[this._CONST_KEY], rowHashCode, tableBodyRow, isNew); } } this._hideNoDataMessage(); var currentRow = this._getCurrentRow(); currentRow = currentRow || {}; var rowContext = oj.TableRendererUtils.getRendererContextObject(this, tableBodyRow[0], {'row': row, 'isCurrentRow': currentRow['rowIndex'] == rowIdx}); // Copy additional properties to top-level context to work with custom element var context = {'rowContext': rowContext, 'row': row[this._CONST_DATA], 'componentElement': rowContext['componentElement'], 'parentElement': rowContext['parentElement'], 'data': row[this._CONST_DATA]}; // check if a row renderer was defined if (rowRenderer) { var rowContent = rowRenderer(context); if (rowContent != null) { // if the renderer returned a value then we set it as the content // for the row tableBodyRow.append(rowContent); //@HTMLUpdateOK } else { // if the renderer didn't return a value then the existing // row was manipulated. So get it and set the required // attributes just in case it was replaced or the attributes // got removed if (docFrag == null) { tableBodyRow = $(tableBody.children()[rowIdx]); } else { docFragStartIdx = docFragStartIdx == null ? 0 : docFragStartIdx; tableBodyRow = $(docFrag.children()[rowIdx - docFragStartIdx]); } this._getTableDomUtils().clearCachedDomRowData(); this._getTableDomUtils().setTableBodyRowAttributes(row, tableBodyRow); this._getTableDomUtils().styleTableBodyRow(tableBodyRow, false); } this._getTableDomUtils().createTableBodyCellAccSelect(rowIdx, row[this._CONST_KEY], rowHashCode, tableBodyRow, false); // set the cell attributes and styling. Skip the 1st one // because it's the acc row select td var tableBodyCells = tableBodyRow.children(oj.TableDomUtils.DOM_ELEMENT._TD); var i, tableBodyCellsCount = tableBodyCells.length; for (i = 1; i < tableBodyCellsCount; i++) { var tableBodyCell = $(tableBodyCells[i]); this._getTableDomUtils().setTableBodyCellAttributes(rowIdx, row[this._CONST_KEY], rowHashCode, i - 1, tableBodyCell); this._getTableDomUtils().styleTableBodyCell(i - 1, tableBodyCell, false); } // sort the re-ordered columns in place if (this._columnsDestMap != null) { var moveTableBodyCell, swapTableBodyCell; for (i = 0; i < this._columnsDestMap.length - 1; i++) { if (this._columnsDestMap[i] > i) { moveTableBodyCell = $(tableBodyCells[this._columnsDestMap[i] + 1]); swapTableBodyCell = $(tableBodyCells[i + 1]); moveTableBodyCell[0].parentNode.insertBefore(moveTableBodyCell[0], swapTableBodyCell[0]); //@HTMLUpdateOK tableBodyCells = tableBodyRow.children(oj.TableDomUtils.DOM_ELEMENT._TD); } } } } else { oj.TableRendererUtils.tableBodyRowDefaultRenderer(this, rowIdx, row, context); } }, /** * Refresh the table footer * @private */ _refreshTableFooter: function() { var columns = this._getColumnDefs(); var tableFooter = this._getTableDomUtils().getTableFooter(); if (!tableFooter) { if (this._isTableFooterless()) { return; } else { // metadata could have been updated to add column headers tableFooter = this._getTableDomUtils().createTableFooter(); this._getTableDomUtils().styleTableFooter(tableFooter); } } var tableFooterRow = this._getTableDomUtils().getTableFooterRow(); // remove all the existing footer cells tableFooterRow.empty(); if (columns && columns.length > 0) { this._getTableDomUtils().createTableFooterAccSelect(tableFooterRow); var i, column, footerRenderer, footerCell, footerCellContent, columnsCount = columns.length; for (i = 0; i < columnsCount; i++) { column = columns[i]; footerRenderer = this._getColumnRenderer(i, 'footer'); footerCell = this._getTableDomUtils().createTableFooterCell(i, this._getColumnSelectionMode()); this._getTableDomUtils().styleTableFooterCell(i, footerCell); this._getTableDomUtils().insertTableFooterCell(i, footerCell); if (footerRenderer) { // if footerRenderer is defined then call that var footerContext = oj.TableRendererUtils.getRendererContextObject(this, footerCell[0], {}); // Copy additional properties to top-level context to work with custom element var context = {'footerContext': footerContext, 'columnIndex': i, 'componentElement': footerContext['componentElement'], 'parentElement': footerContext['parentElement']} footerCellContent = footerRenderer(context); if (footerCellContent != null) { // if the renderer returned a value then we set it as the content // for the footer cell footerCell.empty(); footerCell.append(footerCellContent); //@HTMLUpdateOK } else { // if the renderer didn't return a value then the existing // footer cell was manipulated. So get it and set the required // attributes just in case it was replaced or the attributes // got removed footerCell = $(tableFooterRow.children(':not(.' + oj.TableDomUtils.CSS_CLASSES._HIDDEN_CONTENT_ACC_CLASS + ')')[i]); this._getTableDomUtils().styleTableFooterCell(i, footerCell, this._getColumnSelectionMode()); } } } } }, /** * Refresh the table header * @private */ _refreshTableHeader: function() { var self = this; var columns = this._getColumnDefs(); var tableHeader = this._getTableDomUtils().getTableHeader(); if (!tableHeader) { if (this._isTableHeaderless()) { return; } else { // metadata could have been updated to add column headers tableHeader = this._getTableDomUtils().createTableHeader(); this._getTableDomUtils().styleTableHeader(tableHeader); } } var tableHeaderRow = this._getTableDomUtils().getTableHeaderRow(); this._unregisterChildStateListeners(tableHeaderRow); // remove all the existing column headers tableHeaderRow.empty(); if (columns && columns.length > 0) { var tableHeaderAccSelectRowColumn = this._getTableDomUtils().createTableHeaderAccSelectRowColumn(); tableHeaderRow.append(tableHeaderAccSelectRowColumn); //@HTMLUpdateOK var i, j, column, headerRenderer, headerColumn, headerColumnContent, headerContext, context, columnsCount = columns.length; for (i = 0; i < columnsCount; i++) { column = columns[i]; headerRenderer = this._getColumnRenderer(i, 'header'); headerColumn = this._getTableDomUtils().createTableHeaderColumn(i, this._getColumnSelectionMode()); if (headerRenderer) { // if headerRenderer is defined then call that headerContext = oj.TableRendererUtils.getRendererContextObject(this, headerColumn[0], {}); // Copy additional properties to top-level context to work with custom element context = {'headerContext': headerContext, 'columnIndex': i, 'data': column['headerText'], 'componentElement': headerContext['componentElement'], 'parentElement': headerContext['parentElement']}; if (column.sortable == oj.TableDomUtils._OPTION_ENABLED) { // add the sortable icon renderer context['columnHeaderSortableIconRenderer'] = function(options, delegateRenderer) { oj.TableRendererUtils.columnHeaderSortableIconRenderer(self, this, options, delegateRenderer); } } else { context['columnHeaderDefaultRenderer'] = function(options, delegateRenderer) { oj.TableRendererUtils.columnHeaderDefaultRenderer(self, this, options, delegateRenderer); } } headerColumnContent = headerRenderer(context); if (headerColumnContent != null) { // if the renderer returned a value then we set it as the content // for the headerColumn headerColumn.empty(); headerColumn.append(headerColumnContent); //@HTMLUpdateOK } else { // if the renderer didn't return a value then the existing // headerColumn was manipulated. So get it and set the required // attributes just in case it was replaced or the attributes // got removed headerColumn = $(tableHeaderRow.children(':not(' + '.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ACC_SELECT_ROW_CLASS + ')')[i]); this._getTableDomUtils().setTableHeaderColumnAttributes(i, headerColumn); this._getTableDomUtils().styleTableHeaderColumn(i, headerColumn, this._getColumnSelectionMode(), false); } } // set the acc column selection checkbox this._getTableDomUtils().createTableHeaderColumnAccSelect(i, this._getColumnSelectionMode()); } this._renderedTableHeaderColumns = true; } }, /** * Refresh the status message * @private */ _refreshTableStatusMessage: function() { var tableStatusMessage = this._getTableDomUtils().getTableStatusMessage(); if (tableStatusMessage != null) { tableStatusMessage.remove(); } this._getTableDomUtils().createTableStatusMessage(); }, /** * Register the events which will be published by the table component. * @private */ _registerCustomEvents: function() { var jqEvent = (/** @type {{special: Object}} */($.event)); var jqEventSpecial = jqEvent['special']; // ojtablebeforecurrentrow handlers will be passed an object which contains the // old and new current row jqEventSpecial['ojtablebeforecurrentrow'] = { /** * Handle event * @param {{handleObj: {handler: {apply: Function}}}} event * @private */ handle: function(event) { var handleObj = event['handleObj']; return handleObj['handler'].apply(this, [event, arguments[1]]); } }; // ojtablesort handlers will be passed an object which contains the // header and direction jqEventSpecial['ojtablesort'] = { /** * Handle event * @param {{handleObj: {handler: {apply: Function}}}} event * @private */ handle: function(event) { var handleObj = event['handleObj']; return handleObj['handler'].apply(this, [event, arguments[1]]); } }; }, /** * Register event listeners which need to be registered datasource. * @private */ _registerDataSourceEventListeners: function() { // register the listeners on the datasource var data = this._getData(); if (data != null) { this._unregisterDataSourceEventListeners(); this._dataSourceEventHandlers = []; this._dataSourceEventHandlers.push({'eventType': oj.TableDataSource.EventType['REQUEST'], 'eventHandler': this._handleDataFetchStart.bind(this)}); this._dataSourceEventHandlers.push({'eventType': oj.TableDataSource.EventType['SYNC'], 'eventHandler': this._handleDataFetchEnd.bind(this)}); this._dataSourceEventHandlers.push({'eventType': oj.TableDataSource.EventType['SORT'], 'eventHandler': this._handleDataSort.bind(this)}); this._dataSourceEventHandlers.push({'eventType': oj.TableDataSource.EventType['ADD'], 'eventHandler': this._handleDataRowAdd.bind(this)}); this._dataSourceEventHandlers.push({'eventType': oj.TableDataSource.EventType['REMOVE'], 'eventHandler': this._handleDataRowRemove.bind(this)}); this._dataSourceEventHandlers.push({'eventType': oj.TableDataSource.EventType['CHANGE'], 'eventHandler': this._handleDataRowChange.bind(this)}); this._dataSourceEventHandlers.push({'eventType': oj.TableDataSource.EventType['REFRESH'], 'eventHandler': this._handleDataRefresh.bind(this)}); this._dataSourceEventHandlers.push({'eventType': oj.TableDataSource.EventType['RESET'], 'eventHandler': this._handleDataReset.bind(this)}); this._dataSourceEventHandlers.push({'eventType': oj.TableDataSource.EventType['ERROR'], 'eventHandler': this._handleDataError.bind(this)}); var i; var ev, dataSourceEventHandlersCount = this._dataSourceEventHandlers.length; for (i = 0; i < dataSourceEventHandlersCount; i++) { ev = data.on(this._dataSourceEventHandlers[i]['eventType'], this._dataSourceEventHandlers[i]['eventHandler']); if (ev) { this._dataSourceEventHandlers[i]['eventHandler'] = ev; } } } }, /** * Register event listeners which need to be registered directly on * the DOM element. * @private */ _registerDomEventListeners: function() { if (this._getTableDomUtils().getScroller() != null) { // if width or height is defined then we can have scrollbars so register scroll event listeners this._getTableDomUtils().getScroller().scroll((function(event) { this._handleScrollerScrollLeft(this._getTableDomUtils().getScrollLeft(event.target)); }).bind(this)); } }, /** * Register the DOM Scroller. * @private */ _registerDomScroller: function() { var self = this; if (this._domScroller != null) { this._domScroller.destroy(); } this._domScrollerMaxCountFunc = function(result) { if (result != null) { if (result['maxCountLimit']) { self._handleScrollerMaxRowCount(); } } }; this._domScroller = new oj.DomScroller(this._getTableDomUtils().getScroller(), this._getData(), {'fetchSize' : this.options['scrollPolicyOptions']['fetchSize'], 'maxCount' : this.options['scrollPolicyOptions']['maxCount'], 'success': this._domScrollerMaxCountFunc}); }, /** * Register event listeners for resize the container DOM element. * @private */ _registerResizeListener: function() { var element = this._getTableDomUtils().getTableContainer(); if (!this._resizeListener) { var self = this; this._resizeListener = function(width, height) { var tableContainerHeight = self._getTableDomUtils().getTableContainer().outerHeight(); var tableContainerWidth = self._getTableDomUtils().getTableContainer().outerWidth(); self._getTableDomUtils().refreshTableDimensions(tableContainerWidth, tableContainerHeight); }; } if (!this._isResizeListenerAdded) { oj.DomUtils.addResizeListener(element[0], this._resizeListener, 50); this._isResizeListenerAdded = true; } }, /** * Remove a keyCode from our internal list of pressed keys. This is done on keyup. * @private */ _removeKeyboardKey: function(keyCode) { var keyboardKeys = this._getKeyboardKeys(); var i, keyboardKeysCount = keyboardKeys.length; for (i = 0; i < keyboardKeysCount; i++) { if (keyboardKeys[i] == keyCode) { keyboardKeys.splice(i, 1); } } }, /** * Scroll column into viewport * @param {number} columnIdx row index * @private */ _scrollColumnIntoViewport: function(columnIdx) { var isRTL = (this._GetReadingDirection() === "rtl"); var tableBody = this._getTableDomUtils().getTableBody(); var tableHeaderColumn = this._getTableDomUtils().getTableHeaderColumn(columnIdx); if (!tableHeaderColumn) { return; } var scrollbarWidth = this._getTableDomUtils().getScrollbarWidth(); var headerColumnRect = tableHeaderColumn.get(0).getBoundingClientRect(); var tableBodyRect = tableBody.get(0).getBoundingClientRect(); var scrolledLeft = false; if (isRTL) { if (headerColumnRect.left < tableBodyRect.left + scrollbarWidth) { var scrollLeftDiff = tableBodyRect.left - headerColumnRect.left + scrollbarWidth; if (!this._getTableDomUtils()._isIE()) { scrollLeftDiff = -1 * scrollLeftDiff; } tableBody.scrollLeft(tableBody.scrollLeft() + scrollLeftDiff); scrolledLeft = true; } if (headerColumnRect.right > tableBodyRect.right && !scrolledLeft) { var scrollLeftDiff = headerColumnRect.right - tableBodyRect.right; if (!this._getTableDomUtils()._isIE()) { scrollLeftDiff = -1 * scrollLeftDiff; } tableBody.scrollLeft(tableBody.scrollLeft() - scrollLeftDiff); } } else { if (headerColumnRect.left < tableBodyRect.left) { var scrollLeftDiff = tableBodyRect.left - headerColumnRect.left; tableBody.scrollLeft(tableBody.scrollLeft() - scrollLeftDiff); scrolledLeft = true; } if (headerColumnRect.right > tableBodyRect.right - scrollbarWidth && !scrolledLeft) { var scrollLeftDiff = headerColumnRect.right - tableBodyRect.right + scrollbarWidth; tableBody.scrollLeft(tableBody.scrollLeft() + scrollLeftDiff); } } }, /** * Scroll row into viewport * @param {number} rowIdx row index * @private */ _scrollRowIntoViewport: function(rowIdx) { var tableBodyRow = this._getTableDomUtils().getTableBodyRow(rowIdx); var scrollbarHeight = this._getTableDomUtils().getScrollbarHeight(); var rowRect = tableBodyRow.get(0).getBoundingClientRect(); var scrollingElement = this._getTableDomUtils().getScroller(); var scrollingElementRect = scrollingElement.get(0).getBoundingClientRect(); var scrolledDown = false; if (rowRect.bottom > scrollingElementRect.bottom - scrollbarHeight) { var scrollTopDiff = rowRect.bottom - scrollingElementRect.bottom + scrollbarHeight; scrollingElement.scrollTop(scrollingElement.scrollTop() + scrollTopDiff); scrolledDown = true; } if (rowRect.top < scrollingElementRect.top && !scrolledDown) { var scrollTopDiff = scrollingElementRect.top - rowRect.top; scrollingElement.scrollTop(scrollingElement.scrollTop() - scrollTopDiff); } }, /** * Update the current row. If called with null then resets the currentRow. * If index/key argument is specified then sets the current row. A beforecurrentrow * event is fired before the current row is changed. If that event results in * an error then the current row will not be changed. * @param {Object} currentRow current row * @param {Object} event * @param {boolean} optionChange whether it was invoked through an optionChange call * @return {boolean} whether setting the current row was successful * @throws {Error} * @private */ _setCurrentRow: function(currentRow, event, optionChange) { var existingCurrentRow = this._currentRow; var tableBodyRow, existingCurrentRowIndex, existingCurrentRowKey, existingCurrentRowIdx; var updateCurrentRow = true; if (currentRow == null) { if (existingCurrentRow != null) { try { updateCurrentRow = this._trigger('beforeCurrentRow', event, {'currentRow': null, 'previousCurrentRow': this._currentRow}); } catch (err) { // caught an error. Do not change current row var errSummary = this._LOGGER_MSG._ERR_PRECURRENTROW_ERROR_SUMMARY; var errDetail = oj.Translations.applyParameters(this._LOGGER_MSG._ERR_PRECURRENTROW_ERROR_DETAIL, {'error': err.toString()}); oj.Logger.info(errSummary + '\n' + errDetail); // do not update the currentRow to the new value if an exception was caught return false; } if (!updateCurrentRow) { // do not update the currentRow to the new value if a listener returned false return false; } existingCurrentRowIndex = existingCurrentRow['rowIndex']; existingCurrentRowKey = this._getRowKeyForDataSourceRowIndex(existingCurrentRowIndex); existingCurrentRowIdx = this._getRowIdxForRowKey(existingCurrentRowKey); var updateEditable = this._setTableEditable(false, false, 0, true, event); if (updateEditable === false) { this._currentRow = existingCurrentRow; var currentFocusElement = document.activeElement; var columnIdx = this._getTableDomUtils().getElementColumnIdx(currentFocusElement); var self = this; this._queueTask(function() { var focusRowIdx = existingCurrentRowIdx; var focusColumnIdx = columnIdx; setTimeout(function(){self._setCellFocus(focusRowIdx, focusColumnIdx)}, 0); }); // do not update the currentRow to the new value if updateEditable returned false return false; } this._currentRow = null; this.option('currentRow', null, {'_context': {writeback: true, originalEvent:event, internalSet: true}}); if (event == null) { this._setRowFocus(-1, true, false, null, event); } tableBodyRow = this._getTableDomUtils().getTableBodyRow(existingCurrentRowIdx); if (tableBodyRow != null) { tableBodyRow.removeClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_CURRENT_ROW_CLASS); } } return true; } var data = this._getData(); var rowIndex = currentRow['rowIndex']; var rowIdx; var rowKey = currentRow['rowKey']; if (rowKey == null) { rowKey = this._getRowKeyForDataSourceRowIndex(rowIndex); } if (rowIndex == null) { rowIndex = this._getDataSourceRowIndexForRowKey(rowKey); } rowIdx = this._getRowIdxForRowKey(rowKey); currentRow = {'rowIndex': rowIndex, 'rowKey': rowKey}; if (rowIdx != -1 && (!data || data.totalSize() == 0 || rowIdx < -1 || rowIdx === null || rowKey === null)) { var errSummary = this._LOGGER_MSG._ERR_CURRENTROW_UNAVAILABLE_INDEX_SUMMARY; var errDetail = oj.Translations.applyParameters(this._LOGGER_MSG._ERR_CURRENTROW_UNAVAILABLE_INDEX_DETAIL, {'rowIdx': rowIdx}); if (optionChange) { // Only throw an Error if the current row was set through option change // so that the caller can be notified of the invalid row. throw new Error(errSummary + '\n' + errDetail); } else { oj.Logger.info(errSummary + '\n' + errDetail); } // do not update the currentRow return false; } var currentFocusedRowIdx = this._getFocusedRowIdx(); var currentRowChanged = !oj.Object.compareValues(this._currentRow, currentRow); if (currentRowChanged) { try { updateCurrentRow = this._trigger('beforeCurrentRow', event, {'currentRow': {'rowIndex': rowIndex, 'rowKey': rowKey}, 'previousCurrentRow': this._currentRow}); } catch (err) { // caught an error. Do not change current row var errSummary = this._LOGGER_MSG._ERR_PRECURRENTROW_ERROR_SUMMARY; var errDetail = oj.Translations.applyParameters(this._LOGGER_MSG._ERR_PRECURRENTROW_ERROR_DETAIL, {'error': err.toString()}); oj.Logger.info(errSummary + '\n' + errDetail); // do not update the currentRow to the new value if an exception was caught return false; } if (!updateCurrentRow) { // do not update the currentRow to the new value if a listener returned false return false; } this._currentRow = {'rowIndex': rowIndex, 'rowKey': rowKey}; if (existingCurrentRow != null) { existingCurrentRowIndex = existingCurrentRow['rowIndex']; existingCurrentRowKey = this._getRowKeyForDataSourceRowIndex(existingCurrentRowIndex); existingCurrentRowIdx = this._getRowIdxForRowKey(existingCurrentRowKey); } var updateEditable = this._setTableEditable(false, false, 0, true, event); if (updateEditable === false) { this._currentRow = existingCurrentRow; var currentFocusElement = document.activeElement; var columnIdx = this._getTableDomUtils().getElementColumnIdx(currentFocusElement); var self = this; this._queueTask(function() { var focusRowIdx = existingCurrentRowIdx; var focusColumnIdx = columnIdx; setTimeout(function(){self._setCellFocus(focusRowIdx, focusColumnIdx)}, 0); }); // do not update the currentRow to the new value if updateEditable returned false return false; } this.option('currentRow', this._currentRow, {'_context': {writeback: true, originalEvent:event, internalSet: true}}); tableBodyRow = this._getTableDomUtils().getTableBodyRow(rowIdx); if (tableBodyRow != null) { tableBodyRow.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_CURRENT_ROW_CLASS); } if (existingCurrentRow != null) { tableBodyRow = this._getTableDomUtils().getTableBodyRow(existingCurrentRowIdx); if (tableBodyRow != null) { tableBodyRow.removeClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_CURRENT_ROW_CLASS); } } } if (currentRowChanged || currentFocusedRowIdx != currentRow['rowIndex']) { if (event == null) { this._setRowFocus(rowIdx, true, false, null, event); } } return true; }, /** * Set waiting state and show the Fetching Data... status message. * @private */ _setDataWaitingState: function() { this._showStatusMessage(); this._hideNoDataMessage(); this._dataFetching = true; if (!this._dataResolveFunc) { this._dataResolveFunc = this._addComponentBusyState('is waiting for data.'); } }, /** * Set focus on a cell * @param {number} rowIdx row index * @param {number} columnIdx column index * @return {boolean} whether setting the cell focus was successful * @private */ _setCellFocus: function(rowIdx, columnIdx) { var tableBodyCell = this._getTableDomUtils().getTableBodyCell(rowIdx, columnIdx); var self = this; var focused = false; tableBodyCell.find('*').each(function() { if (!focused) { if ($(this).is(':focusable')) { this.focus(); focused = $(this).is(':focus'); } } }); return focused; }, /** * Try setting focus in the cell. If unsuccesful, set focus on the first focusable cell in the row * if forwardSearch is true. Else try from the last cell in the row. * @param {number} rowIdx row index * @param {number} columnIdx column index * @param {boolean} forwardSearch try setting focus starting at the first column * @private */ _setCellInRowFocus: function(rowIdx, columnIdx, forwardSearch) { if (this._setCellFocus(rowIdx, columnIdx)) { return; } var tableBodyCells = this._getTableDomUtils().getTableBodyCells(rowIdx); if (!tableBodyCells) { return; } var i, tableBodyCellIndex, tableBodyCellsCount = tableBodyCells.length; for (i = 0; i < tableBodyCellsCount; i++) { tableBodyCellIndex = i; if (!forwardSearch) { tableBodyCellIndex = tableBodyCellsCount - i - 1; } if (this._setCellFocus(rowIdx, tableBodyCellIndex)) { return; } } }, /** * Called by component to declare rendering is not finished. This method currently * handles the ready state for the component page level BusyContext * @private */ _setComponentNotReady : function() { // For page level BusyContext // If we've already registered a busy state with the page's busy context, don't need to do anything further if (!this._readyResolveFunc) { this._readyResolveFunc = this._addComponentBusyState('is being loaded.'); } }, /** * Called by component to declare rendering is finished. This method currently * handles the page level BusyContext. * @private */ _setComponentReady : function() { if (this._readyResolveFunc) { this._readyResolveFunc(); this._readyResolveFunc = null; } }, /** * Set the editable row index * @param {number} rowIdx row index * @private */ _setEditableRowIdx: function(rowIdx) { // store the rowKey so we can restore easily after sort this._editableRowKey = this._getRowKeyForRowIdx(rowIdx); this._editableRowIdx = rowIdx; }, /** * Set focus on column header * @param {number} columnIdx column index * @param {boolean} focused whether it's focused * @param {boolean} clearSelectedRows whether to clear the selected rows * @param {Object} event * @private */ _setHeaderColumnFocus: function(columnIdx, focused, clearSelectedRows, event) { var element = null; if (event != null) { element = event.currentTarget; } if (focused) { var focusedHeaderColumnIdx = this._getFocusedHeaderColumnIdx(); if (focusedHeaderColumnIdx != null && focusedHeaderColumnIdx != columnIdx) { this._setHeaderColumnFocus(focusedHeaderColumnIdx, false, false, event); } // clear focused row this._clearFocusedRow(true); // clear selected rows if (clearSelectedRows) { this._clearSelectedRows(); } // scroll column into view this._scrollColumnIntoViewport(columnIdx); this._activeColumnIndex = columnIdx; } this._setHeaderColumnState(columnIdx, {focused: focused}, element); }, /** * Set selection on column header * @param {number} columnIdx column index * @param {boolean} selected whether it's focused * @param {jQuery} element DOM element which triggered the column header selection * @param {Object} event * @param {boolean} updateSelection whether to update the selection * @private */ _setHeaderColumnSelection: function(columnIdx, selected, element, event, updateSelection) { if (this._getColumnSelectionMode() == this._OPTION_SELECTION_MODES._SINGLE || this._getColumnSelectionMode() == this._OPTION_SELECTION_MODES._MULTIPLE) { if (isNaN(columnIdx) || columnIdx < 0) { // validate value oj.Logger.error('Error: Invalid column selection value: ' + columnIdx); } // if we have single selection then clear any existing selections if (this._getColumnSelectionMode() == this._OPTION_SELECTION_MODES._SINGLE && selected) { this._clearSelectedHeaderColumns(); } this._setHeaderColumnState(columnIdx, {selected: selected}, element, event); // save it this._setLastHeaderColumnSelection(columnIdx, selected); // update the acc checkbox var accSelectionColumn = this._getTableDomUtils().getTableHeaderColumnAccSelect(columnIdx); var accSelectCheckbox = $(accSelectionColumn.children('.' + oj.TableDomUtils.CSS_CLASSES._CHECKBOX_ACC_SELECT_COLUMN_CLASS)[0]); accSelectCheckbox.prop('checked', selected); if (updateSelection) { var selection = this._getSelection(); var existingSelection = this['options']['selection']; this.option('selection', selection, {'_context': {writeback: true, internalSet: true}}); } } }, /** * Set the state of the column header. e.g., focused, selected, etc. * @param {number} columnIdx column index * @param {Object} state Object which contains whether it's focused or selected * @param {jQuery} element DOM element which triggered the column header state * @param {Object} event * @private */ _setHeaderColumnState: function(columnIdx, state, element, event) { var headerColumn = this._getTableDomUtils().getTableHeaderColumn(columnIdx); if (!headerColumn) { return; } var focused = state.focused; var selected = state.selected; if (selected != null) { var headerColumnSelected = headerColumn.hasClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._SELECTED); if (headerColumnSelected != selected) { if (!selected) { headerColumn.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._SELECTED); } else { headerColumn.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._SELECTED); } } } if (focused != null) { if (!focused) { headerColumn.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._FOCUS); this._hideTableHeaderColumnSortLink(columnIdx, true); this._hideTableHeaderColumnSortLink(columnIdx, false); } else { headerColumn.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._FOCUS); this._showTableHeaderColumnSortLink(columnIdx); } } this._updateHeaderColumnStateCellsClass(columnIdx); }, /** * Set the last column which was selected (chronologically) * @param {number} columnIdx column index * @param {boolean} selected whether it's selected * @private */ _setLastHeaderColumnSelection: function(columnIdx, selected) { if (!this._lastSelectedColumnIdxArray) { this._lastSelectedColumnIdxArray = []; } var i, lastSelectedColumnIdxArrayCount = this._lastSelectedColumnIdxArray.length; for (i = 0; i < lastSelectedColumnIdxArrayCount; i++) { if (this._lastSelectedColumnIdxArray[i] == columnIdx) { this._lastSelectedColumnIdxArray.splice(i, 1); break; } } if (selected) { this._lastSelectedColumnIdxArray.push(columnIdx); } }, /** * Set the last row which was selected (chronologically) * @param {number} rowIdx row index * @param {boolean} selected whether it's selected * @private */ _setLastRowSelection: function(rowIdx, selected) { if (!this._lastSelectedRowIdxArray) { this._lastSelectedRowIdxArray = []; } var i, lastSelectedRowIdxArrayCount = this._lastSelectedRowIdxArray.length; for (i = 0; i < lastSelectedRowIdxArrayCount; i++) { if (this._lastSelectedRowIdxArray[i] == rowIdx) { this._lastSelectedRowIdxArray.splice(i, 1); break; } } if (selected) { this._lastSelectedRowIdxArray.push(rowIdx); } }, /** * Set the next row to editable * @param {number} columnIdx column index * @param {Object} event * @throws {Error} * @private */ _setNextRowEditable: function(columnIdx, event) { var tableBodyRows = this._getTableDomUtils().getTableBodyRows(); var rowCount = tableBodyRows != null ? tableBodyRows.length : 0; var editableRowIdx = this._getEditableRowIdx(); if (editableRowIdx >= 0 && editableRowIdx < rowCount - 1) { this._setTableEditable(false, false, columnIdx, true, event); this._setCurrentRow({'rowIndex': editableRowIdx + 1}, event, false); this._setTableEditable(true, false, columnIdx, true, event); } else if (editableRowIdx === rowCount - 1) { this._setTableEditable(false, false, columnIdx, true, event); this._getTableDomUtils().getTable().focus(); } }, /** * Set the previous row to editable * @param {number} columnIdx column index * @param {Object} event * @throws {Error} * @private */ _setPreviousRowEditable: function(columnIdx, event) { var editableRowIdx = this._getEditableRowIdx(); if (editableRowIdx >= 1) { this._setTableEditable(false, false, columnIdx, false, event); this._setCurrentRow({'rowIndex': editableRowIdx - 1}, event, false); this._setTableEditable(true, false, columnIdx, false, event); } else if (editableRowIdx === 0) { this._setTableEditable(false, false, columnIdx, false, event); this._getTableDomUtils().getTable().focus(); } }, /** * Set focus on row * @param {number} rowIdx row index * @param {boolean} focused whether it's focused * @param {boolean} updateCurrentRow whether to update the currentRow * @param {jQuery} element DOM element which triggered the row focus * @param {Object} event * @return {boolean} whether setting the row focus was successful * @private */ _setRowFocus: function(rowIdx, focused, updateCurrentRow, element, event) { if (rowIdx == -1) { var focusedRowIdx = this._getFocusedRowIdx(); if (focusedRowIdx != null) { this._setRowFocus(focusedRowIdx, false, updateCurrentRow, null, null); } if (updateCurrentRow) { var updateRowFocus = this._setCurrentRow(null, event, false); if (!updateRowFocus) { return false; } } return true; } var tableBodyRow = this._getTableDomUtils().getTableBodyRow(rowIdx); if (!tableBodyRow) { return false; } if (focused) { var focusedRowIdx = this._getFocusedRowIdx(); if (focusedRowIdx != null && focusedRowIdx != rowIdx) { this._setRowFocus(focusedRowIdx, false, updateCurrentRow, element, null); } if (updateCurrentRow) { var rowKey = this._getRowKeyForRowIdx(rowIdx); var updateRowFocus = this._setCurrentRow({'rowKey': rowKey}, event, false); if (!updateRowFocus) { return false; } } tableBodyRow.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._FOCUS); this._scrollRowIntoViewport(rowIdx); // clear any hover on the row this._updateRowStateCellsClass(rowIdx, {focused: true, hover: false}); // clear any focused column header this._clearFocusedHeaderColumn(); // clear any selected column header this._clearSelectedHeaderColumns(); // unset table actionable mode this._setTableActionableMode(false); } else { tableBodyRow.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._FOCUS); } // update focus style for the cells this._updateRowStateCellsClass(rowIdx, {focused: focused}); return true; }, /** * Set selection on row * @param {number} rowIdx column index * @param {boolean} selected whether it's selected * @param {jQuery} element DOM element which triggered the row selection * @param {Object} event * @param {boolean} updateSelection whether to update the selection * @private */ _setRowSelection: function(rowIdx, selected, element, event, updateSelection) { if (this._getRowSelectionMode() == this._OPTION_SELECTION_MODES._SINGLE || this._getRowSelectionMode() == this._OPTION_SELECTION_MODES._MULTIPLE) { if (isNaN(rowIdx) || rowIdx < 0) { // validate value oj.Logger.error('Error: Invalid row selection value: ' + rowIdx); } // if we have single selection then clear any existing selections if (this._getRowSelectionMode() == this._OPTION_SELECTION_MODES._SINGLE && selected) { this._clearSelectedRows(); } var tableBodyRow = this._getTableDomUtils().getTableBodyRow(rowIdx); if (tableBodyRow != null) { var selectionChanged = false; var rowSelected = tableBodyRow.hasClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._SELECTED); if (rowSelected != selected) { if (!selected) { tableBodyRow.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._SELECTED); } else { tableBodyRow.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._SELECTED); } selectionChanged = true; // Set the draggable property on the row element if the dnd.drag.rows option is specified var dragOption = this.options['dnd']['drag']; if (dragOption && (dragOption === 'rows' || dragOption.rows)) { tableBodyRow.prop("draggable", selected); } } if (selectionChanged) { // if selection was set then we want to override // the default style precedence if (selected) { this._updateRowStateCellsClass(rowIdx, {hover: false, focused: false, selected: true}); } else { this._updateRowStateCellsClass(rowIdx, {selected: false}); } } // save it this._setLastRowSelection(rowIdx, selected); // update the acc checkbox var accSelectionCell = this._getTableDomUtils().getTableBodyCellAccSelect(tableBodyRow); var accSelectCheckbox = $(accSelectionCell.children('.' + oj.TableDomUtils.CSS_CLASSES._CHECKBOX_ACC_SELECT_ROW_CLASS)[0]); accSelectCheckbox.prop('checked', selected); if (updateSelection) { var selection = this._getSelection(); this.option('selection', selection, {'_context': {writeback: true, internalSet: true}}); } } } }, /** * Sets selection * @param {Object} selection * @private */ _setSelection: function(selection) { if (selection == null) { this._clearSelectedRows(); this._clearSelectedHeaderColumns(); return; } // we need to set the selection var i, j, rangeObj, startRowKey, endRowKey, startRowIndex, endRowIndex, startRowIdx, endRowIdx, startColumnIdx, endColumnIdx, updateSelection, selectionCount = selection.length; for (i = 0; i < selectionCount; i++) { rangeObj = selection[i]; if ((rangeObj['startKey'] == null && rangeObj[this._CONST_STARTINDEX] == null) || (rangeObj['endKey'] == null && rangeObj[this._CONST_ENDINDEX] == null)) { oj.Logger.error('Error: Invalid range object in selection. Both start and end objects must be specified'); return null; } startRowKey = null; endRowKey = null; startRowIndex = null; endRowIndex = null; startRowIdx = null; endRowIdx = null; startColumnIdx = null; endColumnIdx = null; updateSelection = false; // if keys are specified, we get the index from the key if (rangeObj['startKey'] != null && rangeObj['startKey'][this._CONST_ROW] != null) { startRowIndex = this._getDataSourceRowIndexForRowKey(rangeObj['startKey'][this._CONST_ROW]); if (rangeObj[this._CONST_STARTINDEX] != null && rangeObj[this._CONST_STARTINDEX][this._CONST_ROW] != null && startRowIndex != rangeObj[this._CONST_STARTINDEX][this._CONST_ROW]) { updateSelection = true; } } if (rangeObj['endKey'] != null && rangeObj['endKey'][this._CONST_ROW] != null) { endRowIndex = this._getDataSourceRowIndexForRowKey(rangeObj['endKey'][this._CONST_ROW]); if (rangeObj[this._CONST_ENDINDEX] != null && rangeObj[this._CONST_ENDINDEX][this._CONST_ROW] != null && endRowIndex != rangeObj[this._CONST_ENDINDEX][this._CONST_ROW]) { updateSelection = true; } } if (rangeObj['startKey'] != null && rangeObj['startKey'][this._CONST_COLUMN] != null) { startColumnIdx = this._getColumnIdxForColumnKey(rangeObj['startKey'][this._CONST_COLUMN]); if (rangeObj[this._CONST_STARTINDEX] != null && rangeObj[this._CONST_STARTINDEX][this._CONST_COLUMN] != null && startColumnIdx != rangeObj[this._CONST_STARTINDEX][this._CONST_COLUMN]) { updateSelection = true; } } if (rangeObj['endKey'] != null && rangeObj['endKey'][this._CONST_COLUMN] != null) { endColumnIdx = this._getColumnIdxForColumnKey(rangeObj['endKey'][this._CONST_COLUMN]); if (rangeObj[this._CONST_ENDINDEX] != null && rangeObj[this._CONST_ENDINDEX][this._CONST_COLUMN] != null && endColumnIdx != rangeObj[this._CONST_ENDINDEX][this._CONST_COLUMN]) { updateSelection = true; } } if (startRowIndex == null && rangeObj[this._CONST_STARTINDEX] != null) { startRowIndex = rangeObj[this._CONST_STARTINDEX][this._CONST_ROW]; } if (endRowIndex == null && rangeObj[this._CONST_ENDINDEX] != null) { endRowIndex = rangeObj[this._CONST_ENDINDEX][this._CONST_ROW]; } if (startColumnIdx == null && rangeObj[this._CONST_STARTINDEX] != null) { startColumnIdx = rangeObj[this._CONST_STARTINDEX][this._CONST_COLUMN]; } if (endColumnIdx == null && rangeObj[this._CONST_ENDINDEX] != null) { endColumnIdx = rangeObj[this._CONST_ENDINDEX][this._CONST_COLUMN]; } if (startRowIndex != null && endRowIndex != null && startColumnIdx != null && endColumnIdx != null) { oj.Logger.error('Error: Invalid range object in selection - Can only support row or column selection. Not both'); return null; } if (startRowIndex != null && startRowIndex >= 0 && endRowIndex != null && endRowIndex >= 0) { // this is a row based selection startRowKey = this._getRowKeyForDataSourceRowIndex(startRowIndex); endRowKey = this._getRowKeyForDataSourceRowIndex(endRowIndex); startRowIdx = this._getRowIdxForRowKey(startRowKey); endRowIdx = this._getRowIdxForRowKey(endRowKey); for (j = startRowIdx; j <= endRowIdx; j++) { try { this._setRowSelection(j, true, null, null, updateSelection); } catch (e) { oj.Logger.error('Error: ' + e); } } } else if (startColumnIdx != null && endColumnIdx != null) { // this is a column based selection for (j = startColumnIdx; j <= endColumnIdx; j++) { try { this._setHeaderColumnSelection(j, true, null, null, updateSelection); } catch (e) { oj.Logger.error('Error: ' + e); } } } else { oj.Logger.error('Error: Invalid range object in selection - \n start row: ' + startRowIndex + '\n' + 'end row: ' + endRowIndex+ '\n' + 'start column: ' + startColumnIdx + '\n' + 'end column: ' + endColumnIdx); return null; } } }, /** * Set whether the component is in table actionable mode * @param {boolean} value true or false * @private */ _setTableActionableMode: function(value) { // only set actionable mode is there are any tabbable elements in the row if (value) { var focusedRowIdx = this._getFocusedRowIdx(); var focusedHeaderColumnIdx = this._getFocusedHeaderColumnIdx(); if (focusedRowIdx != null || focusedHeaderColumnIdx != null) { var focusedElement = null; if (focusedRowIdx != null) { focusedElement = this._getTableDomUtils().getTableBodyRow(focusedRowIdx); } else { focusedElement = this._getTableDomUtils().getTableHeaderColumn(focusedHeaderColumnIdx); } if (focusedElement != null) { var tabbableElementsInFocusedElement = this._getTabbableElements(focusedElement); if (tabbableElementsInFocusedElement != null && tabbableElementsInFocusedElement.length > 0) { this._tableActionableMode = value; // set focus on the first tabbable element tabbableElementsInFocusedElement[0].focus(); } } } } else { this._tableActionableMode = value; } }, /** * Set the table editable * @param {boolean} editable true if editable, false otherwise * @param {boolean} cancelled true if edit was cancelled * @param {number} columnIdx column index * @param {boolean} forwardSearch try setting focus starting at the first column * @param {Object} event * @private */ _setTableEditable: function(editable, cancelled, columnIdx, forwardSearch, event) { if (!this._isTableEditMode()) { return; } var currentRow = this._getCurrentRow(); if (currentRow != null) { var rowKey = currentRow['rowKey']; var rowIdx = this._getRowIdxForRowKey(rowKey); var updateEditMode; try { if (editable && !this._hasEditableRow()) { // fire the beforeEdit event if there are no existing editable rows // and we are starting edit on a row var tableBodyRow = this._getTableDomUtils().getTableBodyRow(rowIdx); var rowContext = oj.TableRendererUtils.getRendererContextObject(this, tableBodyRow[0], {'row': {key: rowKey, index: currentRow['rowIndex']}, 'isCurrentRow': true}); updateEditMode = this._trigger('beforeRowEdit', event, {'rowContext': rowContext}); } else if (!editable && this._hasEditableRow()) { // only trigger the beforeRowEditEnd if we are actually ending an edit // fire on the edited row var tableBodyRow = this._getTableDomUtils().getTableBodyRow(this._getEditableRowIdx()); rowKey = this._getRowKeyForRowIdx(this._getEditableRowIdx()); var rowContext = oj.TableRendererUtils.getRendererContextObject(this, tableBodyRow[0], {'row': {key: rowKey, index: this._getDataSourceRowIndexForRowKey(rowKey)}, 'isCurrentRow': true}); updateEditMode = this._trigger('beforeRowEditEnd', event, {'rowContext': rowContext, 'cancelEdit': cancelled}); } else { // No updates so just exit return; } } catch (err) { return false; } if (!updateEditMode) { return false; } // save the old editable row index var prevEditableRowIdx = this._getEditableRowIdx(); var self = this; if (editable) { // set the editable row index this._setEditableRowIdx(rowIdx); // re-render the newly editable row this['refreshRow'](rowIdx).then(function(){ self._queueTask(function() { var focusRowIdx = rowIdx; var focusColumnIdx = columnIdx; var focusForwardSearch = forwardSearch; // set focus on the column in the row self._setCellInRowFocus(focusRowIdx, focusColumnIdx, focusForwardSearch); }); }); } else { this._setEditableRowIdx(null); this._getTableDomUtils().getTable().focus(); } // clear out the old editable row if (prevEditableRowIdx != null) { // re-render the previously editable row, which will be read-only now this['refreshRow'](prevEditableRowIdx).then(function(){ self._queueTask(function() { var selfPrevEditableRowIdx = prevEditableRowIdx; var prevEditableRow = this._getTableDomUtils().getTableBodyRow(selfPrevEditableRowIdx); if (prevEditableRow != null) { prevEditableRow.removeClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_EDIT_CLASS); } }); }); } } }, /** * Show the inline message. * @param {string} summary * @param {string} detail * @param {number} severityLevel * @private */ _showInlineMessage: function(summary, detail, severityLevel) { this._getTableDomUtils().setTableInlineMessage(summary, detail, severityLevel); var inlineMessage = this._getTableDomUtils().getTableInlineMessage(); if (inlineMessage.css(oj.TableDomUtils.CSS_PROP._DISPLAY) == oj.TableDomUtils.CSS_VAL._NONE) { inlineMessage.css(oj.TableDomUtils.CSS_PROP._DISPLAY, oj.TableDomUtils.CSS_VAL._BLOCK); // set the table container margin to add space to display the message var inlineMessagePaddingLeft = parseInt(inlineMessage.css(oj.TableDomUtils.CSS_PROP._PADDING_LEFT), 10); var inlineMessagePaddingRight = parseInt(inlineMessage.css(oj.TableDomUtils.CSS_PROP._PADDING_RIGHT), 10); var tableContainer = this._getTableDomUtils().getTableContainer(); if (severityLevel == oj.Message.SEVERITY_LEVEL['WARNING']) { tableContainer.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._WARNING); inlineMessage.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._WARNING); } var tableContainerWidth = tableContainer.width(); inlineMessage.css(oj.TableDomUtils.CSS_PROP._WIDTH, tableContainerWidth - inlineMessagePaddingLeft - inlineMessagePaddingRight + oj.TableDomUtils.CSS_VAL._PX); var inlineMessageHeight = inlineMessage.outerHeight(); var tableContainerBorderBottom = parseInt(tableContainer.css(oj.TableDomUtils.CSS_PROP._BORDER_BOTTOM_WIDTH), 10); var tableContainerBorderLeft = parseInt(tableContainer.css(oj.TableDomUtils.CSS_PROP._BORDER_LEFT_WIDTH), 10); var tableContainerMarginBottom = parseInt(tableContainer.css(oj.TableDomUtils.CSS_PROP._MARGIN_BOTTOM), 10); tableContainerMarginBottom = tableContainerMarginBottom + tableContainerBorderBottom + inlineMessageHeight; tableContainer.css(oj.TableDomUtils.CSS_PROP._MARGIN_BOTTOM, tableContainerMarginBottom + oj.TableDomUtils.CSS_VAL._PX); inlineMessage.css(oj.TableDomUtils.CSS_PROP._BOTTOM, -1 * (tableContainerMarginBottom + tableContainerBorderBottom) + oj.TableDomUtils.CSS_VAL._PX); inlineMessage.css(oj.TableDomUtils.CSS_PROP._LEFT, -1 * tableContainerBorderLeft + oj.TableDomUtils.CSS_VAL._PX); } }, /** * Show the 'No data to display.' or 'Initializing...' message. * @private */ _showNoDataMessage: function() { var messageRow = this._getTableDomUtils().getTableBodyMessageRow(); var data = this._getData(); // if data is null then we are initializing var messageText = data != null ? this.getTranslatedString(this._BUNDLE_KEY._MSG_NO_DATA) : this.getTranslatedString(this._BUNDLE_KEY._MSG_INITIALIZING); if (messageRow == null) { this._getTableDomUtils().createTableBodyMessageRow(this._getColumnDefs().length, messageText); } else { this._getTableDomUtils().setTableBodyMessage(messageText); } }, /** * Show the Fetching Data... status message. * @private */ _showStatusMessage: function() { var statusMessage = this._getTableDomUtils().getTableStatusMessage(); if (statusMessage.css(oj.TableDomUtils.CSS_PROP._DISPLAY) == oj.TableDomUtils.CSS_VAL._NONE) { statusMessage.css(oj.TableDomUtils.CSS_PROP._DISPLAY, oj.TableDomUtils.CSS_VAL._INLINE); this._getTableDomUtils().refreshTableStatusPosition(); } }, /** * Show the column header sort link * @param {number} columnIdx column index * @private */ _showTableHeaderColumnSortLink: function(columnIdx) { if (this._getColumnDefs()[columnIdx]['sortable'] == this._OPTION_ENABLED) { var tableHeaderColumn = this._getTableDomUtils().getTableHeaderColumn(columnIdx); if (!tableHeaderColumn) { return; } // check if the column is currently sorted var sorted = tableHeaderColumn.data('sorted'); // we should only show the ascending sort link if the column is not sorted if (sorted == null) { var headerColumnAscLink = tableHeaderColumn.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ASC_LINK_CLASS); headerColumnAscLink.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._ENABLED); headerColumnAscLink.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DISABLED); var headerColumnAsc = tableHeaderColumn.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ASC_CLASS); headerColumnAsc.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DISABLED); var headerColumnDsc = tableHeaderColumn.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DSC_CLASS); headerColumnDsc.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DISABLED); } } }, /** * Unregister _focusable(), etc, which were added to the child elements * @param {jQuery} parent jQuery div DOM element * @private */ _unregisterChildStateListeners: function(parent) { var self = this; parent.find('*').each(function() { self._UnregisterChildNode(this); }); self = null; }, /** * Unregister event listeners which are registered on datasource. * @private */ _unregisterDataSourceEventListeners: function() { var data = this._getData(); // unregister the listeners on the datasource if (this._dataSourceEventHandlers != null && data != null) { var i, dataSourceEventHandlersCount = this._dataSourceEventHandlers.length; for (i = 0; i < dataSourceEventHandlersCount; i++) data.off(this._dataSourceEventHandlers[i]['eventType'], this._dataSourceEventHandlers[i]['eventHandler']); } }, /** * Unregister event listeners for resize the container DOM element. * @private */ _unregisterResizeListener: function() { var element = this._getTableDomUtils().getTableContainer(); oj.DomUtils.removeResizeListener(element[0], this._resizeListener); this._isResizeListenerAdded = false; }, /** * Update the css class from all the cells in a column according to column state * @param {number} columnIdx column index * @param {boolean} blur true or false * @private */ _updateHeaderColumnStateCellsClass: function(columnIdx, blur) { var state = this._getHeaderColumnState(columnIdx); var selected = state.selected; var selectedRowIdxs = this._getSelectedRowIdxs(); var tableBodyRows = this._getTableDomUtils().getTableBodyRows(); if (tableBodyRows != null && tableBodyRows.length > 0) { var i, j, tableBodyCell, rowSelected, selectedRowIdxsCount, tableBodyRowsCount = tableBodyRows.length; for (i = 0; i < tableBodyRowsCount; i++) { tableBodyCell = this._getTableDomUtils().getTableBodyCell(i, columnIdx); if (!selected) { rowSelected = false; selectedRowIdxsCount = selectedRowIdxs.length; for (j = 0; j < selectedRowIdxsCount; j++) { if (i == selectedRowIdxs[j]) { rowSelected = true; break; } } if (!rowSelected) { $(tableBodyCell).removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._SELECTED); } } else { $(tableBodyCell).addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._SELECTED); } } } }, /** * Update the css class from all the cells in a row according to row state * @param {number} rowIdx row index * @param {Object} state row state * @param {boolean} blur true or false * @private */ _updateRowStateCellsClass: function(rowIdx, state, blur) { var tableBodyCells = this._getTableDomUtils().getTableBodyCells(rowIdx); var focused = state.focused; var selected = state.selected; var hover = state.hover; if (!tableBodyCells) { return; } if (hover != null) { var i, tableBodyCellsCount = tableBodyCells.length; for (i = 0; i < tableBodyCellsCount; i++) { if (!hover) { $(tableBodyCells[i]).removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._HOVER); } else { $(tableBodyCells[i]).addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._HOVER); } } } if (focused != null) { var i, tableBodyCellsCount = tableBodyCells.length; for (i = 0; i < tableBodyCellsCount; i++) { if (!focused) { $(tableBodyCells[i]).removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._FOCUS); } else { $(tableBodyCells[i]).addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._FOCUS); } } } if (selected != null) { var i, tableBodyCellsCount = tableBodyCells.length;; for (i = 0; i < tableBodyCellsCount; i++) { if (!selected) { $(tableBodyCells[i]).removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._SELECTED); } else { $(tableBodyCells[i]).addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._SELECTED); } } } }, _setFinalTask: function(task) { this._finalTask = (task ? task.bind(this) : undefined); }, _queueTask: function(task) { var self = this; if (!this._pendingTasks) { this._taskCount = 0; this._pendingTasks = Promise.resolve(); this._setComponentNotReady(); } this._taskCount++; this._pendingTasks = this._pendingTasks .then( function() { if (!self._componentDestroyed) { return task.bind(self)(); } }) .then(function(value) { self._taskCount--; if (self._taskCount == 0) { self._pendingTasks = undefined; try { if (!self._componentDestroyed) { if (self._finalTask) { self._finalTask(); } self._trigger("ready"); } } catch(err) { oj.Logger.error(err); } // Need to remove busy state even if the component is destroyed self._setComponentReady(); self = null; } return value; }, function(error) { self._taskCount--; if (self._taskCount == 0) { self._pendingTasks = undefined; oj.Logger.error(error); self._setComponentReady(); self = null; } return Promise.reject(error); }); return this._pendingTasks; } /* Later when needed _whenReady: function() { if (this._pendingTasks) { return this._pendingTasks; } return Promise.resolve(); } */ /**** end internal functions ****/ } ) }()); oj.Components.setDefaultOptions( { 'ojTable': { 'display': oj.Components.createDynamicPropertyGetter(function() { return (oj.ThemeUtils.parseJSONFromFontFamily('oj-table-option-defaults') || {})['display']; }) } } ); /** * Copyright (c) 2014, Oracle and/or its affiliates. * All rights reserved. */ /** * @preserve Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ /*jslint browser: true,devel:true*/ /** * @ignore * @export * @class oj.TableDomUtils * @classdesc DOM Utils for ojTable * @param {Object} component ojTable instance * @constructor */ oj.TableDomUtils = function(component) { this.component = component; this.options = component['options']; this.element = component['element']; this.OuterWrapper = component.OuterWrapper; this.Init(); }; // Subclass from oj.Object oj.Object.createSubclass(oj.TableDomUtils, oj.Object, "oj.TableDomUtils"); /** * Initializes the instance. * @export */ oj.TableDomUtils.prototype.Init = function() { oj.TableDomUtils.superclass.Init.call(this); }; /** * Clear any cached DOM * @private */ oj.TableDomUtils.prototype.clearCachedDom = function() { this.clearCachedDomRowData(); this._tableDimensions = null; } /** * Clear any cached DOM rows * @private */ oj.TableDomUtils.prototype.clearCachedDomRowData = function() { this._cachedDomTableBodyRows = null; } /** * Create a span element for acc purposes * @param {string} text span text * @param {string|null} className css class * @return {jQuery} jQuery span DOM element */ oj.TableDomUtils.prototype.createAccLabelSpan = function(text, className) { var accLabel = $(document.createElement('span')); if (className != null) { accLabel.addClass(className); } accLabel.addClass(oj.TableDomUtils.CSS_CLASSES._HIDDEN_CONTENT_ACC_CLASS); accLabel.text(text); return accLabel; }; /** * Add a default context menu to the table container if there is none. If there is * a context menu set on the table options we use that one. Add listeners * for context menu before show and select. * @param {function(Object)} handleContextMenuSelect function called for menu select * @return {jQuery} jQuery ul DOM element */ oj.TableDomUtils.prototype.createContextMenu = function(handleContextMenuSelect) { var menuContainer = null; var self = this; var enableNonContigousSelectionMenu = this.component._isTouchDevice() ? this.component._getRowSelectionMode() == this.component._OPTION_SELECTION_MODES._MULTIPLE : false; if (this.options["contextMenu"] != null || this.getTable().attr("contextmenu") != null) { var menuContainerId = this.getContextMenuId(); menuContainer = $(menuContainerId); if (menuContainer != null && menuContainer.length > 0) { var listItems = menuContainer.find('[data-oj-command]'); if (listItems != null && listItems.length > 0) { var command; listItems.each(function() { if ($(this).children(oj.TableDomUtils.DOM_ELEMENT._A).length === 0) { command = $(this).attr('data-oj-command').split("-"); $(this).replaceWith(self.createContextMenuItem(command[command.length - 1])); //@HTMLUpdateOK } }); this._menuContainer = menuContainer; this.component._contextMenuId = menuContainerId; if (menuContainer.data('oj-ojMenu')) { menuContainer.ojMenu('refresh'); } menuContainer.on("ojselect", handleContextMenuSelect); } } } else if (this.component._isTableSortable() || enableNonContigousSelectionMenu) { menuContainer = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._UL)); menuContainer.css(oj.TableDomUtils.CSS_PROP._DISPLAY, oj.TableDomUtils.CSS_VAL._NONE); menuContainer.attr(oj.TableDomUtils.DOM_ATTR._ID, this.getTableId() + '_contextmenu'); this.getTableContainer().append(menuContainer); //@HTMLUpdateOK if (this.component._isTableSortable()) { var sortMenu = this.createContextMenuItem('sort'); menuContainer.append(sortMenu); //@HTMLUpdateOK } if (enableNonContigousSelectionMenu) { var nonContigousSelectionMenu = this.createContextMenuItem('enableNonContiguousSelection'); menuContainer.append(nonContigousSelectionMenu); //@HTMLUpdateOK } menuContainer.ojMenu(); this._menuContainer = menuContainer; this.component._contextMenuId = '#' + menuContainer.attr(oj.TableDomUtils.DOM_ATTR._ID); menuContainer.on("ojselect", handleContextMenuSelect); this.component._setOption("contextMenu", '#' + menuContainer.attr(oj.TableDomUtils.DOM_ATTR._ID)); } return menuContainer; }; /** * Builds a menu for a command, takes care of submenus where appropriate * @return {jQuery} jQuery li DOM element */ oj.TableDomUtils.prototype.createContextMenuItem = function(command) { if (command === 'sort') { var sortMenuListItem = $(this.createContextMenuListItem(command)); var listElement = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._UL)); sortMenuListItem.append(listElement); //@HTMLUpdateOK listElement.append($(this.createContextMenuListItem('sortAsc'))); //@HTMLUpdateOK listElement.append($(this.createContextMenuListItem('sortDsc'))); //@HTMLUpdateOK return sortMenuListItem; } else if (command === 'sortAsc') { return $(this.createContextMenuListItem(command)); } else if (command === 'sortDsc') { return $(this.createContextMenuListItem(command)); } else if (command == 'enableNonContiguousSelection') { return $(this.createContextMenuListItem(command)); } else if (command == 'disableNonContiguousSelection') { return $(this.createContextMenuListItem(command)); } return null; }; /** * Builds a context menu list item from a command * @param {string} command the string to look up command value for as well as translation * @return {jQuery} jQuery li DOM element */ oj.TableDomUtils.prototype.createContextMenuListItem = function(command) { var contextMenuListItem = $(document.createElement('li')); contextMenuListItem.attr('data-oj-command', 'oj-table-' + command); contextMenuListItem.append(this.createContextMenuLabel(command)); //@HTMLUpdateOK return contextMenuListItem; }; /** * Builds a context menu label by looking up command translation * @param {string} command the string to look up translation for * @return {jQuery} jQuery a DOM element */ oj.TableDomUtils.prototype.createContextMenuLabel = function(command) { var contextMenuLabel = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._A)); contextMenuLabel.attr(oj.TableDomUtils.DOM_ATTR._HREF, '#'); var commandString = null; if (command == 'sort') { commandString = this.component.getTranslatedString('labelSort'); } else if (command == 'sortAsc') { commandString = this.component.getTranslatedString('labelSortAsc'); } else if (command == 'sortDsc') { commandString = this.component.getTranslatedString('labelSortDsc'); } else if (command == 'enableNonContiguousSelection') { commandString = this.component.getTranslatedString('labelEnableNonContiguousSelection'); } else if (command == 'disableNonContiguousSelection') { commandString = this.component.getTranslatedString('labelDisableNonContiguousSelection'); } contextMenuLabel.text(commandString); return contextMenuLabel; }; /** * Create the initial empty table * @param {boolean} isTableHeaderless is table headerless * @param {boolean} isTableFooterless is table footerless * @return {jQuery} jQuery table DOM element */ oj.TableDomUtils.prototype.createInitialTable = function(isTableHeaderless, isTableFooterless) { var table = this.getTable(); this.createTableContainer(); // we only need a scroller div if we are using fallback scrolling if (this.isDivScroller()) { this.createTableDivScroller(); } if (!isTableHeaderless) { this.createTableHeader(); } if (!isTableFooterless) { this.createTableFooter(); } this.createTableBody(); this.createTableStatusMessage(); this.createTableInlineMessage(); this.createTableStatusAccNotification(); return table; }; /** * Create an empty tbody element with appropriate styling * @return {jQuery} jQuery tbody DOM element */ oj.TableDomUtils.prototype.createTableBody = function() { var table = this.getTable(); var tableBody = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._TBODY)); table.append(tableBody); //@HTMLUpdateOK this._cachedDomTableBody = tableBody; return tableBody; }; /** * Create an empty td element with appropriate styling * @param {number} rowIdx row index * @param {number} columnIdx column index * @return {jQuery} jQuery td DOM element */ oj.TableDomUtils.prototype.createTableBodyCell = function(rowIdx, columnIdx) { var tableBodyCell = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._TD)); return tableBodyCell; }; /** * Create a checkbox for accessibility row selection * @param {number} rowIdx row index * @param {Object} rowKey row key * @param {Object} rowHashCode row hash code * @param {jQuery} tableBodyRow tr DOM element * @param {boolean} isNew is new row * @return {jQuery} jQuery td DOM element */ oj.TableDomUtils.prototype.createTableBodyCellAccSelect = function(rowIdx, rowKey, rowHashCode, tableBodyRow, isNew) { var accSelectionCell = null; if (!isNew) { accSelectionCell = this.getTableBodyCellAccSelect(tableBodyRow); } if (accSelectionCell != null) { return accSelectionCell; } var rowKeyStr = rowKey != null ? rowKey.toString() : rowIdx.toString(); var rowKeyStrHashCode = rowHashCode == null ? this.hashCode(rowKeyStr) : rowHashCode; accSelectionCell = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._TD)); accSelectionCell.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_CELL_ACC_SELECT_CLASS); accSelectionCell.css('padding', '0'); accSelectionCell.css('border', '0'); var isTableHeaderless = this.getTableHeader() == null ? true : false; if (!isTableHeaderless) { var accessibility = this.options['accessibility']; var rowHeaderColumnId = null; if (accessibility != null && accessibility['rowHeader'] != null) { rowHeaderColumnId = accessibility['rowHeader']; } else { rowHeaderColumnId = this.component._getColumnDefs()[0].id; } var cellRowHeaderId = this.getTableId() + ':' + rowHeaderColumnId + '_' + rowKeyStrHashCode; accSelectionCell.attr(oj.TableDomUtils.DOM_ATTR._HEADERS, this.getTableId() + ':' + oj.TableDomUtils._COLUMN_HEADER_ROW_SELECT_ID + ' ' + cellRowHeaderId); } var accSelectCheckbox = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._INPUT)); accSelectCheckbox.attr(oj.TableDomUtils.DOM_ATTR._ID, this.getTableId() + ':acc_sel_row_' + rowKeyStrHashCode); accSelectCheckbox.attr(oj.TableDomUtils.DOM_ATTR._TYPE, 'checkbox'); accSelectCheckbox.attr(oj.TableDomUtils.DOM_ATTR._TABINDEX, '-1'); var selectRowTitle = null; var editMode = this['options']['editMode']; var isRowSelectionEnabled = this.component._getRowSelectionMode() != null ? true : false; if (editMode == this.component._OPTION_EDIT_MODE._ROW_EDIT) { if (!isRowSelectionEnabled) { selectRowTitle = this.component.getTranslatedString(this.component._BUNDLE_KEY._LABEL_EDIT_ROW); } else { selectRowTitle = this.component.getTranslatedString(this.component._BUNDLE_KEY._LABEL_SELECT_AND_EDIT_ROW); } } else { selectRowTitle = this.component.getTranslatedString(this.component._BUNDLE_KEY._LABEL_SELECT_ROW); } accSelectCheckbox.attr(oj.TableDomUtils.DOM_ATTR._TITLE, selectRowTitle); accSelectCheckbox.addClass(oj.TableDomUtils.CSS_CLASSES._CHECKBOX_ACC_SELECT_ROW_CLASS); accSelectCheckbox.addClass(oj.TableDomUtils.CSS_CLASSES._HIDDEN_CONTENT_ACC_CLASS); if (this.component._getEditableRowIdx() == rowIdx) { accSelectCheckbox.prop('checked', true); } else { accSelectCheckbox.prop('checked', false); } accSelectionCell.append(accSelectCheckbox); //@HTMLUpdateOK tableBodyRow.prepend(accSelectionCell); //@HTMLUpdateOK return accSelectionCell; }; /** * Create the message td element with appropriate styling and message * @param {jQuery} tableBodyMessageRow tr DOM element * @param {number} columnCount number of visible columns * @param {string} message message * @return {jQuery} jQuery td DOM element */ oj.TableDomUtils.prototype.createTableBodyMessageCell = function(tableBodyMessageRow, columnCount, message) { var messageCell = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._TD)); messageCell.attr(oj.TableDomUtils.DOM_ATTR._COLSPAN, columnCount + 1); messageCell.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_BODY_MESSAGE_CLASS); messageCell.text(message); tableBodyMessageRow.append(messageCell); //@HTMLUpdateOK return messageCell; }; /** * Create the message row with appropriate styling * @param {number} columnCount number of visible columns * @param {string} message message * @return {jQuery} jQuery row DOM element */ oj.TableDomUtils.prototype.createTableBodyMessageRow = function(columnCount, message) { var tableBody = this.getTableBody(); var tableBodyMessageRow = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._TR)); tableBodyMessageRow.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_BODY_MESSAGE_ROW_CLASS); this.createTableBodyMessageCell(tableBodyMessageRow, columnCount, message); tableBody.append(tableBodyMessageRow); //@HTMLUpdateOK return tableBodyMessageRow; }; /** * Create an empty tr element with appropriate styling * @param {number} rowIdx row index * @param {Object} rowKey row key * @return {jQuery} jQuery tr DOM element */ oj.TableDomUtils.prototype.createTableBodyRow = function(rowIdx, rowKey) { var tableBodyRow = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._TR)); this.createTableBodyCellAccSelect(rowIdx, rowKey, null, tableBodyRow, true); return tableBodyRow; }; /** * Add the touch affordance to the table row. * @param {number} rowIdx row index */ oj.TableDomUtils.prototype.createTableBodyRowTouchSelectionAffordance = function(rowIdx) { var topAffordance = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._DIV)); topAffordance.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_TOUCH_SELECTIOM_AFFORDANCE_TOP_CLASS); topAffordance.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_TOUCH_SELECTIOM_AFFORDANCE_TOUCH_AREA_CLASS); topAffordance.data('rowIdx', rowIdx); var topIcon = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._DIV)); topIcon.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_TOUCH_SELECTIOM_AFFORDANCE_TOP_ICON_CLASS); topIcon.attr(oj.TableDomUtils.DOM_ATTR._ROLE, 'button'); topIcon.attr(oj.TableDomUtils.DOM_ATTR._ARIA_LABEL, this.component.getTranslatedString('labelAccSelectionAffordanceTop')); topIcon.data('rowIdx', rowIdx); topAffordance.append(topIcon); //@HTMLUpdateOK var bottomAffordance = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._DIV)); bottomAffordance.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_TOUCH_SELECTIOM_AFFORDANCE_BOTTOM_CLASS); bottomAffordance.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_TOUCH_SELECTIOM_AFFORDANCE_TOUCH_AREA_CLASS); bottomAffordance.data('rowIdx', rowIdx); var bottomIcon = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._DIV)); bottomIcon.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_TOUCH_SELECTIOM_AFFORDANCE_BOTTOM_ICON_CLASS); bottomIcon.attr(oj.TableDomUtils.DOM_ATTR._ROLE, 'button'); bottomIcon.attr(oj.TableDomUtils.DOM_ATTR._ARIA_LABEL, this.component.getTranslatedString('labelAccSelectionAffordanceBottom')); bottomIcon.data('rowIdx', rowIdx); bottomAffordance.append(bottomIcon); //@HTMLUpdateOK var tableContainer = this.getTableContainer(); tableContainer.append(topAffordance); //@HTMLUpdateOK tableContainer.append(bottomAffordance); //@HTMLUpdateOK this.moveTableBodyRowTouchSelectionAffordanceTop(rowIdx); this.moveTableBodyRowTouchSelectionAffordanceBottom(rowIdx); }; /** * Create an empty div element with appropriate styling * @return {jQuery} jQuery div DOM element */ oj.TableDomUtils.prototype.createTableContainer = function() { var options = this.options; // need to enclose the table in a div to provide horizontal scrolling var tableContainer; if (this.OuterWrapper) { tableContainer = $(this.OuterWrapper); } else { tableContainer = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._DIV)); this.element.parent()[0].replaceChild(tableContainer[0], this.element[0]); tableContainer.prepend(this.element); //@HTMLUpdateOK } this._cachedDomTableContainer = tableContainer; return tableContainer; }; /** * Create an empty tfoot with appropriate styling * @return {jQuery} jQuery tfoot DOM element */ oj.TableDomUtils.prototype.createTableFooter = function() { var table = this.getTable(); var tableFooter = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._TFOOT)); var tableFooterRow = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._TR)); this.createTableFooterAccSelect(tableFooterRow); tableFooter.append(tableFooterRow); //@HTMLUpdateOK // check if thead is already there. If so add relative to thead. var tableHeader = this.getTableHeader(); if (tableHeader != null) { tableHeader.after(tableFooter); //@HTMLUpdateOK } else { // check if tbody is already there. If so add relative to tbody. var tableBody = this.getTableBody(); if (tableBody != null) { tableBody.before(tableFooter); //@HTMLUpdateOK } else { table.append(tableFooter); //@HTMLUpdateOK } } return tableFooter; }; /** * Create a checkbox for accessibility row selection * @param {jQuery} tableFooterRow tr DOM element * @return {jQuery} jQuery td DOM element */ oj.TableDomUtils.prototype.createTableFooterAccSelect = function(tableFooterRow) { var accFooterCell = tableFooterRow.children('.' + oj.TableDomUtils.CSS_CLASSES._HIDDEN_CONTENT_ACC_CLASS); if (accFooterCell != null && accFooterCell.length > 0) { return $(accFooterCell[0]); } accFooterCell = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._TD)); accFooterCell.addClass(oj.TableDomUtils.CSS_CLASSES._HIDDEN_CONTENT_ACC_CLASS); accFooterCell.attr(oj.TableDomUtils.DOM_ATTR._TABINDEX, '-1'); tableFooterRow.prepend(accFooterCell); //@HTMLUpdateOK return accFooterCell; }; /** * Create an empty td element with appropriate styling * @param {number} columnIdx column index * @return {jQuery} jQuery td DOM element */ oj.TableDomUtils.prototype.createTableFooterCell = function(columnIdx) { var tableFooterCell = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._TD)); return tableFooterCell; }; /** * Create an empty thead & tr element with appropriate styling * @return {jQuery} jQuery thead DOM element */ oj.TableDomUtils.prototype.createTableHeader = function() { var table = this.getTable(); var tableHeader = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._THEAD)); var tableHeaderRow = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._TR)); this._cachedDomTableHeaderRow = tableHeaderRow; tableHeader.append(tableHeaderRow); //@HTMLUpdateOK // check if tfoot is already there. If so add relative to tfoot. var tableFooter = this.getTableFooter(); if (tableFooter != null) { tableFooter.before(tableHeader); //@HTMLUpdateOK } else { // check if tbody is already there. If so add relative to tbody. var tableBody = this.getTableBody(); if (tableBody != null) { tableBody.before(tableHeader); //@HTMLUpdateOK } else { table.append(tableHeader); //@HTMLUpdateOK } } this._cachedDomTableHeader = tableHeader; return tableHeader; }; /** * Create a th element for accessibility row selection * @return {jQuery} jQuery th DOM element */ oj.TableDomUtils.prototype.createTableHeaderAccSelectRowColumn = function() { var headerColumn = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._TH)); headerColumn.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ACC_SELECT_ROW_CLASS); headerColumn.attr(oj.TableDomUtils.DOM_ATTR._ID, this.getTableId() + ':' + oj.TableDomUtils._COLUMN_HEADER_ROW_SELECT_ID); var selectRowTitle; var editMode = this['options']['editMode']; var isRowSelectionEnabled = this.component._getRowSelectionMode() != null ? true : false; if (editMode == this.component._OPTION_EDIT_MODE._ROW_EDIT) { if (!isRowSelectionEnabled) { selectRowTitle = this.component.getTranslatedString(this.component._BUNDLE_KEY._LABEL_EDIT_ROW); } else { selectRowTitle = this.component.getTranslatedString(this.component._BUNDLE_KEY._LABEL_SELECT_AND_EDIT_ROW); } } else { selectRowTitle = this.component.getTranslatedString(this.component._BUNDLE_KEY._LABEL_SELECT_ROW); } headerColumn.attr(oj.TableDomUtils.DOM_ATTR._TITLE, selectRowTitle); headerColumn.css('padding', '0'); headerColumn.css('border', '0'); var headerColumnText = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._SPAN)); headerColumnText.text(selectRowTitle); headerColumnText.addClass(oj.TableDomUtils.CSS_CLASSES._HIDDEN_CONTENT_ACC_CLASS); headerColumn.append(headerColumnText); //@HTMLUpdateOK return headerColumn; }; /** * Create a th element with appropriate styling and column content * @param {number} columnIdx column index * @param {string} columnSelectionMode column selection mode * @return {jQuery} jQuery th DOM element */ oj.TableDomUtils.prototype.createTableHeaderColumn = function(columnIdx, columnSelectionMode) { var column = this.component._getColumnDefs()[columnIdx]; var headerColumnCell = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._TH)); this.styleTableHeaderColumn(columnIdx, headerColumnCell, columnSelectionMode, true); // add abbr for acc headerColumnCell.attr('abbr', column.headerText); // add title for tooltip headerColumnCell.attr(oj.TableDomUtils.DOM_ATTR._TITLE, column.headerText); this.insertTableHeaderColumn(columnIdx, headerColumnCell); var headerContext = {'columnIndex' : columnIdx, 'headerContext': {'component': this.component, 'parentElement': headerColumnCell}}; if (column.sortable == oj.TableDomUtils._OPTION_ENABLED) { headerColumnCell.attr('data-oj-sortable', oj.TableDomUtils._OPTION_ENABLED); oj.TableRendererUtils.columnHeaderSortableIconRenderer(this.component, headerContext, null, null); } else { oj.TableRendererUtils.columnHeaderDefaultRenderer(this.component, headerContext, null, null); } return headerColumnCell; }; /** * Create the drag image for the column * @param {number} columnIdx column index * @return {jQuery} jQuery DOM element */ oj.TableDomUtils.prototype.createTableHeaderColumnDragImage = function(columnIdx) { var headerColumn = this.getTableHeaderColumn(columnIdx); var headerColumnDragImage = headerColumn.clone(); headerColumnDragImage.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DRAG); headerColumnDragImage.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._FOCUS); headerColumnDragImage.removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._HOVER); headerColumnDragImage.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DRAG_IMAGE); headerColumnDragImage.css(oj.TableDomUtils.CSS_PROP._POSITION, oj.TableDomUtils.CSS_VAL._ABSOLUTE); headerColumnDragImage.css(oj.TableDomUtils.CSS_PROP._TOP, '0'); headerColumnDragImage.css(oj.TableDomUtils.CSS_PROP._LEFT, '-999em'); headerColumnDragImage.css(oj.TableDomUtils.CSS_PROP._ZINDEX, '-999'); var tableContainer = this.getTableContainer(); tableContainer.append(headerColumnDragImage); //@HTMLUpdateOK return headerColumnDragImage; }; /** * Create a checkbox for accessibility column selection * @param {number} columnIdx column index * @param {string} columnSelectionMode column selection mode * @return {jQuery} jQuery div DOM element */ oj.TableDomUtils.prototype.createTableHeaderColumnAccSelect = function(columnIdx, columnSelectionMode) { if (columnSelectionMode != oj.TableDomUtils._OPTION_SELECTION_MODES._SINGLE && columnSelectionMode != oj.TableDomUtils._OPTION_SELECTION_MODES._MULTIPLE) { return null; } var headerColumn = this.getTableHeaderColumn(columnIdx); var accSelectionHeaderColumn = this.getTableHeaderColumnAccSelect(columnIdx); if (accSelectionHeaderColumn != null) { return accSelectionHeaderColumn; } accSelectionHeaderColumn = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._DIV)); accSelectionHeaderColumn.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ACC_SELECT_COLUMN_CLASS); accSelectionHeaderColumn.addClass(oj.TableDomUtils.CSS_CLASSES._HIDDEN_CONTENT_ACC_CLASS); var accSelectCheckbox = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._INPUT)); accSelectCheckbox.attr(oj.TableDomUtils.DOM_ATTR._ID, this.getTableId() + ':acc_sel_col' + columnIdx); accSelectCheckbox.attr(oj.TableDomUtils.DOM_ATTR._TYPE, 'checkbox'); accSelectCheckbox.attr(oj.TableDomUtils.DOM_ATTR._TABINDEX, '-1'); var selectColumnTitle = this.component.getTranslatedString(this.component._BUNDLE_KEY._LABEL_SELECT_COLUMN); accSelectCheckbox.attr(oj.TableDomUtils.DOM_ATTR._TITLE, selectColumnTitle); accSelectCheckbox.addClass(oj.TableDomUtils.CSS_CLASSES._CHECKBOX_ACC_SELECT_COLUMN_CLASS); accSelectionHeaderColumn.append(accSelectCheckbox); //@HTMLUpdateOK headerColumn.prepend(accSelectionHeaderColumn); //@HTMLUpdateOK return accSelectionHeaderColumn; }; /** * Create a div element for table scrolling. Used in scrolling fallback mode. * @return {jQuery} jQuery div DOM element */ oj.TableDomUtils.prototype.createTableDivScroller = function() { var table = this.getTable(); var tableContainer = this.getTableContainer(); var tableDivScroller = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._DIV)); tableDivScroller.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_SCROLLER_CLASS); tableContainer[0].replaceChild(tableDivScroller[0], table[0]); tableDivScroller.append(table); //@HTMLUpdateOK this._cachedDomTableDivScroller = tableDivScroller; return tableDivScroller; }; /** * Create a div element for inline messages * @return {jQuery} jQuery div DOM element */ oj.TableDomUtils.prototype.createTableInlineMessage = function() { var tableContainer = this.getTableContainer(); var inlineMessage = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._DIV)); inlineMessage.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_INLINE_MESSAGE_CLASS); inlineMessage.css(oj.TableDomUtils.CSS_PROP._DISPLAY, oj.TableDomUtils.CSS_VAL._NONE); tableContainer.append(inlineMessage); //@HTMLUpdateOK this._cachedDomTableInlineMessage = inlineMessage; return inlineMessage; }; /** * Create a div element for the accessibility notifications * @return {jQuery} jQuery div DOM element */ oj.TableDomUtils.prototype.createTableStatusAccNotification = function() { var tableContainer = this.getTableContainer(); var statusNotification = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._DIV)); statusNotification.attr(oj.TableDomUtils.DOM_ATTR._ROLE, 'status'); statusNotification.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_STATUS_ACC_NOTIFICATION_CLASS); statusNotification.addClass(oj.TableDomUtils.CSS_CLASSES._HIDDEN_CONTENT_ACC_CLASS); tableContainer.append(statusNotification); //@HTMLUpdateOK this._cachedDomTableStatusAccNotification = statusNotification; return statusNotification; }; /** * Create a div element for the Fetching Data... status message * @return {jQuery} jQuery div DOM element */ oj.TableDomUtils.prototype.createTableStatusMessage = function() { var tableContainer = this.getTableContainer(); var statusMessage = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._DIV)); statusMessage.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_STATUS_MESSAGE_CLASS); statusMessage.css(oj.TableDomUtils.CSS_PROP._DISPLAY, oj.TableDomUtils.CSS_VAL._NONE); var statusMessageText = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._DIV)); statusMessageText.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_STATUS_MESSAGE_TEXT_CLASS); statusMessageText.text(this.component.getTranslatedString(this.component._BUNDLE_KEY._MSG_FETCHING_DATA)); statusMessage.append(statusMessageText); //@HTMLUpdateOK tableContainer.append(statusMessage); //@HTMLUpdateOK this._cachedDomTableStatusMessage = statusMessage; return statusMessage; }; /** * Display the visual indicator for column drag over * @param {number} columnIdx column index * @param {boolean} before before the column */ oj.TableDomUtils.prototype.displayDragOverIndicatorColumn = function(columnIdx, before) { this.removeDragOverIndicatorColumn(); var tableHeaderRow = this.getTableHeaderRow(); var tableHeaderColumn = this.getTableHeaderColumn(columnIdx); if (tableHeaderColumn != null) { if (before) { tableHeaderColumn.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DRAG_INDICATOR_BEFORE_CLASS); } else { tableHeaderColumn.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DRAG_INDICATOR_AFTER_CLASS); } } else { var columns = this.component._getColumnDefs(); if (columns == null || columns.length == 0) { if (before) { tableHeaderRow.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DRAG_INDICATOR_BEFORE_CLASS); } else { tableHeaderRow.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DRAG_INDICATOR_AFTER_CLASS); } } } } /** * Display the visual indicator for row drag over * @param {number} rowIdx row index * @param {boolean} before before the row */ oj.TableDomUtils.prototype.displayDragOverIndicatorRow = function(rowIdx, before, modelRow) { this.removeDragOverIndicatorRow(); var tableBodyRowDragIndicator = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._TR)); if (before) { tableBodyRowDragIndicator.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_DRAG_INDICATOR_BEFORE_CLASS); } else { tableBodyRowDragIndicator.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_DRAG_INDICATOR_AFTER_CLASS); } if (modelRow) tableBodyRowDragIndicator.height(modelRow.height()); var tableBodyDragIndicatorCell = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._TD)); var columns = this.component._getColumnDefs(); tableBodyDragIndicatorCell.attr(oj.TableDomUtils.DOM_ATTR._COLSPAN, columns.length + 1); tableBodyRowDragIndicator.append(tableBodyDragIndicatorCell); //@HTMLUpdateOK var tableBodyRow = this.getTableBodyRow(rowIdx); if (tableBodyRow != null) { if (before) { tableBodyRow.before(tableBodyRowDragIndicator); //@HTMLUpdateOK } else { tableBodyRow.after(tableBodyRowDragIndicator); //@HTMLUpdateOK } } else { var tableBodyRows = this.getTableBodyRows(); if (tableBodyRows == null || tableBodyRows.length == 0) { this.component._hideNoDataMessage(); } this.getTableBody().append(tableBodyRowDragIndicator); //@HTMLUpdateOK } } /** * Get the context menu * @return {jQuery} jQuery table DOM element */ oj.TableDomUtils.prototype.getContextMenu = function() { return this._menuContainer; }; /** * Get the context menu id * @return {string} context menu id */ oj.TableDomUtils.prototype.getContextMenuId = function() { return this.options["contextMenu"] == null ? '#' + this.getTable().attr("contextmenu") : this.options["contextMenu"]; }; /** * Get the column index of the DOM element. e.g. pass in the table cell to * see which column it's in. * @param {jQuery} element DOM element * @return {number|null} the column index * @private */ oj.TableDomUtils.prototype.getElementColumnIdx = function(element) { var tableBodyCell = this.getFirstAncestor(element, oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_CELL_CLASS); if (tableBodyCell != null) { return tableBodyCell.parent().children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_CELL_CLASS).index(tableBodyCell); } var tableHeaderColumn = this.getFirstAncestor(element, oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_CELL_CLASS); if (tableHeaderColumn != null) { return tableHeaderColumn.parent().children('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_CELL_CLASS).index(tableHeaderColumn); } var tableFooterCell = this.getFirstAncestor(element, oj.TableDomUtils.CSS_CLASSES._TABLE_FOOTER_CELL_CLASS); if (tableFooterCell != null) { return tableFooterCell.parent().children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_FOOTER_CELL_CLASS).index(tableFooterCell); } return null; }; /** * Get the row index of the DOM element. e.g. pass in the table cell to * see which row it's in. * @param {jQuery} element DOM element * @return {number|null} the row index * @private */ oj.TableDomUtils.prototype.getElementRowIdx = function(element) { var tableBodyRow = this.getFirstAncestor(element, oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_CLASS); if (tableBodyRow != null) { return tableBodyRow.index(); } return null; }; /** * Find the first ancestor of an element with a specific class name * @param {jQuery} element the element to find the nearest class name to * @param {string} className the class name to look for * @return {jQuery|null} the element with the className, if there is none returns null */ oj.TableDomUtils.prototype.getFirstAncestor = function(element, className) { var parents; if (element == null) { return null; } element = $(element); if (element.hasClass(className)) { return element; } parents = element.parents('.' + className); if (parents.length != 0) { return parents.eq(0); } return null; }; /** * Return the scrollbar height * @return {number} scrolbar height * @private */ oj.TableDomUtils.prototype.getScrollbarHeight = function() { var scroller = this.getScroller(); if (scroller.get(0).clientHeight > 0) { var scrollbarHeight = scroller.get(0).offsetHeight - scroller.get(0).clientHeight; return scrollbarHeight; } return 0; }; /** * Return the scrollbar width * @return {number} scrolbar width * @private */ oj.TableDomUtils.prototype.getScrollbarWidth = function() { var scroller = this.getScroller(); if (scroller.get(0).clientWidth > 0) { var scrollbarWidth = scroller.get(0).offsetWidth - scroller.get(0).clientWidth; return scrollbarWidth; } return 0; }; /** * Return the table scroller * @return {jQuery} scrolbar */ oj.TableDomUtils.prototype.getScroller = function() { if (!this.isDivScroller()) { return this.getTableBody(); } else { return this.getTableDivScroller(); } }; /** * Get the element scrollLeft * @param {jQuery} element DOM element */ oj.TableDomUtils.prototype.getScrollLeft = function(element) { element = $(element); var scrollLeft = element[0].scrollLeft; if (this.component._GetReadingDirection() === "rtl") { scrollLeft = Math.abs(scrollLeft); if (this._isWebkit()) { var maxScrollLeft = element[0].scrollWidth - element[0].clientWidth; scrollLeft = maxScrollLeft - scrollLeft; } } return scrollLeft; }; /** * Return the table element * @return {jQuery} jQuery table DOM element */ oj.TableDomUtils.prototype.getTable = function() { return $(this.element); }; /** * Return the table body element * @return {jQuery|null} jQuery tbody DOM element */ oj.TableDomUtils.prototype.getTableBody = function() { if (!this._cachedDomTableBody) { var table = this.getTable(); var tableBody = null; if (table) { tableBody = table.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_BODY_CLASS); if (tableBody && tableBody.length > 0) { this._cachedDomTableBody = $(tableBody.get(0)); } } } return this._cachedDomTableBody; }; /** * Return the cell element * @param {number} rowIdx row index * @param {number} columnIdx column index * @param {jQuery|null} tableBodyRow tr DOM element * @return {jQuery|null} jQuery td DOM element */ oj.TableDomUtils.prototype.getTableBodyCell = function(rowIdx, columnIdx, tableBodyRow) { var tableBodyCells = this.getTableBodyCells(rowIdx, tableBodyRow); if (!tableBodyCells) { return null; } if (tableBodyCells.length > columnIdx) { return $(tableBodyCells[columnIdx]); } return null; }; /** * Get checkbox cell for accessibility row selection * @param {jQuery} tableBodyRow tr DOM element * @return {jQuery|null} jQuery td DOM element */ oj.TableDomUtils.prototype.getTableBodyCellAccSelect = function(tableBodyRow) { if (tableBodyRow != null) { var accSelectionCell = tableBodyRow.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_CELL_ACC_SELECT_CLASS); if (accSelectionCell != null && accSelectionCell.length > 0) { return $(accSelectionCell[0]); } } return null; }; /** * Return all the logical cell elements in a row * @param {number} rowIdx row index * @param {jQuery|null} tableBodyRow tr DOM element * @return {jQuery|null} jQuery array of td DOM elements */ oj.TableDomUtils.prototype.getTableBodyLogicalCells = function(rowIdx, tableBodyRow) { var tableBodyCells = this.getTableBodyCells(rowIdx, tableBodyRow); if (!tableBodyCells) { return null; } return this._getColspanLogicalElements(tableBodyCells); } /** * Return all the cell elements in a row * @param {number} rowIdx row index * @param {jQuery|null} tableBodyRow tr DOM element * @return {jQuery|null} jQuery array of td DOM elements */ oj.TableDomUtils.prototype.getTableBodyCells = function(rowIdx, tableBodyRow) { if (!tableBodyRow) { tableBodyRow = this.getTableBodyRow(rowIdx); } if (!tableBodyRow) { return null; } var tableBodyCellElements = tableBodyRow.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_CELL_CLASS); if (tableBodyCellElements != null && tableBodyCellElements.length > 0) { return tableBodyCellElements; } return null; }; /** * Return the table body message cell element * @return {jQuery|null} jQuery tr DOM element */ oj.TableDomUtils.prototype.getTableBodyMessageCell = function() { var tableBody = this.getTableBody(); if (tableBody) { var messageCell = tableBody.find('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_BODY_MESSAGE_CLASS); if (messageCell && messageCell.length > 0) { return $(messageCell.get(0)); } } return null; }; /** * Return the table body message row element * @return {jQuery|null} jQuery tr DOM element */ oj.TableDomUtils.prototype.getTableBodyMessageRow = function() { var tableBody = this.getTableBody(); if (tableBody) { var messageRow = tableBody.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_BODY_MESSAGE_ROW_CLASS); if (messageRow && messageRow.length > 0) { return $(messageRow.get(0)); } } return null; }; /** * Return table row * @param {number|null} rowIdx row index * @return {jQuery|null} jQuery tr DOM element */ oj.TableDomUtils.prototype.getTableBodyRow = function(rowIdx) { var tableBodyRows = this.getTableBodyRows(); if (!tableBodyRows) { return null; } if (rowIdx == null) { return null; } if (tableBodyRows.length > rowIdx) { return $(tableBodyRows[rowIdx]); } return null; }; /** * Return all the table rows * @return {jQuery|null} jQuery array of tr DOM elements */ oj.TableDomUtils.prototype.getTableBodyRows = function() { if (!this._cachedDomTableBodyRows) { var tableBody = this.getTableBody(); if (tableBody != null) { var tableBodyRowElements = tableBody.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_CLASS); if (tableBodyRowElements != null && tableBodyRowElements.length > 0) { this._cachedDomTableBodyRows = tableBodyRowElements; } } } return this._cachedDomTableBodyRows; }; /** * Get top touch affordance to the table row. * @return {jQuery|null} jQuery div DOM element */ oj.TableDomUtils.prototype.getTableBodyRowTouchSelectionAffordanceTop = function() { var tableContainer = this.getTableContainer(); var topAffordance = tableContainer.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_TOUCH_SELECTIOM_AFFORDANCE_TOP_CLASS); if (topAffordance != null && topAffordance.length > 0) { topAffordance = $(topAffordance[0]); return topAffordance; } return null; }; /** * Get bottom touch affordance to the table row. * @return {jQuery|null} jQuery div DOM element */ oj.TableDomUtils.prototype.getTableBodyRowTouchSelectionAffordanceBottom = function() { var tableContainer = this.getTableContainer(); var bottomAffordance = tableContainer.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_TOUCH_SELECTIOM_AFFORDANCE_BOTTOM_CLASS); if (bottomAffordance != null && bottomAffordance.length > 0) { bottomAffordance = $(bottomAffordance[0]); return bottomAffordance; } return null; }; /** * Return the table container * @return {jQuery|null} jQuery div DOM element */ oj.TableDomUtils.prototype.getTableContainer = function() { if (!this._cachedDomTableContainer) { if (!this.isDivScroller()) { this._cachedDomTableContainer = $(this.element.get(0).parentNode); } else { this._cachedDomTableContainer = $(this.element.get(0).parentNode.parentNode); } } return this._cachedDomTableContainer; }; /** * Return the table footer * @return {jQuery|null} jQuery tfoot DOM element */ oj.TableDomUtils.prototype.getTableFooter = function() { var table = this.getTable(); var tableFooter = null; if (table) { tableFooter = table.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_FOOTER_CLASS); if (tableFooter && tableFooter.length > 0) { return $(tableFooter.get(0)); } } return null; }; /** * Return the footer cell element * @param {number} columnIdx column index */ oj.TableDomUtils.prototype.getTableFooterCell = function(columnIdx) { var tableFooterCells = this.getTableFooterCells(); if (tableFooterCells != null && tableFooterCells.length > columnIdx) { return $(tableFooterCells[columnIdx]); } return null; }; /** * Return all footer cells * @return {jQuery|null} jQuery array of jQuery td DOM elements */ oj.TableDomUtils.prototype.getTableFooterCells = function() { var tableFooterRow = this.getTableFooterRow(); var tableFooterCells = $(tableFooterRow).children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_FOOTER_CELL_CLASS); if (tableFooterCells != null && tableFooterCells.length > 0) { return tableFooterCells; } return null; }; /** * Return all logical footer cells * @return {jQuery|null} jQuery array of jQuery td DOM elements */ oj.TableDomUtils.prototype.getTableFooterLogicalCells = function() { var tableFooterCells = this.getTableFooterCells(); if (!tableFooterCells) { return null; } return this._getColspanLogicalElements(tableFooterCells); } /** * Return table footer row * @return {jQuery|null} jQuery tr DOM element */ oj.TableDomUtils.prototype.getTableFooterRow = function() { if (!this._cachedDomTableFooterRow) { var tableFooter = this.getTableFooter(); if (!tableFooter) { return null; } this._cachedDomTableFooterRow = $(tableFooter.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_FOOTER_ROW_CLASS).get(0)); } return this._cachedDomTableFooterRow; }; /** * Return the table header * @return {jQuery|null} jQuery thead DOM element */ oj.TableDomUtils.prototype.getTableHeader = function() { if (!this._cachedDomTableHeader) { var table = this.getTable(); var tableHeader = null; if (table) { tableHeader = table.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_HEADER_CLASS); if (tableHeader && tableHeader.length > 0) { this._cachedDomTableHeader = $(tableHeader.get(0)); } } } return this._cachedDomTableHeader; }; /** * Return table column header * @param {number} columnIdx column index * @return {jQuery|null} jQuery th DOM element */ oj.TableDomUtils.prototype.getTableHeaderColumn = function(columnIdx) { var headerColumns = this.getTableHeaderColumns(); if (!headerColumns) { return null; } if (headerColumns.length > columnIdx) { return $(headerColumns[columnIdx]); } return null; }; /** * Get checkbox cell for accessibility column selection * @param {number} columnIdx column index * @return {jQuery|null} jQuery td DOM element */ oj.TableDomUtils.prototype.getTableHeaderColumnAccSelect = function(columnIdx) { var headerColumn = this.getTableHeaderColumn(columnIdx); if (headerColumn != null) { var accSelectionCell = headerColumn.children('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ACC_SELECT_COLUMN_CLASS); if (accSelectionCell != null && accSelectionCell.length > 0) { return $(accSelectionCell[0]); } } return null; }; /** * Return all table column headers * @return {jQuery|null} jQuery array of th DOM elements */ oj.TableDomUtils.prototype.getTableHeaderColumns = function() { var tableHeaderRow = this.getTableHeaderRow(); if (tableHeaderRow != null) { var headerColumnElements = tableHeaderRow.children('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_CELL_CLASS); if (headerColumnElements != null && headerColumnElements.length > 0) { return headerColumnElements; } } return null; }; /** * Return all logical table column headers * @return {jQuery|null} jQuery array of th DOM elements */ oj.TableDomUtils.prototype.getTableHeaderLogicalColumns = function() { var tableHeaderColumns = this.getTableHeaderColumns(); if (!tableHeaderColumns) { return null; } return this._getColspanLogicalElements(tableHeaderColumns); } /** * Return table header row * @return {jQuery|null} jQuery th DOM element */ oj.TableDomUtils.prototype.getTableHeaderRow = function() { if (!this._cachedDomTableHeaderRow) { var tableHeader = this.getTableHeader(); if (!tableHeader) { return null; } this._cachedDomTableHeaderRow = $(tableHeader.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_HEADER_ROW_CLASS).get(0)); } return this._cachedDomTableHeaderRow; }; /** * Return the table div scroller * @return {jQuery|null} jQuery div DOM element */ oj.TableDomUtils.prototype.getTableDivScroller = function() { if (!this._cachedDomTableDivScroller) { var tableContainer = this.getTableContainer(); if (tableContainer) { var tableDivScroller = tableContainer.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_SCROLLER_CLASS); if (tableDivScroller && tableDivScroller.length > 0) { this._cachedDomTableDivScroller = $(tableDivScroller.get(0)); } } } return this._cachedDomTableDivScroller; }; /** * Return the table DOM element id. * @return {string} Id for table */ oj.TableDomUtils.prototype.getTableId = function() { if (!this._tableId) { // Id for custom element is on the container var idElem = this.component._IsCustomElement() ? this.getTableContainer() : this.getTable(); this._tableId = idElem.attr(oj.TableDomUtils.DOM_ATTR._ID); } return this._tableId; }; /** * Return the table inline message element * @return {jQuery|null} jQuery div DOM element */ oj.TableDomUtils.prototype.getTableInlineMessage = function() { if (!this._cachedDomTableInlineMessage) { var tableContainer = this.getTableContainer(); if (tableContainer) { var inlineMessage = tableContainer.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_INLINE_MESSAGE_CLASS); if (inlineMessage && inlineMessage.length > 0) { this._cachedDomTableInlineMessage = $(inlineMessage.get(0)); } } } return this._cachedDomTableInlineMessage; }; /** * Return the table status accessibility notification * @return {jQuery|null} jQuery div DOM element */ oj.TableDomUtils.prototype.getTableStatusAccNotification = function() { if (!this._cachedDomTableStatusAccNotification) { var tableContainer = this.getTableContainer(); if (tableContainer) { var statusNotification = tableContainer.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_STATUS_ACC_NOTIFICATION_CLASS); if (statusNotification && statusNotification.length > 0) { this._cachedDomTableStatusAccNotification = $(statusNotification.get(0)); } } } return this._cachedDomTableStatusAccNotification; }; /** * Return the table status message element * @return {jQuery|null} jQuery div DOM element */ oj.TableDomUtils.prototype.getTableStatusMessage = function() { if (!this._cachedDomTableStatusMessage) { var tableContainer = this.getTableContainer(); if (tableContainer) { var statusMessage = tableContainer.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_STATUS_MESSAGE_CLASS); if (statusMessage && statusMessage.length > 0) { this._cachedDomTableStatusMessage = $(statusMessage.get(0)); } } } return this._cachedDomTableStatusMessage; }; /** * Return the unique identifier for the table. If the DOM element has an id then * return that. If not, generate a random UID. * @return {string} UID for table */ oj.TableDomUtils.prototype.getTableUID = function() { if (!this._tableUID) { var uid = this.getTableId(); if (uid == null) { uid = (Math.random()*1e32).toString(36); // used to generate a unique id. Should not be a security issue. } this._tableUID = uid; } return this._tableUID; }; /** * Get a hash code for a string * @param {string} str String * @return {number} hashCode */ oj.TableDomUtils.prototype.hashCode = function(str) { if ($.type(str) != 'string') { str = str.toString(); } // Same hash algorithm as Java's String.hashCode var hash = 0; if (str.length == 0) { return hash; } var charVal, i, strCount = str.length; for (i = 0; i < strCount; i++) { charVal = str.charCodeAt(i); hash = ((hash << 5) - hash) + charVal; hash = hash & hash; } return hash; }; /** * Insert a td element in the appropriate place in the DOM * @param {number} rowIdx row index * @param {Object} rowKey row key * @param {Object} rowHashCode row hash code * @param {number} columnIdx column index * @param {jQuery} tableBodyCell DOM element * @param {jQuery} tableBodyRow tr DOM element * @param {boolean} isNew is new row */ oj.TableDomUtils.prototype.insertTableBodyCell = function(rowIdx, rowKey, rowHashCode, columnIdx, tableBodyCell, tableBodyRow, isNew) { this.setTableBodyCellAttributes(rowIdx, rowKey, rowHashCode, columnIdx, tableBodyCell); if (isNew) { // if it's a new row then the cells are appended in order // so don't bother trying to find the position to insert to $(tableBodyRow).append(tableBodyCell); //@HTMLUpdateOK return tableBodyCell; } if (columnIdx == 0) { // insert right after the acc cell var accSelectionCell = tableBodyRow.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_CELL_ACC_SELECT_CLASS); if (accSelectionCell != null && accSelectionCell.length > 0) { $(accSelectionCell[0]).after(tableBodyCell); //@HTMLUpdateOK } else { // just prepend it tableBodyRow.prepend(tableBodyCell); //@HTMLUpdateOK } } else { var tableBodyCells = $(tableBodyRow).children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_CELL_CLASS); if (tableBodyCells.length >= columnIdx) { var previousCell = $(tableBodyCells.get(columnIdx - 1)); previousCell.after(tableBodyCell); //@HTMLUpdateOK } else { $(tableBodyRow).append(tableBodyCell); //@HTMLUpdateOK } } return tableBodyCell; }; /** * Insert a tr element in the appropriate place in the DOM * @param {number} rowIdx row index * @param {jQuery} tableBodyRow DOM element * @param {Object} row row and key object * @param {Object} docFrag document fragment */ oj.TableDomUtils.prototype.insertTableBodyRow = function(rowIdx, tableBodyRow, row, docFrag) { this.setTableBodyRowAttributes(row, tableBodyRow); if (docFrag == null) { var tableBody = this.getTableBody(); var tableBodyRows = tableBody.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_CLASS); if (rowIdx == 0) { // just prepend it tableBody.prepend(tableBodyRow); //@HTMLUpdateOK } else if (tableBodyRows.length >= rowIdx) { var previousRow = $(tableBodyRows.get(rowIdx - 1)); previousRow.after(tableBodyRow); //@HTMLUpdateOK } else { tableBody.append(tableBodyRow); //@HTMLUpdateOK } } else { docFrag.append(tableBodyRow); //@HTMLUpdateOK } this.clearCachedDomRowData(); }; /** * Insert a td element in the appropriate place in the DOM * @param {number} columnIdx column index * @param {jQuery} tableFooterCell DOM element */ oj.TableDomUtils.prototype.insertTableFooterCell = function(columnIdx, tableFooterCell) { var tableFooterRow = this.getTableFooterRow(); var tableFooterCells = $(tableFooterRow).children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_FOOTER_CELL_CLASS); if (columnIdx == 0) { // insert right after the acc cell var accFooterCell = tableFooterRow.children('.' + oj.TableDomUtils.CSS_CLASSES._HIDDEN_CONTENT_ACC_CLASS); if (accFooterCell != null && accFooterCell.length > 0) { $(accFooterCell[0]).after(tableFooterCell); //@HTMLUpdateOK } else { // just prepend it tableFooterRow.prepend(tableFooterCell); //@HTMLUpdateOK } } else if (tableFooterRow.length >= columnIdx) { var previousCell = $(tableFooterCells.get(columnIdx - 1)); previousCell.after(tableFooterCell); //@HTMLUpdateOK } else { tableFooterRow.append(tableFooterCell); //@HTMLUpdateOK } return tableFooterCell; }; /** * Insert a th element in the appropriate place in the DOM * @param {number} columnIdx column index * @param {jQuery} tableHeaderColumn DOM element */ oj.TableDomUtils.prototype.insertTableHeaderColumn = function(columnIdx, tableHeaderColumn) { var tableHeaderRow = this.getTableHeaderRow(); var tableHeaderColumns = this.getTableHeaderColumns(); // save the column index on the element this.setTableHeaderColumnAttributes(columnIdx, tableHeaderColumn); // if there is an existing th at the index then replace it var oldTableHeaderColumn = this.getTableHeaderColumn(columnIdx); if (oldTableHeaderColumn) oldTableHeaderColumn.replaceWith(tableHeaderColumn); //@HTMLUpdateOK else { if (columnIdx == 0) { // insert right after the acc column var accSelectionColumn = tableHeaderRow.children('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ACC_SELECT_ROW_CLASS); if (accSelectionColumn != null && accSelectionColumn.length > 0) { $(accSelectionColumn[0]).after(tableHeaderColumn); //@HTMLUpdateOK } else { // just prepend it tableHeaderRow.prepend(tableHeaderColumn); //@HTMLUpdateOK } } else if (tableHeaderColumns.length >= columnIdx) { var previousColumn = $(tableHeaderColumns.get(columnIdx - 1)); previousColumn.after(tableHeaderColumn); //@HTMLUpdateOK } else { tableHeaderRow.append(tableHeaderColumn); //@HTMLUpdateOK } } }; /** * Returns true if a div scroller is used. False if tbody scrolling is used. * @return {boolean} Whether div scroller is used */ oj.TableDomUtils.prototype.isDivScroller = function() { return this._isIE() && this._isIE() < 10 ? true : false; } /** * Returns true if scrollHeight > clientHeight for height and width. * @return {Array} First element is height boolean, followed by width boolean. */ oj.TableDomUtils.prototype.isTableContainerScrollable = function() { var tableContainer = this.getTableContainer(); var table = this.getTable(); var tableStatusMessage = this.getTableStatusMessage(); var tableStatusMessageDisplay = tableStatusMessage.css(oj.TableDomUtils.CSS_PROP._DISPLAY).toString(); tableStatusMessage.css(oj.TableDomUtils.CSS_PROP._DISPLAY, oj.TableDomUtils.CSS_VAL._NONE); var result = []; if (tableContainer[0].clientHeight > 0) { // don't use tableContainer[0].scrollHeight as it may not be accurate if (table[0].clientHeight > tableContainer[0].clientHeight) { // overflow result[0] = 1; } else if (tableContainer[0].clientHeight - table[0].clientHeight > 1) { // underflow result[0] = -1; } else { result[0] = 0; } } else { result[0] = 0; } if (tableContainer[0].clientWidth > 0) { if (table[0].clientWidth > tableContainer[0].clientWidth) { // overflow result[1] = 1; } else if (tableContainer[0].clientWidth - table[0].clientWidth > 1) { // underflow result[1] = -1; } else { result[1] = 0; } } else { result[1] = 0; } tableStatusMessage.css(oj.TableDomUtils.CSS_PROP._DISPLAY, tableStatusMessageDisplay); return result; } /** * Move the top touch affordance to the table row. * @param {number} rowIdx row index */ oj.TableDomUtils.prototype.moveTableBodyRowTouchSelectionAffordanceTop = function(rowIdx) { var topAffordance = this.getTableBodyRowTouchSelectionAffordanceTop(); if (topAffordance != null) { topAffordance.data('rowIdx', rowIdx); $(topAffordance.children()[0]).data('rowIdx', rowIdx); var tableBody = this.getTableBody(); var tableBodyRow = this.getTableBodyRow(rowIdx); var tableBodyRowRect = tableBodyRow[0].getBoundingClientRect(); var tableContainer = this.getTableContainer(); var tableContainerRect = tableContainer[0].getBoundingClientRect(); topAffordance.css(oj.TableDomUtils.CSS_PROP._TOP, tableBodyRowRect.top - tableContainerRect.top - topAffordance.height() / 2); topAffordance.css(oj.TableDomUtils.CSS_PROP._LEFT, tableBody.width() / 2 + oj.TableDomUtils.CSS_VAL._PX); } }; /** * Move the bottom touch affordance to the table row. * @param {number} rowIdx row index */ oj.TableDomUtils.prototype.moveTableBodyRowTouchSelectionAffordanceBottom = function(rowIdx) { var bottomAffordance = this.getTableBodyRowTouchSelectionAffordanceBottom(); if (bottomAffordance != null) { bottomAffordance.data('rowIdx', rowIdx); $(bottomAffordance.children()[0]).data('rowIdx', rowIdx); var tableBody = this.getTableBody(); var tableBodyRow = this.getTableBodyRow(rowIdx); var tableBodyRowRect = tableBodyRow[0].getBoundingClientRect(); var tableContainer = this.getTableContainer(); var tableContainerRect = tableContainer[0].getBoundingClientRect(); bottomAffordance.css(oj.TableDomUtils.CSS_PROP._TOP, tableBodyRowRect.top - tableContainerRect.top + tableBodyRowRect.height - bottomAffordance.height() / 2); bottomAffordance.css(oj.TableDomUtils.CSS_PROP._LEFT, tableBody.width() / 2 + oj.TableDomUtils.CSS_VAL._PX); } }; /** * Move the column to the destination index. If there is already a column at destIdx, * then insert before it. * @param {number} columnIdx column index * @param {number} destIdx column index * @param {Object} event * @return {Array} Array of moved columns map */ oj.TableDomUtils.prototype.moveTableHeaderColumn = function(columnIdx, destIdx, event) { var columns = this.component._getColumnDefs(); var tableHeaderColumn = this.getTableHeaderColumn(columnIdx); var tableFooterCell = this.getTableFooterCell(columnIdx); var tableBodyCell = null; var destTableHeaderColumn = null; var destTableFooterCell = null; var destTableBodyCell = null; var colSpan = null; var afterColumn = false; if (destIdx == columns.length) { destIdx = destIdx - 1; afterColumn = true; } if (tableHeaderColumn != null) { colSpan = tableHeaderColumn.attr(oj.TableDomUtils.DOM_ATTR._COLSPAN); destTableHeaderColumn = this.getTableHeaderColumn(destIdx); if (destTableHeaderColumn != null && (colSpan == null || colSpan == 1)) { if (afterColumn) { destTableHeaderColumn.after(tableHeaderColumn); //@HTMLUpdateOK } else { destTableHeaderColumn.before(tableHeaderColumn); //@HTMLUpdateOK } } } if (tableFooterCell != null) { colSpan = tableFooterCell.attr(oj.TableDomUtils.DOM_ATTR._COLSPAN); destTableFooterCell = this.getTableFooterCell(destIdx); if (destTableFooterCell != null && (colSpan == null || colSpan == 1)) { if (afterColumn) { destTableFooterCell.after(tableFooterCell); //@HTMLUpdateOK } else { destTableFooterCell.before(tableFooterCell); //@HTMLUpdateOK } } } var tableBodyRows = this.getTableBodyRows(); if (tableBodyRows != null) { var i; for (i = 0; i < tableBodyRows.length; i++) { tableBodyCell = this.getTableBodyCell(i, columnIdx, null); if (tableBodyCell != null) { destTableBodyCell = this.getTableBodyCell(i, destIdx, null); colSpan = tableBodyCell.attr(oj.TableDomUtils.DOM_ATTR._COLSPAN); if (destTableBodyCell != null && (colSpan == null || colSpan == 1)) { if (afterColumn) { destTableBodyCell.after(tableBodyCell); //@HTMLUpdateOK } else { destTableBodyCell.before(tableBodyCell); //@HTMLUpdateOK } } } } } // update options var columnsOption = this.options['columns']; var destColIdx = columnIdx < destIdx && !afterColumn ? destIdx - 1 : destIdx; var columnOption = columnsOption.splice(columnIdx, 1); columnsOption.splice(destColIdx, 0, columnOption[0]); // re-order the column definition metadata var columnDef = this.component._columnDefArray.splice(columnIdx, 1); this.component._columnDefArray.splice(destColIdx, 0, columnDef[0]); if (!this._columnsDestMap) { this._columnsDestMap = []; var i; for (i = 0; i < columnsOption.length; i++) { this._columnsDestMap[i] = i; } } var columnsDestMapItem = this._columnsDestMap.splice(columnIdx, 1); this._columnsDestMap.splice(destColIdx, 0, columnsDestMapItem[0]); // clone the array so we can trigger that it's changed columnsOption = columnsOption.slice(0); this.component.option('columns', columnsOption, {'_context': {writeback: true, originalEvent: event, internalSet: true}}); this.component._queueTask(function(){}); return this._columnsDestMap; } /** * Refresh any translated strings in the context menu. */ oj.TableDomUtils.prototype.refreshContextMenu = function() { var self = this; var menuContainer = this._menuContainer; if (menuContainer && menuContainer.length > 0) { var listItems = menuContainer.find('[data-oj-command]'); listItems.each(function() { var contextMenuLabel = $(this).children(oj.TableDomUtils.DOM_ELEMENT._A); if (contextMenuLabel.length > 0) { var command = $(this).attr('data-oj-command').split("-"); command = command[command.length - 1]; var commandString; if (command == 'sort') { commandString = self.component.getTranslatedString('labelSort'); } else if (command == 'sortAsc') { commandString = self.component.getTranslatedString('labelSortAsc'); } else if (command == 'sortDsc') { commandString = self.component.getTranslatedString('labelSortDsc'); } contextMenuLabel.contents().filter(function() {return this.nodeType === 3;})[0].nodeValue = commandString; } }); } }; /** * Refresh the table dimensions * @param {number|null} width table container width * @param {number|null} height table container height * @param {boolean} resetScrollTop reset the scrollTop * @param {boolean} resetScrollLeft reset the scrollLeft */ oj.TableDomUtils.prototype.refreshTableDimensions = function(width, height, resetScrollTop, resetScrollLeft) { // remove resize listeners to prevent triggering resize notifications this.component._unregisterResizeListener(); this._refreshTableDimensions(width, height, resetScrollTop, resetScrollLeft); this.component._registerResizeListener(); // set the current row this.component._setCurrentRow(this.options['currentRow'], null); }; /** * Remove the visual indicator for column drag over */ oj.TableDomUtils.prototype.removeDragOverIndicatorColumn = function() { var table = this.getTable(); var indicatorElements = table.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DRAG_INDICATOR_BEFORE_CLASS + ',' + '.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DRAG_INDICATOR_AFTER_CLASS); var i = 0; if (indicatorElements && indicatorElements.length > 0) { var indicatorElementsCount = indicatorElements.length; for (i = 0; i < indicatorElementsCount; i++) { $(indicatorElements[i]).removeClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DRAG_INDICATOR_BEFORE_CLASS); $(indicatorElements[i]).removeClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DRAG_INDICATOR_AFTER_CLASS); } } } /** * Remove the visual indicator for row drag over */ oj.TableDomUtils.prototype.removeDragOverIndicatorRow = function() { var tableBody = this.getTableBody(); var indicatorRowBeforeElements = tableBody.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_DRAG_INDICATOR_BEFORE_CLASS); var indicatorRowAfterElements = tableBody.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_DRAG_INDICATOR_AFTER_CLASS); var i = 0; if (indicatorRowBeforeElements && indicatorRowBeforeElements.length > 0) { var indicatorRowBeforeElementsCount = indicatorRowBeforeElements.length; for (i = 0; i < indicatorRowBeforeElementsCount; i++) { $(indicatorRowBeforeElements[i]).remove(); } } if (indicatorRowAfterElements && indicatorRowAfterElements.length > 0) { var indicatorRowAfterElementsCount = indicatorRowAfterElements.length; for (i = 0; i < indicatorRowAfterElementsCount; i++) { $(indicatorRowAfterElements[i]).remove(); } } var tableBodyRows = this.getTableBodyRows(); if (tableBodyRows == null || tableBodyRows.length == 0) { this.component._showNoDataMessage(); } } /** * Remove a tr element from the tbody DOM * @param {number} rowIdx row index */ oj.TableDomUtils.prototype.removeTableBodyRow = function(rowIdx) { var tableBodyRow = this.getTableBodyRow(rowIdx); if (tableBodyRow != null) { oj.Components.subtreeDetached(tableBodyRow[0]); tableBodyRow.remove(); this.clearCachedDomRowData(); } }; /** * Remove all tr elements from the tbody DOM */ oj.TableDomUtils.prototype.removeAllTableBodyRows = function() { var tableBodyRows = this.getTableBodyRows(); if (tableBodyRows != null && tableBodyRows.length > 0) { var tableBody = this.getTableBody(); oj.Components.subtreeDetached(tableBody[0]); tableBody.empty(); this.clearCachedDomRowData(); } }; /** * Finds and removes the touch selection icons from the DOM * @private */ oj.TableDomUtils.prototype.removeTableBodyRowTouchSelectionAffordance = function() { var tableContainer = this.getTableContainer(); var touchAffordance = tableContainer.children('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_TOUCH_SELECTIOM_AFFORDANCE_TOUCH_AREA_CLASS); if (touchAffordance != null && touchAffordance.length > 0) { var i; for (i = 0; i < touchAffordance.length; i++) { touchAffordance[i].remove(); } } }; /** * Remove the drag image for the column */ oj.TableDomUtils.prototype.removeTableHeaderColumnDragImage = function() { var tableContainer = this.getTableContainer(); var headerDragImage = tableContainer.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DRAG_IMAGE); if (headerDragImage && headerDragImage.length > 0) { var i; var headerDragImageCount = headerDragImage.length; for (i = 0; i < headerDragImageCount; i++) { $(headerDragImage[i]).remove(); } } }; /** * Set the element scrollLeft * @param {jQuery} element DOM element * @param {number} scrollLeft scrollLeft */ oj.TableDomUtils.prototype.setScrollLeft = function(element, scrollLeft) { element = $(element); if (this.component._GetReadingDirection() === "rtl") { scrollLeft = Math.abs(scrollLeft); if (this._isWebkit()) { var maxScrollLeft = element[0].scrollWidth - element[0].clientWidth; scrollLeft = maxScrollLeft - scrollLeft; } else if (this._isFF()) { scrollLeft = -1 * scrollLeft; } } if (element[0].scrollLeft != scrollLeft) { element[0].scrollLeft = scrollLeft; } } /** * Set the attributes on the cell * @param {number} rowIdx row index * @param {Object} rowKey row key * @param {Object} rowHashCode row hash code * @param {number} columnIdx column index * @param {jQuery} tableBodyCell td DOM element */ oj.TableDomUtils.prototype.setTableBodyCellAttributes = function(rowIdx, rowKey, rowHashCode, columnIdx, tableBodyCell) { var accessibility = this.options['accessibility']; var column = this.component._getColumnDefs()[columnIdx]; if (column == null) { return; } var rowHeaderColumnId = null; var isTableHeaderless = this.getTableHeader() == null ? true : false; if (accessibility != null && accessibility['rowHeader'] != null) { rowHeaderColumnId = accessibility['rowHeader']; } else { rowHeaderColumnId = this.component._getColumnDefs()[0].id; } var rowKeyStr = rowKey != null ? rowKey.toString() : rowIdx.toString(); var rowKeyStrHashCode = rowHashCode == null ? this.hashCode(rowKeyStr) : rowHashCode; var cellRowHeaderId = this.getTableId() + ':' + rowHeaderColumnId + '_' + rowKeyStrHashCode; var headers = this.getTableId() + ':' + column.id; if (rowHeaderColumnId == column.id) { tableBodyCell.attr(oj.TableDomUtils.DOM_ATTR._ID, cellRowHeaderId); if (isTableHeaderless) { headers = ''; } } else { if (!isTableHeaderless) { headers = headers + ' ' + cellRowHeaderId; } else { headers = cellRowHeaderId; } } if (!tableBodyCell.attr(oj.TableDomUtils.DOM_ATTR._HEADERS)) { tableBodyCell.attr(oj.TableDomUtils.DOM_ATTR._HEADERS, headers); } }; /** * Set the attributes on the row like rowIdx, etc * @param {Object} row row * @param {jQuery} tableBodyRow tr DOM element */ oj.TableDomUtils.prototype.setTableBodyRowAttributes = function(row, tableBodyRow) { tableBodyRow.data('rowKey', row['key']); tableBodyRow.data('rowData', row['data']); }; /** * Set the attributes on the header like columndx, etc * @param {number} columnIdx column index * @param {jQuery} tableHeaderColumn th DOM element */ oj.TableDomUtils.prototype.setTableHeaderColumnAttributes = function(columnIdx, tableHeaderColumn) { var column = this.component._getColumnDefs()[columnIdx]; if (!tableHeaderColumn.attr(oj.TableDomUtils.DOM_ATTR._ID)) { tableHeaderColumn.attr(oj.TableDomUtils.DOM_ATTR._ID, this.getTableId() + ':' + column.id); } }; /** * Set the css class from all the cells in a column with the styleClass * @param {number|null} columnIdx column index * @param {boolean} add add or remove the class * @param {string} styleClass style class */ oj.TableDomUtils.prototype.setTableColumnCellsClass = function(columnIdx, add, styleClass) { var tableBodyRows = this.getTableBodyRows(); if (tableBodyRows != null && tableBodyRows.length > 0) { if (columnIdx === null) { var tableBodyCells = null; if (!add) { tableBodyCells = this.getTableBody().find('.' + styleClass); } else { tableBodyCells = this.getTableBody().find('[td]'); } if (tableBodyCells != null && tableBodyCells.length > 0) { var i, tableBodyCellsCount = tableBodyCells.length; for (i = 0; i < tableBodyCellsCount; i++) { if (!add) { $(tableBodyCells[i]).removeClass(styleClass); } else { $(tableBodyCells[i]).addClass(styleClass); } } } } else { var i, tableBodyCell, tableBodyRowsCount = tableBodyRows.length; for (i = 0; i < tableBodyRowsCount; i++) { tableBodyCell = this.getTableBodyCell(i, columnIdx, null); if (!add) { $(tableBodyCell).removeClass(styleClass); } else { $(tableBodyCell).addClass(styleClass); } } } } }; /** * Set the table body message. * @param {string} message */ oj.TableDomUtils.prototype.setTableBodyMessage = function(message) { var tableBodyMessageCell = this.getTableBodyMessageCell(); tableBodyMessageCell.empty(); tableBodyMessageCell.append(message); //@HTMLUpdateOK }; /** * Set the table inline message. * @param {string} summary * @param {string} detail * @param {number} severityLevel */ oj.TableDomUtils.prototype.setTableInlineMessage = function(summary, detail, severityLevel) { var inlineMessage = this.getTableInlineMessage(); inlineMessage.empty(); inlineMessage.append(oj.PopupMessagingStrategyUtils.buildMessageHtml(document, summary, detail, severityLevel, null)); //@HTMLUpdateOK }; /** * Set the table accessibility notification. * @param {string} status */ oj.TableDomUtils.prototype.setTableStatusAccNotification = function(status) { var statusNotification = this.getTableStatusAccNotification(); statusNotification.empty(); statusNotification.append(status); //@HTMLUpdateOK } /** * Style the initial table */ oj.TableDomUtils.prototype.styleInitialTable = function() { var table = this.getTable(); var tableContainer = this.getTableContainer(); var tableHeader = table.children(oj.TableDomUtils.DOM_ELEMENT._THEAD); tableHeader = tableHeader.length > 0 ? $(tableHeader[0]) : null; var tableFooter = table.children(oj.TableDomUtils.DOM_ELEMENT._TFOOT); tableFooter = tableFooter.length > 0 ? $(tableFooter[0]) : null; var tableBody = table.children(oj.TableDomUtils.DOM_ELEMENT._TBODY); tableBody = tableBody.length > 0 ? $(tableBody[0]) : null; // set the tabindex table.attr(oj.TableDomUtils.DOM_ATTR._TABINDEX, '0'); // set focusable this.component._focusable(table); // set focusable this.component._focusable(tableContainer); this.styleTableHeader(tableHeader); this.styleTableFooter(tableFooter); this.styleTableBody(tableBody); }; /** * Style the tbody element * @param {jQuery} tableBody thead DOM element */ oj.TableDomUtils.prototype.styleTableBody = function(tableBody) { tableBody.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_BODY_CLASS); // Add a special marker attribute to tell child components that they are container within table tableBody.attr(oj.Components._OJ_CONTAINER_ATTR, this.component['widgetName']); }; /** * Style the td element * @param {number} columnIdx column index * @param {jQuery} tableBodyCell td DOM element * @param {boolean} isNew is new cell */ oj.TableDomUtils.prototype.styleTableBodyCell = function(columnIdx, tableBodyCell, isNew) { var options = this.options; var column = this.component._getColumnDefs()[columnIdx]; if (isNew || !tableBodyCell.hasClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_CELL_CLASS)) { tableBodyCell.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_CELL_CLASS); tableBodyCell.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATE_CELL_FORM_CONTROL_CLASS); // add the column option stuff in here since we only want to do this once when adding // the table data cell class. Column option styling or class can be overridden // later in a custom renderer if (column != null && column.style != null && (isNew || tableBodyCell.attr(oj.TableDomUtils.DOM_ATTR._STYLE) != column.style)) { tableBodyCell.attr(oj.TableDomUtils.DOM_ATTR._STYLE, column.style); } if (column != null && column.className != null && (isNew || !tableBodyCell.hasClass(column.className))) { tableBodyCell.addClass(column.className); } } if (this._isVerticalGridEnabled()) { if (isNew || !tableBodyCell.hasClass(oj.TableDomUtils.CSS_CLASSES._TABLE_VGRID_LINES_CLASS)) { tableBodyCell.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_VGRID_LINES_CLASS); } } }; /** * Style the tr element * @param {jQuery} tableBodyRow tr DOM element * @param {boolean} isNew is new row */ oj.TableDomUtils.prototype.styleTableBodyRow = function(tableBodyRow, isNew) { if (isNew || !tableBodyRow.hasClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_CLASS)) { tableBodyRow.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_CLASS); } if (this._isHorizontalGridEnabled()) { if (isNew || !tableBodyRow.hasClass(oj.TableDomUtils.CSS_CLASSES._TABLE_HGRID_LINES_CLASS)) { tableBodyRow.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_HGRID_LINES_CLASS); } } }; /** * Style the table container * @param {jQuery} tableContainer div DOM element */ oj.TableDomUtils.prototype.styleTableContainer = function(tableContainer) { // add main css class to container tableContainer.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_CLASS); tableContainer.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_CONTAINER_CLASS); tableContainer.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._WIDGET); if (this.options.display == oj.TableDomUtils._OPTION_DISPLAY._GRID) { tableContainer.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_COMPACT_CLASS); } else { tableContainer.removeClass(oj.TableDomUtils.CSS_CLASSES._TABLE_COMPACT_CLASS); } var editMode = this.options['editMode']; if (editMode != null && editMode != this.component._OPTION_EDIT_MODE._NONE) { tableContainer.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_EDIT_CLASS); } else { tableContainer.removeClass(oj.TableDomUtils.CSS_CLASSES._TABLE_EDIT_CLASS); } }; /** * Style the tfoot element * @param {jQuery} tableFooter tfoot DOM element */ oj.TableDomUtils.prototype.styleTableFooter = function(tableFooter) { if (!tableFooter) { return; } tableFooter.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_FOOTER_CLASS); var tableFooterRow = $(tableFooter.children(oj.TableDomUtils.DOM_ELEMENT._TR)[0]); tableFooterRow.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_FOOTER_ROW_CLASS); }; /** * Style the td element * @param {number} columnIdx column index * @param {jQuery} tableFooterCell td DOM element */ oj.TableDomUtils.prototype.styleTableFooterCell = function(columnIdx, tableFooterCell) { var options = this.options; var lastColumn = columnIdx == this.component._getColumnDefs().length - 1 ? true : false; var column = this.component._getColumnDefs()[columnIdx]; tableFooterCell.attr(oj.TableDomUtils.DOM_ATTR._STYLE, column.footerStyle); if (!tableFooterCell.hasClass(oj.TableDomUtils.CSS_CLASSES._TABLE_FOOTER_CELL_CLASS)) { tableFooterCell.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_FOOTER_CELL_CLASS); } if (this._isVerticalGridEnabled() && !tableFooterCell.hasClass(oj.TableDomUtils.CSS_CLASSES._TABLE_VGRID_LINES_CLASS)) { tableFooterCell.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_VGRID_LINES_CLASS); } if (column.footerClassName) { tableFooterCell.addClass(column.footerClassName); } }; /** * Style the thead element * @param {jQuery} tableHeader thead DOM element */ oj.TableDomUtils.prototype.styleTableHeader = function(tableHeader) { if (!tableHeader) { return; } tableHeader.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_HEADER_CLASS); tableHeader.css(oj.TableDomUtils.CSS_PROP._DISPLAY, 'table-header-group'); var tableHeaderRow = $(tableHeader.children(oj.TableDomUtils.DOM_ELEMENT._TR)[0]); tableHeaderRow.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_HEADER_ROW_CLASS); tableHeaderRow.css(oj.TableDomUtils.CSS_PROP._POSITION, oj.TableDomUtils.CSS_VAL._RELATIVE); }; /** * Style the th element * @param {number} columnIdx column index * @param {jQuery} tableHeaderColumn th DOM element * @param {string} columnSelectionMode column selection mode * @param {boolean} isNew is new column */ oj.TableDomUtils.prototype.styleTableHeaderColumn = function(columnIdx, tableHeaderColumn, columnSelectionMode, isNew) { var column = this.component._getColumnDefs()[columnIdx]; if (isNew || !tableHeaderColumn.hasClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_CELL_CLASS)) { tableHeaderColumn.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_CELL_CLASS); if (this._isVerticalGridEnabled()) { if (isNew || !tableHeaderColumn.hasClass(oj.TableDomUtils.CSS_CLASSES._TABLE_VGRID_LINES_CLASS)) { tableHeaderColumn.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_VGRID_LINES_CLASS); } } if (column.headerStyle != null && (isNew || tableHeaderColumn.attr(oj.TableDomUtils.DOM_ATTR._STYLE) != column.headerStyle)) { tableHeaderColumn.attr(oj.TableDomUtils.DOM_ATTR._STYLE, column.headerStyle); } if (column.headerClassName != null && (isNew || !tableHeaderColumn.hasClass(column.headerClassName))) { tableHeaderColumn.addClass(column.headerClassName); } } }; /** * Return all the colspanned logical elements * @param {jQuery} elementArray jQuery array of jQuery DOM elements * @return {jQuery|null} jQuery array of DOM elements */ oj.TableDomUtils.prototype._getColspanLogicalElements = function(elementArray) { var i, j, indexedElementArrayNum = 0, indexedElementArray = []; var elementArrayCount = elementArray.length; for (i = 0; i < elementArrayCount; i++) { var colSpan = $(elementArray[i]).attr(oj.TableDomUtils.DOM_ATTR._COLSPAN); if (colSpan != null) { colSpan = parseInt(colSpan, 10); for (j = 0; j < colSpan; j++) { indexedElementArray[indexedElementArrayNum + j] = elementArray[i]; } indexedElementArrayNum = indexedElementArrayNum + colSpan; } else { indexedElementArray[indexedElementArrayNum++] = elementArray[i]; } } return $(indexedElementArray); } /** * Helper function which returns if the horizontal grid lines are enabled. * @private * @return {boolean} enabled */ oj.TableDomUtils.prototype._isHorizontalGridEnabled = function() { if (this.options.horizontalGridVisible == oj.TableDomUtils._OPTION_ENABLED || this.options.horizontalGridVisible == oj.TableDomUtils._OPTION_AUTO) { return true; } return false; }; /** * Helper function which returns if the vertical grid lines are enabled. * @private * @return {boolean} enabled */ oj.TableDomUtils.prototype._isVerticalGridEnabled = function() { if (this.options.verticalGridVisible == oj.TableDomUtils._OPTION_ENABLED || (this.options.verticalGridVisible == oj.TableDomUtils._OPTION_AUTO && this.options.display == oj.TableDomUtils._OPTION_DISPLAY._GRID)) { return true; } return false; }; /** * Helper function which returns if the browser is FF * @private * @return {boolean} FF */ oj.TableDomUtils.prototype._isFF = function() { if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) { return true; } return false; }; /** * Helper function which returns if the browser is IE and if so the version. * @private * @return {number|null} IE version. null if not IE. */ oj.TableDomUtils.prototype._isIE = function() { if (typeof this._browserIsIE == 'undefined') { var userAgent = navigator.userAgent; if (navigator.appName == 'Microsoft Internet Explorer') { var resultArray = (new RegExp('MSIE ([0-9]{1,}[\.0-9]{0,})')).exec(userAgent); if (resultArray != null) { this._browserIsIE = parseFloat(resultArray[1]); } } else if (userAgent.indexOf('Trident') >= 0) { this._browserIsIE = 11; } else { this._browserIsIE = null; } } return this._browserIsIE; }; /** * Helper function which returns if the browser is webkit. * @private * @return {boolean} webkit */ oj.TableDomUtils.prototype._isWebkit = function() { if (typeof this._browserIsWebkit == 'undefined') { var ua = navigator.userAgent.toLowerCase(); this._browserIsWebkit = (/webkit/.test(ua)) && !(/edge/.test(ua)); } return this._browserIsWebkit; }; /** * Refresh the table dimensions * @param {number|null} width table container width * @param {number|null} height table container height * @param {boolean} resetScrollTop reset the scrollTop * @param {boolean} resetScrollLeft reset the scrollLeft */ oj.TableDomUtils.prototype._refreshTableDimensions = function(width, height, resetScrollTop, resetScrollLeft) { var options = this.options; var table = this.getTable(); var tableHeader = this.getTableHeader(); var tableFooter = this.getTableFooter(); var tableFooterRow = this.getTableFooterRow(); var tableHeaderRow = this.getTableHeaderRow(); var tableContainer = this.getTableContainer(); var tableBody = this.getTableBody(); // preserve the scrollTop & scrollLeft var scrollTop = null; var scrollLeft = null; if (this.getScroller() != null) { var maxScrollTop = this.getScroller()[0].scrollHeight - this.getScroller()[0].clientHeight; var maxScrollLeft = this.getScroller()[0].scrollWidth - this.getScroller()[0].clientWidth; // only preserve the scroll positions if we can actually scroll if (maxScrollTop > 0) { scrollTop = this.getScroller()[0].scrollTop; } if (maxScrollLeft > 0) { scrollLeft = this.getScrollLeft(this.getScroller()[0]); } } // first remove any styling so that the browser sizes the table this._removeTableDimensionsStyling(); this.styleTableContainer(tableContainer); var tableContainerScrollableState = this.isTableContainerScrollable(); if (tableContainerScrollableState[0] === 1) { this._tableHeightConstrained = true; } else { this._tableHeightConstrained = false; } if (tableContainerScrollableState[1] === 1) { this._tableWidthConstrained = true; } else { this._tableWidthConstrained = false; } if (tableBody == null) { return; } if (this._tableHeightConstrained || this._tableWidthConstrained) { // Add the oj-table-scroll class because some styling only applies // to scrollable table. tableContainer.addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_SCROLL_CLASS); if (!this._tableDimensions) { this._tableDimensions = {}; } // use constants for width height if (width > 0 || height > 0) { if (width > 0 && this._tableWidthConstrained) { this._tableDimensions[oj.TableDomUtils.CSS_PROP._WIDTH] = width; } if (height > 0 && this._tableHeightConstrained) { this._tableDimensions[oj.TableDomUtils.CSS_PROP._HEIGHT] = height; } } else { if (this._tableHeightConstrained) { this._tableDimensions[oj.TableDomUtils.CSS_PROP._HEIGHT] = tableContainer[0].offsetHeight; } else { this._tableDimensions[oj.TableDomUtils.CSS_PROP._HEIGHT] = 0; } if (this._tableWidthConstrained) { this._tableDimensions[oj.TableDomUtils.CSS_PROP._WIDTH] = tableContainer[0].offsetWidth; } else { this._tableDimensions[oj.TableDomUtils.CSS_PROP._WIDTH] = 0; } } if (!this._tableBorderWidth) { this._tableBorderWidth = tableContainer.outerWidth() - tableContainer.innerWidth(); } if (!this._tableBorderHeight) { this._tableBorderHeight = tableContainer.outerHeight() - tableContainer.innerHeight(); } // if there is a vertical scrollbar but no horizontal scrollbar then we need // to make sure the width sizes to accommodate the scrollbar var tableContainerScrollbarWidth = 0; if (this._tableHeightConstrained && !this._tableWidthConstrained) { tableContainer.css(oj.TableDomUtils.CSS_PROP._OVERFLOW, oj.TableDomUtils.CSS_VAL._AUTO); tableContainerScrollbarWidth = tableContainer.get(0).offsetWidth - tableContainer.get(0).clientWidth; // if tableContainer has set width then we need to shrink, otherwise we can expand if (this._tableDimensions[oj.TableDomUtils.CSS_PROP._WIDTH] > 0) { table.css(oj.TableDomUtils.CSS_PROP._WIDTH, tableContainer.get(0).clientWidth + oj.TableDomUtils.CSS_VAL._PX); } else { table.css(oj.TableDomUtils.CSS_PROP._WIDTH, tableContainer.get(0).scrollWidth + tableContainerScrollbarWidth + oj.TableDomUtils.CSS_VAL._PX); // check if we caused overflow tableContainerScrollableState = this.isTableContainerScrollable(); if (tableContainerScrollableState[1] === 1) { // if we caused overflow we need to shrink so that we can set the column widths to the width without // the scrollbar table.css(oj.TableDomUtils.CSS_PROP._WIDTH, tableContainer.get(0).clientWidth + oj.TableDomUtils.CSS_VAL._PX); } } tableContainer.css(oj.TableDomUtils.CSS_PROP._OVERFLOW, ''); } var tableWidth = table.width(); // let the browser layout the column widths this._setColumnWidths(); if (tableContainerScrollbarWidth > 0) { // if the container scrollbar width > 0 that means that we have overflow even though we're not width constrained // so we've set table width to table container clientWidth to set the column widths to accommodate the vertical scrollbar // so we can set the table back to container offset width table.css(oj.TableDomUtils.CSS_PROP._WIDTH, tableContainer.get(0).offsetWidth + oj.TableDomUtils.CSS_VAL._PX); } var captionHeight = 0; var caption = table.children('caption'); if (caption != null && caption.length > 0) { captionHeight = $(caption[0]).outerHeight(); caption.css(oj.TableDomUtils.CSS_PROP._DISPLAY, oj.TableDomUtils.CSS_VAL._INLINE); if (tableHeader != null) { tableHeader.css(oj.TableDomUtils.CSS_PROP._BORDER_TOP, tableContainer.css(oj.TableDomUtils.CSS_PROP._BORDER_TOP).toString()); } } // apply the styling which sets the fixed column headers, etc var tableHeaderHeight = 0; if (tableHeader != null) { tableHeader.css(oj.TableDomUtils.CSS_PROP._DISPLAY, oj.TableDomUtils.CSS_VAL._BLOCK); if (!this.isDivScroller()) { tableHeader.css(oj.TableDomUtils.CSS_PROP._POSITION, oj.TableDomUtils.CSS_VAL._RELATIVE); } else { tableHeader.css(oj.TableDomUtils.CSS_PROP._POSITION, oj.TableDomUtils.CSS_VAL._ABSOLUTE); tableHeader.css(oj.TableDomUtils.CSS_PROP._TOP, '0px'); } tableHeaderRow.css(oj.TableDomUtils.CSS_PROP._DISPLAY, oj.TableDomUtils.CSS_VAL._BLOCK); tableHeaderRow.css(oj.TableDomUtils.CSS_PROP._POSITION, oj.TableDomUtils.CSS_VAL._RELATIVE); tableHeaderHeight = tableHeader.outerHeight(); } if (this.isDivScroller()) { // if we use fallback scrolling then the padding top of the container is used to // position the table scroller to below the table header. tableContainer.css(oj.TableDomUtils.CSS_PROP._PADDING_TOP, tableHeaderHeight + captionHeight + oj.TableDomUtils.CSS_VAL._PX); } var tableFooterHeight = 0; if (tableFooter != null) { if (!this.isDivScroller()) { tableFooter.css(oj.TableDomUtils.CSS_PROP._POSITION, oj.TableDomUtils.CSS_VAL._RELATIVE); } else { tableFooter.css(oj.TableDomUtils.CSS_PROP._POSITION, oj.TableDomUtils.CSS_VAL._ABSOLUTE); tableHeader.css(oj.TableDomUtils.CSS_PROP._BOTTOM, '0px'); } tableFooter.css(oj.TableDomUtils.CSS_PROP._DISPLAY, oj.TableDomUtils.CSS_VAL._BLOCK); tableFooterRow.css(oj.TableDomUtils.CSS_PROP._DISPLAY, oj.TableDomUtils.CSS_VAL._BLOCK); tableFooterRow.css(oj.TableDomUtils.CSS_PROP._POSITION, oj.TableDomUtils.CSS_VAL._RELATIVE); } tableBody.css(oj.TableDomUtils.CSS_PROP._DISPLAY, oj.TableDomUtils.CSS_VAL._BLOCK); var scrollbarWidth; var tableBodyHeight = 0; var tableBodyWidth = 0; if (!this.isDivScroller()) { tableBody.css(oj.TableDomUtils.CSS_PROP._OVERFLOW_Y, oj.TableDomUtils.CSS_VAL._AUTO); tableBody.css(oj.TableDomUtils.CSS_PROP._POSITION, oj.TableDomUtils.CSS_VAL._RELATIVE); if (this._tableWidthConstrained) { tableBody.css(oj.TableDomUtils.CSS_PROP._WIDTH, this._tableDimensions[oj.TableDomUtils.CSS_PROP._WIDTH] - this._tableBorderWidth); } else if (tableContainerScrollbarWidth > 0) { tableBody.css(oj.TableDomUtils.CSS_PROP._WIDTH, tableWidth - this._tableBorderWidth + tableContainerScrollbarWidth); } tableBodyWidth = tableBody.width(); if (tableFooter != null) { tableFooterHeight = tableFooter.outerHeight(); tableBody.css(oj.TableDomUtils.CSS_PROP._TOP, -1 * tableFooterHeight + oj.TableDomUtils.CSS_VAL._PX); } // if we don't use fallback scrolling then size the table body // to fit in the height if (this._tableHeightConstrained) { tableBodyHeight = this._tableDimensions[oj.TableDomUtils.CSS_PROP._HEIGHT] - tableHeaderHeight - tableFooterHeight - captionHeight - this._tableBorderHeight; if (tableBodyHeight > 0) { tableBody.css(oj.TableDomUtils.CSS_PROP._HEIGHT, tableBodyHeight + oj.TableDomUtils.CSS_VAL._PX); tableBody.css(oj.TableDomUtils.CSS_PROP._MIN_HEIGHT, tableBodyHeight + oj.TableDomUtils.CSS_VAL._PX); } } else { tableBodyHeight = tableBody.outerHeight(); } scrollbarWidth = this.getScrollbarWidth(); if (this._tableWidthConstrained) { var tableBodyRows = this.getTableBodyRows(); if (tableBodyRows != null && tableBodyRows.length > 0) { tableBody.css(oj.TableDomUtils.CSS_PROP._OVERFLOW_X, oj.TableDomUtils.CSS_VAL._AUTO); tableContainer.css(oj.TableDomUtils.CSS_PROP._OVERFLOW_X, oj.TableDomUtils.CSS_VAL._HIDDEN); tableContainer.css(oj.TableDomUtils.CSS_PROP._OVERFLOW_Y, oj.TableDomUtils.CSS_VAL._HIDDEN); if (tableHeader != null) { var tableHeaderWidth = this._tableDimensions[oj.TableDomUtils.CSS_PROP._WIDTH] - this._tableBorderWidth; if (tableHeaderWidth > 0) { if (scrollbarWidth > 0) { // if we have scrollbars then size the tableheader // to align with the scrollbars tableHeader.css(oj.TableDomUtils.CSS_PROP._WIDTH, tableHeaderWidth - scrollbarWidth + oj.TableDomUtils.CSS_VAL._PX); } else { tableHeader.css(oj.TableDomUtils.CSS_PROP._WIDTH, tableHeaderWidth + oj.TableDomUtils.CSS_VAL._PX); } } } } else { // if we have no data then use the tableContainer's horizontal scroller tableBody.css(oj.TableDomUtils.CSS_PROP._OVERFLOW_X, oj.TableDomUtils.CSS_VAL._HIDDEN); tableContainer.css(oj.TableDomUtils.CSS_PROP._OVERFLOW_X, oj.TableDomUtils.CSS_VAL._AUTO); tableContainer.css(oj.TableDomUtils.CSS_PROP._OVERFLOW_Y, oj.TableDomUtils.CSS_VAL._HIDDEN); } } else { tableBody.css(oj.TableDomUtils.CSS_PROP._OVERFLOW_X, oj.TableDomUtils.CSS_VAL._HIDDEN); } } if (this.isDivScroller()) { var tableDivScroller = this.getTableDivScroller(); tableDivScroller.css(oj.TableDomUtils.CSS_PROP._OVERFLOW, oj.TableDomUtils.CSS_VAL._AUTO); if (this._tableWidthConstrained) { tableDivScroller.css(oj.TableDomUtils.CSS_PROP._WIDTH, this._tableDimensions[oj.TableDomUtils.CSS_PROP._WIDTH]); } if (this._tableHeightConstrained) { tableDivScroller.css(oj.TableDomUtils.CSS_PROP._HEIGHT, this._tableDimensions[oj.TableDomUtils.CSS_PROP._HEIGHT] - tableHeaderHeight - tableFooterHeight); } tableBody.css(oj.TableDomUtils.CSS_PROP._FLOAT, oj.TableDomUtils.CSS_VAL._LEFT); tableContainer.css(oj.TableDomUtils.CSS_PROP._OVERFLOW, oj.TableDomUtils.CSS_VAL._HIDDEN); } if (tableFooter != null) { if (!this.isDivScroller()) { tableFooter.css(oj.TableDomUtils.CSS_PROP._TOP, tableBodyHeight + oj.TableDomUtils.CSS_VAL._PX); } } } this._setHeaderColumnLastWidth(); this._setHeaderColumnOverflowWidths(); this._removeTableBodyRowBottomBorder(tableContainerScrollableState[0] < 0); this.refreshTableStatusPosition(); if (scrollTop != null && !resetScrollTop) { var maxScrollTop = this.getScroller()[0].scrollHeight - this.getScroller()[0].clientHeight; scrollTop = scrollTop > maxScrollTop ? maxScrollTop : scrollTop; if (this.component._isLoadMoreOnScroll() && maxScrollTop == scrollTop) { // Do not set to maxScrollTop or we will cause another fetch scrollTop--; } this.getScroller()[0].scrollTop = scrollTop; this.getScroller().scroll(); } else if (resetScrollTop) { this.getScroller()[0].scrollTop = 0; this.getScroller().scroll(); } if (scrollLeft != null && !resetScrollLeft) { this.setScrollLeft(this.getScroller()[0], scrollLeft); this.getScroller().scroll(); } else if (resetScrollLeft) { this.setScrollLeft(this.getScroller()[0], 0); this.getScroller().scroll(); } }; /** * Refresh the table status position * @private */ oj.TableDomUtils.prototype.refreshTableStatusPosition = function() { var tableContainer = this.getTableContainer(); var tableBody = this.getTableBody(); var tableStatusMessage = this.getTableStatusMessage(); var overTableElement = tableContainer; if (tableBody.height() > 0) { overTableElement = tableBody; } // if status message is hidden then return if (!tableStatusMessage || !tableStatusMessage[0].offsetParent) return; // size the messaging background tableStatusMessage.css(oj.TableDomUtils.CSS_PROP._HEIGHT, tableBody.height() + oj.TableDomUtils.CSS_VAL._PX); tableStatusMessage.css(oj.TableDomUtils.CSS_PROP._WIDTH, tableBody.width() + oj.TableDomUtils.CSS_VAL._PX); var tableStatusMessageText = $(tableStatusMessage[0].children[0]); // refresh the status message position var isRTL = (this.component._GetReadingDirection() === "rtl"); // position status in the center var options = {'my': 'center', 'at': 'center', 'collision': 'none', 'of': overTableElement}; options = oj.PositionUtils.normalizeHorizontalAlignment(options, isRTL); (/** @type {Object} */ (tableStatusMessage)).position(options); var msgTextOptions = {'my': 'center', 'at': 'center', 'collision': 'none', 'of': tableStatusMessage}; msgTextOptions = oj.PositionUtils.normalizeHorizontalAlignment(msgTextOptions, isRTL); (/** @type {Object} */ (tableStatusMessageText)).position(msgTextOptions); }; /** * Iterate through the columns and remove the widths * @private */ oj.TableDomUtils.prototype._removeHeaderColumnAndCellColumnWidths = function() { var columns = this.component._getColumnDefs(); var i, headerColumn, columnCount = columns.length; for (i = 0; i < columnCount; i++) { headerColumn = this.getTableHeaderColumn(i); if (headerColumn != null) { headerColumn.css(oj.TableDomUtils.CSS_PROP._MIN_WIDTH, ''); } } var tableBodyRows = this.getTableBodyRows(); if (tableBodyRows != null && tableBodyRows.length > 0) { var tableBodyCell; for (i = 0; i < columnCount; i++) { tableBodyCell = this.getTableBodyCell(0, i, null); if (tableBodyCell != null) { tableBodyCell.css(oj.TableDomUtils.CSS_PROP._MIN_WIDTH, ''); } } } }; /** * Remove table cell bottom border * @param {boolean} underflow table content underflow * @private */ oj.TableDomUtils.prototype._removeTableBodyRowBottomBorder = function(underflow) { if (!this._isHorizontalGridEnabled()) { return; } var tableBodyRows = this.getTableBodyRows(); if (tableBodyRows != null && tableBodyRows.length > 0) { // first make sure that all rows have hgrid var i, tableBodyRowsCount = tableBodyRows.length; for (i = 0; i < tableBodyRowsCount; i++) { if (!$(tableBodyRows[i]).hasClass(oj.TableDomUtils.CSS_CLASSES._TABLE_HGRID_LINES_CLASS)) { $(tableBodyRows[i]).addClass(oj.TableDomUtils.CSS_CLASSES._TABLE_HGRID_LINES_CLASS); } } var lastTableBodyRow = $(tableBodyRows[tableBodyRows.length - 1]); if (!underflow) { lastTableBodyRow.removeClass(oj.TableDomUtils.CSS_CLASSES._TABLE_HGRID_LINES_CLASS); } } }; /** * Remove table dimensions styling * @private */ oj.TableDomUtils.prototype._removeTableDimensionsStyling = function() { var table = this.getTable(); var tableHeader = this.getTableHeader(); var tableHeaderRow = this.getTableHeaderRow(); var tableFooter = this.getTableFooter(); var tableFooterRow = this.getTableFooterRow(); var tableBody = this.getTableBody(); // first remove any styling so that the browser sizes the table if (tableHeader != null) { tableHeader.attr(oj.TableDomUtils.DOM_ATTR._STYLE, ''); tableHeaderRow.attr(oj.TableDomUtils.DOM_ATTR._STYLE, ''); var headerColumnTextDivs = tableHeaderRow.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_TEXT_CLASS); var i; if (headerColumnTextDivs && headerColumnTextDivs.length > 0) { var headerColumnTextDivsCount = headerColumnTextDivs.length; for (i = 0; i < headerColumnTextDivsCount; i++) { $(headerColumnTextDivs[i]).css(oj.TableDomUtils.CSS_PROP._WIDTH, ''); } } } if (tableFooter != null) { tableFooter.attr(oj.TableDomUtils.DOM_ATTR._STYLE, ''); tableFooterRow.attr(oj.TableDomUtils.DOM_ATTR._STYLE, ''); } table.css(oj.TableDomUtils.CSS_PROP._DISPLAY, ''); table.css(oj.TableDomUtils.CSS_PROP._WIDTH, ''); if (tableBody != null) { tableBody.attr(oj.TableDomUtils.DOM_ATTR._STYLE, ''); } this._removeHeaderColumnAndCellColumnWidths(); }; /** * Iterate through the columns and get and then set the widths * for the columns and first row this is so that when we re-apply the styling * the headers and footers will align with the cells * @private */ oj.TableDomUtils.prototype._setColumnWidths = function() { var columns = this.component._getColumnDefs(); var columnWidths = []; var columnPaddingWidths = []; var footerPaddingWidth = null; var defaultColumnPaddingWidth, defaultTableBodyCellPaddingWidth, headerRenderer, cellRenderer = null; var i, headerColumnCell, headerColumnCellStyle, headerColumnDiv, headerColumnTextDivHeight, headerColumnTextDiv, footerCell, columnsCount = columns.length; for (i = 0; i < columnsCount; i++) { headerColumnCell = this.getTableHeaderColumn(i); if (headerColumnCell != null) { // read in the widths first. Set the widths in a separate loop so setting // the widths of early columns does not affect the widths of the rest headerColumnCellStyle = window.getComputedStyle(headerColumnCell[0]); columnWidths[i] = parseInt(headerColumnCellStyle[oj.TableDomUtils.CSS_PROP._WIDTH], 10); headerRenderer = this.component._getColumnRenderer(i, 'header'); if (!defaultColumnPaddingWidth && headerRenderer == null) { defaultColumnPaddingWidth = parseInt(headerColumnCellStyle[oj.TableDomUtils.CSS_PROP._PADDING_RIGHT], 10) + parseInt(headerColumnCellStyle[oj.TableDomUtils.CSS_PROP._PADDING_LEFT], 10); columnPaddingWidths[i] = defaultColumnPaddingWidth; } else if (headerRenderer != null) { columnPaddingWidths[i] = parseInt(headerColumnCellStyle[oj.TableDomUtils.CSS_PROP._PADDING_RIGHT], 10) + parseInt(headerColumnCellStyle[oj.TableDomUtils.CSS_PROP._PADDING_LEFT], 10); } else { columnPaddingWidths[i] = defaultColumnPaddingWidth; } // also set the header heights headerColumnTextDivHeight = null; headerColumnTextDiv = headerColumnCell.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_TEXT_CLASS); if (headerColumnTextDiv && headerColumnTextDiv.length > 0) { headerColumnTextDivHeight = headerColumnTextDiv.get(0).clientHeight; } if (headerColumnTextDivHeight != null) { headerColumnDiv = headerColumnCell.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_CLASS); headerColumnDiv.css(oj.TableDomUtils.CSS_PROP._MIN_HEIGHT, headerColumnTextDivHeight + oj.TableDomUtils.CSS_VAL._PX); } } } var adjustedColumnWidths = []; var tableBodyRows = this.getTableBodyRows(); if (tableBodyRows != null && tableBodyRows.length > 0) { var tableBodyCell, tableBodyCellStyle, tableBodyCellPaddingWidth, adjustedColumnWidth; for (i = 0; i < columnsCount; i++) { tableBodyCell = this.getTableBodyCell(0, i, null); if (tableBodyCell != null) { cellRenderer = this.component._getColumnRenderer(i, 'cell'); if (this.component._hasRowOrCellRenderer(i)) { tableBodyCellStyle = window.getComputedStyle(tableBodyCell[0]); tableBodyCellPaddingWidth = parseInt(tableBodyCellStyle[oj.TableDomUtils.CSS_PROP._PADDING_RIGHT], 10) + parseInt(tableBodyCellStyle[oj.TableDomUtils.CSS_PROP._PADDING_LEFT], 10); } else { if (!defaultTableBodyCellPaddingWidth) { tableBodyCellStyle = window.getComputedStyle(tableBodyCell[0]); defaultTableBodyCellPaddingWidth = parseInt(tableBodyCellStyle[oj.TableDomUtils.CSS_PROP._PADDING_RIGHT], 10) + parseInt(tableBodyCellStyle[oj.TableDomUtils.CSS_PROP._PADDING_LEFT], 10); } tableBodyCellPaddingWidth = defaultTableBodyCellPaddingWidth; } adjustedColumnWidth = null; if (tableBodyCellPaddingWidth > columnPaddingWidths[i]) { adjustedColumnWidth = columnWidths[i] - tableBodyCellPaddingWidth + columnPaddingWidths[i]; } else { adjustedColumnWidth = columnWidths[i] + columnPaddingWidths[i] - tableBodyCellPaddingWidth; } adjustedColumnWidths[i] = adjustedColumnWidth; } } } for (i = 0; i < columnsCount; i++) { headerColumnCell = this.getTableHeaderColumn(i); if (headerColumnCell != null) { headerColumnCell.css(oj.TableDomUtils.CSS_PROP._MIN_WIDTH, columnWidths[i] + oj.TableDomUtils.CSS_VAL._PX); } tableBodyCell = this.getTableBodyCell(0, i, null); if (tableBodyCell != null) { tableBodyCell.css(oj.TableDomUtils.CSS_PROP._MIN_WIDTH, adjustedColumnWidths[i] + oj.TableDomUtils.CSS_VAL._PX); } footerCell = this.getTableFooterCell(i); if (footerCell != null) { footerPaddingWidth = parseInt(footerCell.css(oj.TableDomUtils.CSS_PROP._PADDING_RIGHT), 10) + parseInt(footerCell.css(oj.TableDomUtils.CSS_PROP._PADDING_LEFT), 10); // adjust the padding widths if the footer has more padding if (footerPaddingWidth > columnPaddingWidths[i]) { adjustedColumnWidth = columnWidths[i] - footerPaddingWidth + columnPaddingWidths[i]; } else { adjustedColumnWidth = columnWidths[i] + columnPaddingWidths[i] - footerPaddingWidth; } footerCell.css(oj.TableDomUtils.CSS_PROP._MIN_WIDTH, adjustedColumnWidth + oj.TableDomUtils.CSS_VAL._PX); } } }; /** * Fix up the last header column width when there is a scrollbar * on the tbody * @private */ oj.TableDomUtils.prototype._setHeaderColumnLastWidth = function() { var scrollbarWidth = this.getScrollbarWidth(); if (scrollbarWidth > 0 && !this.isDivScroller()) { var scrollbarHeight = this.getScrollbarHeight(); // only do this if we don't have a horizontal scrollbar. If we have a // horizontal scrollbar then the header is constrained by the scroller if (scrollbarHeight <= 1) { // make the last column header take up the space of the table header. // we need to do this because the vertical scrollbar takes up space // in the tbody, making the last td cells smaller. So the corresponding // th ends up being shrunk unnecessarily var columns = this.component._getColumnDefs(); var columnsCount = columns.length; var lastHeaderColumnCell = this.getTableHeaderColumn(columnsCount - 1); var totalHeaderColumnCellWidth = 0; if (lastHeaderColumnCell != null) { // get the total header column width var i, column, headerColumnCell, headerColumnCellStyle, headerColumnCellWidth; for (i = 0; i < columnsCount; i++) { column = columns[i]; headerColumnCell = this.getTableHeaderColumn(i); headerColumnCellStyle = window.getComputedStyle(headerColumnCell[0]); headerColumnCellWidth = parseInt(headerColumnCellStyle[oj.TableDomUtils.CSS_PROP._WIDTH], 10); totalHeaderColumnCellWidth = totalHeaderColumnCellWidth + headerColumnCellWidth; } var tableHeader = this.getTableHeader(); var tableHeaderStyle = window.getComputedStyle(tableHeader[0]); var tableHeaderWidth = parseInt(tableHeaderStyle[oj.TableDomUtils.CSS_PROP._WIDTH], 10); if (tableHeaderWidth > totalHeaderColumnCellWidth) { var lastHeaderColumnCellStyle = window.getComputedStyle(lastHeaderColumnCell[0]); var lastHeaderColumnCellWidth = parseInt(lastHeaderColumnCellStyle[oj.TableDomUtils.CSS_PROP._WIDTH], 10); lastHeaderColumnCell.css(oj.TableDomUtils.CSS_PROP._MIN_WIDTH, lastHeaderColumnCellWidth + scrollbarWidth + oj.TableDomUtils.CSS_VAL._PX); } } } } }; /** * Iterate through the header columns and set widths for those * which have overflow so that the text displays an ellipsis * @private */ oj.TableDomUtils.prototype._setHeaderColumnOverflowWidths = function() { var columns = this.component._getColumnDefs(); var i, column, headerColumnCell, headerColumnDiv, headerColumnTextDiv, headerColumnTextDivWidth, newHeaderColumnTextDivWidth, sortPlaceHolderDivWidth, columnsCount = columns.length; for (i = 0; i < columnsCount; i++) { column = columns[i]; headerColumnCell = this.getTableHeaderColumn(i); if (headerColumnCell != null) { // if we have overflow headerColumnDiv = headerColumnCell.children('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_CLASS); if (headerColumnDiv.length > 0) { headerColumnDiv = $(headerColumnDiv[0]); headerColumnTextDiv = headerColumnCell.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_TEXT_CLASS); if (headerColumnTextDiv && headerColumnTextDiv.length > 0) { sortPlaceHolderDivWidth = 0; if (column.sortable == oj.TableDomUtils._OPTION_ENABLED) { sortPlaceHolderDivWidth = $(headerColumnCell.find('.' + oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_SORT_PACEHOLDER_CLASS).get(0)).width(); } if (headerColumnDiv[0].clientWidth > 0 && headerColumnTextDiv.width() + sortPlaceHolderDivWidth > headerColumnDiv[0].clientWidth) { headerColumnTextDiv.css(oj.TableDomUtils.CSS_PROP._WIDTH, ''); headerColumnTextDivWidth = headerColumnTextDiv.width(); newHeaderColumnTextDivWidth = headerColumnCell.width() - sortPlaceHolderDivWidth; // we only want to constrain the width. if (headerColumnTextDivWidth > newHeaderColumnTextDivWidth + 1) { headerColumnTextDiv.css(oj.TableDomUtils.CSS_PROP._WIDTH, newHeaderColumnTextDivWidth + oj.TableDomUtils.CSS_VAL._PX); } } } } } } }; /** * @const */ oj.TableDomUtils.CSS_CLASSES = { _CHECKBOX_ACC_SELECT_COLUMN_CLASS: 'oj-table-checkbox-acc-select-column', _CHECKBOX_ACC_SELECT_ROW_CLASS: 'oj-table-checkbox-acc-select-row', _TABLE_CONTAINER_CLASS: 'oj-table-container', _TABLE_SCROLLER_CLASS: 'oj-table-scroller', _TABLE_CLASS: 'oj-table', _TABLE_COMPACT_CLASS: 'oj-table-grid-display', _TABLE_EDIT_CLASS: 'oj-table-editable', _TABLE_SCROLL_CLASS: 'oj-table-scroll', _TABLE_ELEMENT_CLASS: 'oj-table-element', _TABLE_FOOTER_CLASS: 'oj-table-footer', _TABLE_FOOTER_ROW_CLASS: 'oj-table-footer-row', _TABLE_HEADER_CLASS: 'oj-table-header', _TABLE_HEADER_ROW_CLASS: 'oj-table-header-row', _COLUMN_HEADER_CELL_CLASS: 'oj-table-column-header-cell', _COLUMN_HEADER_DROP_EMPTY_CELL_CLASS: 'oj-table-column-header-drop-empty-cell', _COLUMN_HEADER_ACC_SELECT_COLUMN_CLASS: 'oj-table-column-header-acc-select-column', _COLUMN_HEADER_ACC_SELECT_ROW_CLASS: 'oj-table-column-header-acc-select-row', _COLUMN_HEADER_ACC_SELECT_ROW_TEXT_CLASS: 'oj-table-column-header-acc-select-row-text', _COLUMN_HEADER_CLASS: 'oj-table-column-header', _COLUMN_HEADER_TEXT_CLASS: 'oj-table-column-header-text', _COLUMN_HEADER_ASC_CLASS: 'oj-table-column-header-asc', _COLUMN_HEADER_DSC_CLASS: 'oj-table-column-header-dsc', _COLUMN_HEADER_SORT_PACEHOLDER_CLASS: 'oj-table-column-header-sort-placeholder', _COLUMN_HEADER_ACC_ASC_LINK_CLASS: 'oj-table-column-header-acc-asc-link', _COLUMN_HEADER_ACC_DSC_LINK_CLASS: 'oj-table-column-header-acc-dsc-link', _COLUMN_HEADER_ASC_LINK_CLASS: 'oj-table-column-header-asc-link', _COLUMN_HEADER_DSC_LINK_CLASS: 'oj-table-column-header-dsc-link', _COLUMN_HEADER_ASC_ICON_CLASS: 'oj-table-column-header-asc-icon', _COLUMN_HEADER_DSC_ICON_CLASS: 'oj-table-column-header-dsc-icon', _COLUMN_HEADER_DRAG_INDICATOR_BEFORE_CLASS: 'oj-table-column-header-drag-indicator-before', _COLUMN_HEADER_DRAG_INDICATOR_AFTER_CLASS: 'oj-table-column-header-drag-indicator-after', _COLUMN_HEADER_DRAG_IMAGE: 'oj-table-column-header-cell-drag-image', _TABLE_BODY_CLASS: 'oj-table-body', _TABLE_DATA_ROW_CLASS: 'oj-table-body-row', _TABLE_DATA_ROW_DRAG_INDICATOR_BEFORE_CLASS: 'oj-table-body-row-drag-indicator-before', _TABLE_DATA_ROW_DRAG_INDICATOR_AFTER_CLASS: 'oj-table-body-row-drag-indicator-after', _TABLE_DATA_ROW_TOUCH_SELECTIOM_AFFORDANCE_TOP_CLASS: 'oj-table-body-row-touch-selection-affordance-top', _TABLE_DATA_ROW_TOUCH_SELECTIOM_AFFORDANCE_BOTTOM_CLASS: 'oj-table-body-row-touch-selection-affordance-bottom', _TABLE_DATA_ROW_TOUCH_SELECTIOM_AFFORDANCE_TOP_ICON_CLASS: 'oj-table-body-row-touch-selection-affordance-top-icon', _TABLE_DATA_ROW_TOUCH_SELECTIOM_AFFORDANCE_BOTTOM_ICON_CLASS: 'oj-table-body-row-touch-selection-affordance-bottom-icon', _TABLE_DATA_ROW_TOUCH_SELECTIOM_AFFORDANCE_TOUCH_AREA_CLASS: 'oj-table-body-row-touch-selection-affordance-touch-area', _TABLE_DATA_ROW_EDIT_CLASS: 'oj-table-body-row-edit', _TABLE_DATA_CURRENT_ROW_CLASS: 'oj-table-body-current-row', _TABLE_DATA_CELL_CLASS: 'oj-table-data-cell', _TABLE_DATA_CELL_ACC_SELECT_CLASS: 'oj-table-data-cell-acc-select', _TABLE_DATA_CELL_EDIT_CLASS: 'oj-table-data-cell-edit', _TABLE_DATE_CELL_FORM_CONTROL_CLASS: 'oj-form-control-inherit', _TABLE_VGRID_LINES_CLASS: 'oj-table-vgrid-lines', _TABLE_HGRID_LINES_CLASS: 'oj-table-hgrid-lines', _TABLE_FOOTER_CELL_CLASS: 'oj-table-footer-cell', _TABLE_FOOTER_DROP_EMPTY_CELL_CLASS: 'oj-table-footer-drop-empty-cell', _TABLE_INLINE_MESSAGE_CLASS: 'oj-table-inline-message', _TABLE_STATUS_ACC_NOTIFICATION_CLASS: 'oj-table-status-acc-notification', _TABLE_STATUS_MESSAGE_CLASS: 'oj-table-status-message', _TABLE_STATUS_MESSAGE_TEXT_CLASS: 'oj-table-status-message-text', _TABLE_BODY_MESSAGE_CLASS: 'oj-table-body-message', _TABLE_BODY_MESSAGE_ROW_CLASS: 'oj-table-body-message-row', _WIDGET_ICON_CLASS: 'oj-component-icon', _HIDDEN_CONTENT_ACC_CLASS: 'oj-helper-hidden-accessible' }; /** * @const */ oj.TableDomUtils.CSS_PROP = { _DISPLAY: 'display', _VISIBILITY: 'visibility', _POSITION: 'position', _HEIGHT: 'height', _WIDTH: 'width', _TOP: 'top', _BOTTOM: 'bottom', _LEFT: 'left', _RIGHT: 'right', _PADDING_TOP: 'padding-top', _PADDING_LEFT: 'padding-left', _PADDING_RIGHT: 'padding-right', _OVERFLOW: 'overflow', _OVERFLOW_X: 'overflow-x', _OVERFLOW_Y: 'overflow-y', _MIN_WIDTH: 'min-width', _MIN_HEIGHT: 'min-height', _FLOAT: 'float', _BORDER_TOP: 'border-top', _BORDER_BOTTOM_WIDTH: 'border-bottom-width', _BORDER_LEFT_WIDTH: 'border-left-width', _MARGIN_BOTTOM: 'margin-bottom', _VERTICAL_ALIGN: 'vertical-align', _CURSOR: 'cursor', _ZINDEX: 'z-index', _BACKGROUND_COLOR: 'background-color' }; /** * @const */ oj.TableDomUtils.CSS_VAL = { _NONE: 'none', _BLOCK: 'block', _INLINE_BLOCK: 'inline-block', _RELATIVE: 'relative', _ABSOLUTE: 'absolute', _INLINE: 'inline', _AUTO: 'auto', _HIDDEN: 'hidden', _LEFT: 'left', _PX: 'px', _MIDDLE: 'middle', _MOVE: 'move', _FIXED: 'fixed', _TRANSPARENT: 'transparent' }; /** * @const */ oj.TableDomUtils.DOM_ATTR = { _STYLE: 'style', _TABINDEX: 'tabindex', _TYPE: 'type', _ID: 'id', _TITLE: 'title', _HREF: 'href', _HEADERS: 'headers', _COLSPAN: 'colspan', _ROLE: 'role', _ARIA_LABEL: 'aria-label', _ARIA_HIDDEN: 'aria-hidden' }; /** * @const */ oj.TableDomUtils.DOM_ELEMENT = { _DIV: 'div', _A: 'a', _TR: 'tr', _TD: 'td', _TH: 'th', _TABLE: 'table', _TBODY: 'tbody', _THEAD: 'thead', _TFOOT: 'tfoot', _INPUT: 'input', _UL: 'ul', _SPAN: 'span' }; /** * @const */ oj.TableDomUtils.MARKER_STYLE_CLASSES = { _WIDGET: 'oj-component', _ACTIVE: 'oj-active', _CLICKABLE_ICON: 'oj-clickable-icon-nocontext', _DISABLED: 'oj-disabled', _ENABLED: 'oj-enabled', _FOCUS: 'oj-focus', _HOVER: 'oj-hover', _SELECTED: 'oj-selected', _WARNING: 'oj-warning', _DRAGGABLE: 'oj-draggable', _DRAG: 'oj-drag' }; /** * @private * @const * @type {string} */ oj.TableDomUtils._COLUMN_HEADER_ROW_SELECT_ID = '_hdrColRowSel'; /** * @private * @const * @type {string} */ oj.TableDomUtils._OPTION_AUTO = 'auto'; /** * @private * @const * @type {string} */ oj.TableDomUtils._OPTION_ENABLED = 'enabled'; /** * @private * @const * @type {string} */ oj.TableDomUtils._OPTION_DISABLED = 'disabled'; /** * @private * @const */ oj.TableDomUtils._OPTION_SELECTION_MODES = { _SINGLE: 'single', _MULTIPLE: 'multiple' }; /** * @private * @const */ oj.TableDomUtils._OPTION_DISPLAY = { _LIST: 'list', _GRID: 'grid' }; /** * <table class="keyboard-table"> * <thead> * <tr> * <th>Target</th> * <th>Gesture</th> * <th>Action</th> * </tr> * </thead> * <tbody> * <tr> * <td rowspan="2">Cell</td> * <td><kbd>Tap</kbd></td> * <td>Focus on the row. If <code class="prettyprint">selectionMode</code> for rows is enabled, selects the row as well. * If multiple selection is enabled the selection handles will appear. Tapping a different row will deselect the previous selection.</td> * </tr> * <tr> * <td><kbd>Press & Hold</kbd></td> * <td>Display context menu</td> * </tr> * * <tr> * <td rowspan="2">Column Header</td> * <td><kbd>Tap</kbd></td> * <td>Focus on the header. If <code class="prettyprint">selectionMode</code> for columns is enabled, selects the column as well.</td> * </tr> * <tr> * <td><kbd>Press & Hold</kbd></td> * <td>Display context menu</td> * </tr> * </tbody> * </table> * * @ojfragment touchDoc - Used in touch section of classdesc, and standalone gesture doc * @memberof oj.ojTable */ /** * <table class="keyboard-table"> * <thead> * <tr> * <th>Target</th> * <th>Key</th> * <th>Action</th> * </tr> * </thead> * <tbody> * <tr> * <td rowspan="13">Cell</td> * <td><kbd>Tab</kbd></td> * <td>The first Tab into the Table moves focus to the first column header. The second Tab moves focus to the next focusable element outside of the Table. * <br>If focus is on a row and the row is actionable then Tab moves focus to the next focusable element within the row. If focus is already on the last focusable element then focus will wrap to the first focusable element in the row. * <br>If <code class="prettyprint">editMode</code> is rowEdit, please see the section 'Cell in EditableRow'. * </td> * </tr> * <tr> * <td><kbd>Shift+Tab</kbd></td> * <td>The first Shift+Tab into the Table moves focus to the first column header. The second Shift+Tab moves focus to the previous focusable element outside of the Table. * <br>If focus is on a row and the row is actionable then Shift+Tab moves focus to the previous focusable element within the row. If focus is already on the first focusable element then focus will wrap to the last focusable element in the row. * <br>If <code class="prettyprint">editMode</code> is rowEdit, please see the section 'Cell in EditableRow'. * </td> * </tr> * <tr> * <td><kbd>DownArrow</kbd></td> * <td>Move focus to the next row.</td> * </tr> * <tr> * <td><kbd>Shift+DownArrow</kbd></td> * <td>Select and move focus to the next row.</td> * </tr> * <tr> * <td><kbd>UpArrow</kbd></td> * <td>Move focus to the previous row. If at the first row then move to the column header.</td> * </tr> * <tr> * <td><kbd>Shift+UpArrow</kbd></td> * <td>Select and move focus to the previous row.</td> * </tr> * <tr> * <td><kbd>LeftArrow</kbd></td> * <td>Do nothing.</td> * </tr> * <tr> * <td><kbd>RightArrow</kbd></td> * <td>Do nothing.</td> * </tr> * <tr> * <td><kbd>Home</kbd></td> * <td>Move focus to first row.</td> * </tr> * <tr> * <td><kbd>End</kbd></td> * <td>Move focus to last row.</td> * </tr> * <tr> * <td><kbd>Space</kbd></td> * <td>Select row.</td> * </tr> * <tr> * <td><kbd>Enter</kbd></td> * <td>If the table <code class="prettyprint">editMode</code> is rowEdit then make the current row editable. * <br>If the table <code class="prettyprint">editMode</code> is none then toggle the current row to actionable mode if there exists a tabbable element in the row. Once toggled to actionable mode, focus will be moved to be first tabbable element in the row.</td> * </tr> * <tr> * <td><kbd>F2</kbd></td> * <td>If the table <code class="prettyprint">editMode</code> is none then toggle the current row to actionable mode if there exists a tabbable element in the row. Once toggled to actionable mode, focus will be moved to be first tabbable element in the row. * <br>If the table <code class="prettyprint">editMode</code> is rowEdit then toggle the current row between editable and readonly. * </td> * </tr> * <tr> * <td rowspan="15">Cell in Editable Row</td> * <td><kbd>Tab</kbd></td> * <td>Move focus to next editable cell or focusable element in the row. * <br>If focus is on the last editable cell or focusable element in the row, make the next row editable and move focus to the first editable cell or focusable element in the next row. * <br>If focus is on the last editable cell or focusable element in the last row, move focus to next focusable element on the page (outside table). * </td> * </tr> * <tr> * <td><kbd>Shift+Tab</kbd></td> * <td>Move focus to previous editable cell or focusable element in the row. * <br>If focus is on the first editable cell or focusable element in the row, make the previous row editable and move focus to the last editable cell or focusable element in the previous row. * <br>If focus is on the first editable cell or focusable element in the first row, move focus to previous focusable element on the page (outside table). * </td> * </tr> * <tr> * <td><kbd>DownArrow</kbd></td> * <td>Handled in the editable cell.</td> * </tr> * <tr> * <td><kbd>Shift+DownArrow</kbd></td> * <td>Handled in the editable cell.</td> * </tr> * <tr> * <td><kbd>UpArrow</kbd></td> * <td>Handled in the editable cell.</td> * </tr> * <tr> * <td><kbd>Shift+UpArrow</kbd></td> * <td>Handled in the editable cell.</td> * </tr> * <tr> * <td><kbd>LeftArrow</kbd></td> * <td>Handled in the editable cell.</td> * </tr> * <tr> * <td><kbd>RightArrow</kbd></td> * <td>Handled by the editable cell.</td> * </tr> * <tr> * <td><kbd>Home</kbd></td> * <td>Handled in the editable cell.</td> * </tr> * <tr> * <td><kbd>End</kbd></td> * <td>Handled in the editable cell.</td> * </tr> * <tr> * <td><kbd>Space</kbd></td> * <td>Handled in the editable cell.</td> * </tr> * <tr> * <td><kbd>Enter</kbd></td> * <td>Make the next row editable and move focus to the editable cell in current column in the next row. * <br>If last row is editable then make it readonly. * </td> * </tr> * <tr> * <td><kbd>Shift+Enter</kbd></td> * <td>Make the previous row editable and move focus to the editable cell in current column in the previous row. * <br>If first row is editable then make it readonly. * </td> * </tr> * <tr> * <td><kbd>F2</kbd></td> * <td>Toggle the current row between editable and readonly.</td> * </tr> * <tr> * <td><kbd>Esc</kbd></td> * <td>Make the current row readonly.</td> * </tr> * <tr> * <td rowspan="11">Column Header</td> * <td><kbd>Tab</kbd></td> * <td>Navigate to next focusable element on page (outside table).</td> * </tr> * <tr> * <td><kbd>Shift+Tab</kbd></td> * <td>Navigate to previous focusable element on page (outside table).</td> * </tr> * <tr> * <td><kbd>DownArrow</kbd></td> * <td>Move focus to the first row.</td> * </tr> * <tr> * <td><kbd>UpArrow</kbd></td> * <td>Do nothing.</td> * </tr> * <tr> * <td><kbd>LeftArrow</kbd></td> * <td>Move focus to previous column header.</td> * </tr> * <tr> * <td><kbd>Shift+LeftArrow</kbd></td> * <td>Select and move focus to previous column header.</td> * </tr> * <tr> * <td><kbd>RightArrow</kbd></td> * <td>Move focus to next column header.</td> * </tr> * <tr> * <td><kbd>Shift+RightArrow</kbd></td> * <td>Select and move focus to next column header.</td> * </tr> * <tr> * <td><kbd>Home</kbd></td> * <td>Move focus to first column header.</td> * </tr> * <tr> * <td><kbd>End</kbd></td> * <td>Move focus to last column header.</td> * </tr> * <tr> * <td><kbd>Space</kbd></td> * <td>Select column.</td> * </tr> * </tbody> * </table> * * @ojfragment keyboardDoc - Used in keyboard section of classdesc, and standalone gesture doc * @memberof oj.ojTable */ /** * {@ojinclude "name":"ojStylingDocIntro"} * * <table class="generic-table styling-table"> * <thead> * <tr> * <th>{@ojinclude "name":"ojStylingDocClassHeader"}</th> * <th>{@ojinclude "name":"ojStylingDocDescriptionHeader"}</th> * </tr> * </thead> * <tbody> * <tr> * <td>oj-table-panel-bottom</td> * <td><p>Used to style a panel that can attach to the bottom of the table * and match the table colors. An app developer can put a paging control * in a div with this class, for example. * * <p>The class is applied as follows: * * <ul> * <li>The class must be applied to the element which is placed immediately below the ojTable element.</li> * </ul> * </td> * </tr> * <tr> * <td>oj-table-data-cell-no-padding</td> * <td><p>Used to style a table cell so that it has no padding. An app developer would likely use * this in the case of editable tables when an editable cell content does not need the default cell padding. * * <p>The class is applied as follows: * * <ul> * <li>The class must be applied to the table cell.</li> * </ul> * </td> * </tr> * <tr> * <td>oj-table-data-cell-padding</td> * <td><p>Used to style a table cell so that it has the default padding. An app developer would likely use * this in the case of editable tables when an editable cell content needs to maintain default cell padding. * * <p>The class is applied as follows: * * <ul> * <li>The class must be applied to the table cell.</li> * </ul> * </td> * </tr> * </tbody> * </table> * * @ojfragment stylingDoc - Used in Styling section of classdesc, and standalone Styling doc * @memberof oj.ojTable */ // SubId Locators ************************************************************** /** * <p>Sub-ID for the ojTable component's cells.</p> * To lookup a cell the locator object should have the following: * <ul> * <li><b>subId</b>: 'oj-table-cell'</li> * <li><b>rowIndex</b>: the zero based absolute row index</li> * <li><b>columnIndex</b>: the zero based absolute column index</li> * </ul> * * @ojsubid oj-table-cell * @memberof oj.ojTable * * @example <caption>Get the cell at row index 1 and column index 2:</caption> * var node = $( ".selector" ).ojTable( "getNodeBySubId", {'subId': 'oj-table-cell', 'rowIndex': 1, 'columnIndex': 2} ); */ /** * <p>Sub-ID for the ojTable component's headers.</p> * * To lookup a header the locator object should have the following: * <ul> * <li><b>subId</b>: 'oj-table-header'</li> * <li><b>index</b>: the zero based absolute column index.</li> * </ul> * * @ojsubid oj-table-header * @memberof oj.ojTable * * @example <caption>Get the header at the specified location:</caption> * var node = $( ".selector" ).ojTable( "getNodeBySubId", {'subId': 'oj-table-header', 'index':0} ); */ /** * <p>Sub-ID for the ojTable component's sort ascending icon in column headers.</p> * * To lookup a sort icon the locator object should have the following: * <ul> * <li><b>subId</b>: 'oj-table-sort-ascending'</li> * <li><b>index</b>: the zero based absolute column index</li> * </ul> * * @ojsubid oj-table-sort-ascending * @memberof oj.ojTable * * @example <caption>Get the sort ascending icon from the header at the specified location:</caption> * var node = $( ".selector" ).ojTable( "getNodeBySubId", {'subId': 'oj-table-sort-ascending', 'index':0} ); */ /** * <p>Sub-ID for the ojTable component's sort descending icon in column headers.</p> * * To lookup a sort icon the locator object should have the following: * <ul> * <li><b>subId</b>: 'oj-table-sort-descending'</li> * <li><b>index</b>: the zero based absolute column index</li> * </ul> * * @ojsubid oj-table-sort-descending * @memberof oj.ojTable * * @example <caption>Get the sort descending icon from the header at the specified location:</caption> * var node = $( ".selector" ).ojTable( "getNodeBySubId", {'subId': 'oj-table-sort-descending', 'index':0} ); */ /** * <p>Sub-ID for the ojTable component's footers.</p> * * To lookup a footer the locator object should have the following: * <ul> * <li><b>subId</b>: 'oj-table-footer'</li> * <li><b>index</b>: the zero based absolute column index.</li> * </ul> * * @ojsubid oj-table-footer * @memberof oj.ojTable * * @example <caption>Get the header at the specified location:</caption> * var node = $( ".selector" ).ojTable( "getNodeBySubId", {'subId': 'oj-table-footer', 'index':0} ); */ // Node Context Objects ******************************************************** /** * <p>Context for the ojTable component's cells.</p> * * @property {number} rowIndex the zero based absolute row index * @property {number} columnIndex the zero based absolute column index * @property {string} key the row key * * @ojnodecontext oj-table-cell * @memberof oj.ojTable */ /** * <p>Context for the ojTable component's headers.</p> * * @property {number} index the zero based absolute column index * * @ojnodecontext oj-table-header * @memberof oj.ojTable */ /** * <p>Context for the ojTable component's footers.</p> * * @property {number} index the zero based absolute column index * * @ojnodecontext oj-table-footer * @memberof oj.ojTable */ /** * Copyright (c) 2015, Oracle and/or its affiliates. * All rights reserved. */ /** * @preserve Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ /*jslint browser: true,devel:true*/ /** * @ignore * @export * @class oj.TableDndContext * @classdesc Drag and Drop Utils for ojTable * @param {Object} component ojTable instance * @constructor */ oj.TableDndContext = function(component) { this.component = component; this.options = component['options']; this.Init(); }; // Subclass from oj.Object oj.Object.createSubclass(oj.TableDndContext, oj.Object, "oj.TableDndContext"); /** * Initializes the instance. * @export */ oj.TableDndContext.prototype.Init = function() { oj.TableDndContext.superclass.Init.call(this); }; /** * Add oj-drag marker class to cells in a column * @param {number} columnIdx the index of the column to mark */ oj.TableDndContext.prototype._addDragMarkerClass = function(columnIdx) { var column = this._getTableDomUtils().getTableHeaderColumn(columnIdx); column.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DRAG); this._getTableDomUtils().setTableColumnCellsClass(columnIdx, true, oj.TableDomUtils.MARKER_STYLE_CLASSES._DRAG); }; /** * Remove oj-drag marker class from cells in dragged columns */ oj.TableDndContext.prototype._removeDragMarkerClass = function() { var dragColumns = this._getTableDomUtils().getTableHeader().find('.' + oj.TableDomUtils.MARKER_STYLE_CLASSES._DRAG); if (dragColumns != null && dragColumns.length > 0) { var i; var dragColumnsCount = dragColumns.length; for (i = 0; i < dragColumnsCount; i++) { $(dragColumns[i]).removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DRAG); } } this._getTableDomUtils().setTableColumnCellsClass(null, false, oj.TableDomUtils.MARKER_STYLE_CLASSES._DRAG); }; /** * Clone the table container * @param {jQuery} tableContainer the div jQuery object * @return {jQuery} jQuery object for the cloned tbody */ oj.TableDndContext.prototype._cloneTableContainer = function(tableContainer) { var tableContainerClone; var tableBody = $(tableContainer.find(oj.TableDomUtils.DOM_ELEMENT._TBODY)[0]); var scrollLeft = tableBody.scrollLeft(); var scrollTop = tableBody.scrollTop(); tableContainerClone = tableContainer.clone(); var tableBodyClone = $(tableContainerClone.find(oj.TableDomUtils.DOM_ELEMENT._TBODY)[0]); // Use fixed positioning with a large top to put it off the screen without // affecting the scrollbar. // Set both overflow and overflow-x/y because on IE, setting overflow does not // affect overflow-x/y that have been explicitly set. tableBodyClone.css(oj.TableDomUtils.CSS_PROP._OVERFLOW, oj.TableDomUtils.CSS_VAL._HIDDEN); tableBodyClone.css(oj.TableDomUtils.CSS_PROP._OVERFLOW_X, oj.TableDomUtils.CSS_VAL._HIDDEN); tableBodyClone.css(oj.TableDomUtils.CSS_PROP._OVERFLOW_Y, oj.TableDomUtils.CSS_VAL._HIDDEN); tableBodyClone.css(oj.TableDomUtils.CSS_PROP._BACKGROUND_COLOR, oj.TableDomUtils.CSS_VAL._TRANSPARENT); tableBodyClone.css(oj.TableDomUtils.CSS_PROP._WIDTH, tableBody.width() + oj.TableDomUtils.CSS_VAL._PX); tableBodyClone.css(oj.TableDomUtils.CSS_PROP._HEIGHT, tableBody.height() + oj.TableDomUtils.CSS_VAL._PX); tableContainerClone.css(oj.TableDomUtils.CSS_PROP._POSITION, oj.TableDomUtils.CSS_VAL._FIXED); tableContainerClone.css(oj.TableDomUtils.CSS_PROP._TOP, 10000); tableBodyClone.scrollLeft(scrollLeft * 1.0); tableBodyClone.scrollTop(scrollTop * 1.0); $("body").append(tableContainerClone); //@HTMLUpdateOK return tableContainerClone; }; /** * Destroy the drag image * @private */ oj.TableDndContext.prototype._destroyDragImage = function() { if (this._dragImage) { this._dragImage.remove(); this._dragImage = null; } }; /** * Get the column index of the header target of an event * @param {Event} event jQuery event object * @return {number} the column index of the header target */ oj.TableDndContext.prototype._getEventColumnIndex = function(event) { return this._getTableDomUtils().getElementColumnIdx($(event.currentTarget)); }; /** * Get the index of the row under the pointer * @param {Event} event jQuery event object * @return {number} index of the row under the pointer */ oj.TableDndContext.prototype._getOverRowIndex = function(event) { var newRowIndex; var overRow = $(event.target).closest(oj.TableDomUtils.DOM_ELEMENT._TR); var context = this.component.getContextByNode(event.target); if (context && context['subId'] == 'oj-table-cell') { newRowIndex = context['rowIndex']; } else if (overRow && overRow.hasClass(oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_DRAG_INDICATOR_BEFORE_CLASS)) { newRowIndex = this._dropRowIndex; } else { // If we are not in a cell and not in the indicator row, we are in an empty part // of the table body, so add any new row to the end. var tableBodyRows = this._getTableDomUtils().getTableBodyRows(); newRowIndex = tableBodyRows ? tableBodyRows.length : 0; } return newRowIndex; }; /** * Get the TableDomUtils object from the ojTable component. */ oj.TableDndContext.prototype._getTableDomUtils = function() { return this.component._getTableDomUtils(); }; /** * Handle dragstart on column * @param {Event} event jQuery event object * @return {boolean|undefined} a value passed back to jQuery. Returning false will * cause jQuery to call event.preventDefault and event.stopPropagation. * Returning true or other values has no side effect. * In the case of dragstart, returning false cancel the drag operation. */ oj.TableDndContext.prototype.handleColumnDragStart = function(event) { if (this._isColumnReorderEnabled()) { var columnIdx = this._getEventColumnIndex(event); this._dragStartColumnIdx = columnIdx; this._setReorderColumnsDataTransfer(event, columnIdx); // Remove any row and column selection this.component._setSelection(null); this.component.option('selection', null, {'_context': {writeback: true, internalSet: true}}); // Remove text selection // Text selection doesn't get cleared unless we put it in a setTimeout setTimeout(function() { window.getSelection().removeAllRanges(); }, 0); this._addDragMarkerClass(columnIdx); return true; } }; /** * Handle dragend on column * @param {Event} event jQuery event object * @return {boolean|undefined} a value passed back to jQuery. Returning false will * cause jQuery to call event.preventDefault and event.stopPropagation. * Returning true or other values has no side effect. * In the case of dragend, returning false has no special implication. */ oj.TableDndContext.prototype.handleColumnDragEnd = function(event) { if (this._isColumnReorderEnabled()) { this.setTableHeaderColumnDraggable(null, false); this._dragStartColumnIdx = null; this._getTableDomUtils().removeDragOverIndicatorColumn(); this._getTableDomUtils().removeTableHeaderColumnDragImage(); this._removeDragMarkerClass(); } }; /** * Handle dragenter on column * @param {Event} event jQuery event object * @return {boolean|undefined} a value passed back to jQuery. Returning false will * cause jQuery to call event.preventDefault and event.stopPropagation. * Returning true or other values has no side effect. * In the case of dragenter, returning false indicates target can accept the data. */ oj.TableDndContext.prototype.handleColumnDragEnter = function(event) { if (this._isColumnReordering()) { return; } var columnIdx = this._getEventColumnIndex(event); return this._invokeDropCallback('columns', 'dragEnter', event, {'columnIndex': columnIdx}); }; /** * Handle dragover on column reordering * @param {Event} event jQuery event object */ oj.TableDndContext.prototype.handleColumnReorderDragOver = function(event) { var columnIdx = this._getEventColumnIndex(event); var dragStartColumnIdx = this._dragStartColumnIdx; if (dragStartColumnIdx != null && dragStartColumnIdx != columnIdx) { this._currentDropColumnBefore = this._isDragOverBeforeColumn(event); // Check the current before/after column position against indicator position // to see if we need to move the indicator if (!(this._currentDropColumnBefore && dragStartColumnIdx == columnIdx - 1) && !(!this._currentDropColumnBefore && dragStartColumnIdx == columnIdx + 1)) { this._getTableDomUtils().displayDragOverIndicatorColumn(columnIdx, this._currentDropColumnBefore); } event.preventDefault(); } }; /** * Handle dragover on column * @param {Event} event jQuery event object * @return {boolean|undefined} a value passed back to jQuery. Returning false will * cause jQuery to call event.preventDefault and event.stopPropagation. * Returning true or other values has no side effect. * In the case of dragover, returning false indicates target can accept the data. */ oj.TableDndContext.prototype.handleColumnDragOver = function(event) { if (this._isColumnReordering()) { return this.handleColumnReorderDragOver(event); } var columnIdx = this._getEventColumnIndex(event); this._currentDropColumnBefore = this._isDragOverBeforeColumn(event); var returnValue = this._invokeDropCallback('columns', 'dragOver', event, {'columnIndex': columnIdx}); if (returnValue === false || event.isDefaultPrevented()) { this._getTableDomUtils().displayDragOverIndicatorColumn(columnIdx, this._isDragOverBeforeColumn(event)); } return returnValue; }; /** * Handle dragleave on column * @param {Event} event jQuery event object * @return {boolean|undefined} a value passed back to jQuery. Returning false will * cause jQuery to call event.preventDefault and event.stopPropagation. * Returning true or other values has no side effect. * In the case of dragleave, returning false has no special implication. */ oj.TableDndContext.prototype.handleColumnDragLeave = function(event) { if (this._isColumnReordering()) { return; } this._getTableDomUtils().removeDragOverIndicatorColumn(); var columnIdx = this._getEventColumnIndex(event); return this._invokeDndCallback('drop', 'columns', 'dragLeave', event, {'columnIndex': columnIdx}); }; /** * Handle drop on column reordering * @param {Event} event jQuery event object */ oj.TableDndContext.prototype.handleColumnReorderDrop = function(event) { var columnIdx = this._getEventColumnIndex(event); if (!this._currentDropColumnBefore) { columnIdx++; } this.component._columnsDestMap = this._getTableDomUtils().moveTableHeaderColumn(this._dragStartColumnIdx, columnIdx, event); event.preventDefault(); }; /** * Handle drop on column * @param {Event} event jQuery event object * @return {boolean|undefined} a value passed back to jQuery. Returning false will * cause jQuery to call event.preventDefault and event.stopPropagation. * Returning true or other values has no side effect. * In the case of drop, returning false indicates target can accept the data. */ oj.TableDndContext.prototype.handleColumnDrop = function(event) { if (this._isColumnReordering()) { return this.handleColumnReorderDrop(event); } this._getTableDomUtils().removeDragOverIndicatorColumn(); var columnIdx = this._getEventColumnIndex(event); if (!this._currentDropColumnBefore) { columnIdx++; } return this._invokeDropCallback('columns', 'drop', event, {'columnIndex': columnIdx}); }; /** * Handle dragstart on row * @param {Event} event jQuery event object * @return {boolean|undefined} a value passed back to jQuery. Returning false will * cause jQuery to call event.preventDefault and event.stopPropagation. * Returning true or other values has no side effect. * In the case of dragstart, returning false cancel the drag operation. */ oj.TableDndContext.prototype.handleRowDragStart = function(event) { var dragOption = this.options['dnd']['drag']; if (dragOption && dragOption['rows']) { var ui = this._setDragRowsDataTransfer(event, dragOption['rows']['dataTypes'], this.component._getSelectedRowIdxs()); if (ui) { return this._invokeDndCallback('drag', 'rows', 'dragStart', event, ui); } // Return false to cancel the dragstart event if no data return false; } }; /** * Handle drag on row * @param {Event} event jQuery event object * @return {boolean|undefined} a value passed back to jQuery. Returning false will * cause jQuery to call event.preventDefault and event.stopPropagation. * Returning true or other values has no side effect. * In the case of drag, returning false has no special implication. */ oj.TableDndContext.prototype.handleRowDrag = function(event) { return this._invokeDndCallback('drag', 'rows', 'drag', event); }; /** * Handle dragend on row * @param {Event} event jQuery event object * @return {boolean|undefined} a value passed back to jQuery. Returning false will * cause jQuery to call event.preventDefault and event.stopPropagation. * Returning true or other values has no side effect. * In the case of dragend, returning false has no special implication. */ oj.TableDndContext.prototype.handleRowDragEnd = function(event) { // Perform any cleanup this._destroyDragImage(); return this._invokeDndCallback('drag', 'rows', 'dragEnd', event); }; /** * Handle dragenter on row * @param {Event} event jQuery event object * @return {boolean|undefined} a value passed back to jQuery. Returning false will * cause jQuery to call event.preventDefault and event.stopPropagation. * Returning true or other values has no side effect. * In the case of dragenter, returning false indicates target can accept the data. */ oj.TableDndContext.prototype.handleRowDragEnter = function(event) { var newRowIndex = this._getOverRowIndex(event); var returnValue = this._invokeDropCallback('rows', 'dragEnter', event, {'rowIndex': newRowIndex}); if (returnValue === false || event.isDefaultPrevented()) { this._updateDragRowsState(event, newRowIndex); } return returnValue; }; /** * Handle dragover on row * @param {Event} event jQuery event object * @return {boolean|undefined} a value passed back to jQuery. Returning false will * cause jQuery to call event.preventDefault and event.stopPropagation. * Returning true or other values has no side effect. * In the case of dragover, returning false indicates target can accept the data. */ oj.TableDndContext.prototype.handleRowDragOver = function(event) { return this._invokeDropCallback('rows', 'dragOver', event, {'rowIndex': this._dropRowIndex}); }; /** * Handle dragleave on row * @param {Event} event jQuery event object * @return {boolean|undefined} a value passed back to jQuery. Returning false will * cause jQuery to call event.preventDefault and event.stopPropagation. * Returning true or other values has no side effect. * In the case of dragleave, returning false has no special implication. */ oj.TableDndContext.prototype.handleRowDragLeave = function(event) { var returnValue = this._invokeDndCallback('drop', 'rows', 'dragLeave', event, {'rowIndex': this._dropRowIndex}); // Remove the indicator row if we are no longer in table body since // this may be the last dnd event we get. if (!this._isDndEventInElement(event, event.currentTarget)) { this._getTableDomUtils().removeDragOverIndicatorRow(); this._dropRowIndex = null; } return returnValue; }; /** * Handle drop on row * @param {Event} event jQuery event object * @return {boolean|undefined} a value passed back to jQuery. Returning false will * cause jQuery to call event.preventDefault and event.stopPropagation. * Returning true or other values has no side effect. * In the case of drop, returning false indicates target can accept the data. */ oj.TableDndContext.prototype.handleRowDrop = function(event) { var dropRowIndex = this._dropRowIndex; this._getTableDomUtils().removeDragOverIndicatorRow(); this._dropRowIndex = null; return this._invokeDropCallback('rows', 'drop', event, {'rowIndex': dropRowIndex}); }; /** * Hide unselected rows in a tbody element * @param {jQuery} tableContainerClone the cloned div jQuery object * @param {Array.<number>} selArray array of selected row index * @return {number|null} row index of the first selected row */ oj.TableDndContext.prototype._hideUnselectedRows = function(tableContainerClone, selArray) { var tableBodyRows; var firstRow = null; tableBodyRows = tableContainerClone.find('.' + oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_ROW_CLASS); for (var i = tableBodyRows.length - 1; i >= 0; i--) { if (selArray.indexOf(i) == -1) { $(tableBodyRows[i]).css(oj.TableDomUtils.CSS_PROP._VISIBILITY, oj.TableDomUtils.CSS_VAL._HIDDEN); } else { firstRow = i; } } // hide thead and tfoot var tableHeader = $(tableContainerClone.find(oj.TableDomUtils.DOM_ELEMENT._THEAD)); if (tableHeader != null && tableHeader.length > 0) { tableHeader.css(oj.TableDomUtils.CSS_PROP._VISIBILITY, oj.TableDomUtils.CSS_VAL._HIDDEN); } var tableFooter = $(tableContainerClone.find(oj.TableDomUtils.DOM_ELEMENT._TFOOT)); if (tableFooter != null && tableFooter.length > 0) { tableFooter.css(oj.TableDomUtils.CSS_PROP._VISIBILITY, oj.TableDomUtils.CSS_VAL._HIDDEN); } return firstRow; }; /** * Invoke user callback function specified in a drag or drop option * @param {string} dndType the dnd option type ('drag' or 'drop') * @param {string} itemType the drag or drop item type such as 'rows' * @param {string} callbackType the callback type such as 'dragStart' * @param {Event} event the jQuery Event object from drag and drop event * @param {Object} [ui] additional properties to pass to callback function * @return {boolean} the return value from the callback function */ oj.TableDndContext.prototype._invokeDndCallback = function(dndType, itemType, callbackType, event, ui) { var dndOption = this.options['dnd'][dndType]; var returnValue; if (dndOption && dndOption[itemType]) { // First let the callback decide if data can be accepted var callback = dndOption[itemType][callbackType]; if (callback && typeof callback == 'function') { try { // Hoist dataTransfer object from DOM event to jQuery event event.dataTransfer = event.originalEvent.dataTransfer; // Invoke callback function returnValue = callback(event, ui); } catch (e) { oj.Logger.error('Error: ' + e); } } } return returnValue; }; /** * Invoke user callback function specified in a drop option * @param {string} itemType the drag or drop item type such as 'rows' * @param {string} callbackType the callback type such as 'dragStart' * @param {Event} event the jQuery Event object from drag and drop event * @param {Object} [ui] additional properties to pass to callback function * @return {boolean} the return value from the callback function */ oj.TableDndContext.prototype._invokeDropCallback = function(itemType, callbackType, event, ui) { var returnValue = this._invokeDndCallback('drop', itemType, callbackType, event, ui); if (returnValue === undefined) { if (this._matchDragDataType(event, itemType)) { event.preventDefault(); } } return returnValue; }; /** * Whether the column reorder is enabled * @return {boolean} true or false * @private */ oj.TableDndContext.prototype._isColumnReorderEnabled = function() { var dndOption = this.options['dnd']; if (dndOption && dndOption['reorder'] && dndOption['reorder']['columns'] == this.component._OPTION_ENABLED) { return true; } return false; }; /** * Return true if column reorder is in progress */ oj.TableDndContext.prototype._isColumnReordering = function() { return (this._dragStartColumnIdx != null); }; /** * Return true if the mouse/touch point of a dnd event is in an element * @param {Event} event jQuery event object * @param {EventTarget} element DOM element */ oj.TableDndContext.prototype._isDndEventInElement = function(event, element) { var rect = element.getBoundingClientRect(); var domEvent = event.originalEvent; // clientX and clientY are only available on the original DOM event. // IE returns client rect in non-integer values. Trim it down to make sure // the pointer is really still in the element. return (domEvent.clientX >= Math.ceil(rect.left) && domEvent.clientX < Math.floor(rect.right) && domEvent.clientY >= Math.ceil(rect.top) && domEvent.clientY < Math.floor(rect.bottom)); }; /** * @param {Object} event event * @return {boolean} <code>true</code> if the event is considered before the * column, <code>false</code> otherwise. * @private */ oj.TableDndContext.prototype._isDragOverBeforeColumn = function(event) { var columnRect = event.currentTarget.getBoundingClientRect(); if (event.originalEvent.clientX != null) { var cursorPosX = columnRect.right - event.originalEvent.clientX; // First figure out whether the pointer is on the left half or right half var onRightHalf = (cursorPosX < (columnRect.right - columnRect.left) / 2); // Whether we are before/after the column depends on the reading direction return (oj.DomUtils.getReadingDirection() === "rtl") ? onRightHalf : !onRightHalf; } return false; }; /** * Return true if the data types from dnd event match one of the values in an array * @param {Event} event jQuery event object for a drag and drop event * @param {string} itemType The drop item type such as "rows" or "columns". * @return {boolean} true if one of the types in dragDataTypes and allowedTypes matches */ oj.TableDndContext.prototype._matchDragDataType = function(event, itemType) { var dragDataTypes = event.originalEvent.dataTransfer.types; var dndOption = this.options['dnd']['drop']; if (dndOption && dndOption[itemType] && dndOption[itemType]['dataTypes']) { var allowedTypes = dndOption[itemType]['dataTypes']; var allowedTypeArray = (typeof allowedTypes == 'string') ? [allowedTypes] : allowedTypes; // dragDataTypes can be either an array of strings (Chrome) or a // DOMStringList (Firefox and IE). For cross-browser compatibility, use its // length and index to traverse it. for (var i = 0; i < dragDataTypes.length; i++) { if (allowedTypeArray.indexOf(dragDataTypes[i]) >= 0) return true; } } return false; }; /** * Set the draggable attribute of a header column * @param {Element} headerColumn the header column DOM element * @param {boolean} draggable true if header column is draggable; false otherwise. */ oj.TableDndContext.prototype._setHeaderColumnDraggable = function(headerColumn, draggable) { headerColumn.draggable = draggable; if (draggable) { $(headerColumn).css(oj.TableDomUtils.CSS_PROP._CURSOR, oj.TableDomUtils.CSS_VAL._MOVE); $(headerColumn).addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DRAGGABLE); } }; /** * Clear the draggable attribute of a header column * @param {Element} headerColumn the header column DOM element */ oj.TableDndContext.prototype._clearHeaderColumnDraggable = function(headerColumn) { headerColumn.draggable = ''; $(headerColumn).css(oj.TableDomUtils.CSS_PROP._CURSOR, oj.TableDomUtils.CSS_VAL._AUTO); $(headerColumn).removeClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DRAGGABLE); }; /** * Set the data of the selected rows into the dataTransfer object * @param {Event} nativeEvent DOM event object * @param {string | Array.<string>} dataTypes a data type or array of data types * @param {Array.<Object>} rowDataArray array of row data */ oj.TableDndContext.prototype._setDragRowsData = function(nativeEvent, dataTypes, rowDataArray) { var dataTransfer = nativeEvent.dataTransfer; var jsonStr = JSON.stringify(rowDataArray); if (typeof dataTypes == 'string') { dataTransfer.setData(dataTypes, jsonStr); } else if (dataTypes) { for (var i = 0; i < dataTypes.length; i++) { dataTransfer.setData(dataTypes[i], jsonStr); } } }; /** * Set the data and drag image of the selected row into the dataTransfer object * @param {Event} event jQuery event object * @param {string | Array.<string>} dataTypes a data type or array of data types * @param {Array.<number>} selArray array of selected row index */ oj.TableDndContext.prototype._setDragRowsDataTransfer = function(event, dataTypes, selArray) { var rowDataArray = []; // Add data for selected rows to an array for (var i = 0; i < selArray.length; i++) { var row = this.component.getDataForVisibleRow(selArray[i]); if (row) { rowDataArray.push(row); } } // Use the row data array as drag data and create drag image if (rowDataArray.length) { this._setDragRowsData(event.originalEvent, dataTypes, rowDataArray); this._dragImage = this._setDragRowsImage(event.originalEvent, $(event.currentTarget).closest(oj.TableDomUtils.DOM_ELEMENT._TABLE).parent(), selArray); return {'rows': rowDataArray}; } return null; }; /** * Set a drag image of the selected rows into the dataTransfer object * @param {Event} nativeEvent DOM event object * @param {jQuery} tableContainer the div jQuery object * @param {Array.<number>} selArray array of selected row index */ oj.TableDndContext.prototype._setDragRowsImage = function(nativeEvent, tableContainer, selArray) { var tableContainerClone = this._cloneTableContainer(tableContainer); this._hideUnselectedRows(tableContainerClone, selArray); var rect = tableContainer[0].getBoundingClientRect(); var tableBody = $(tableContainer.find(oj.TableDomUtils.DOM_ELEMENT._TBODY)[0]); var scrollLeft = tableBody.scrollLeft(); var scrollTop = tableBody.scrollTop(); var offsetX = nativeEvent.clientX - rect.left + scrollLeft; var offsetY = nativeEvent.clientY - rect.top + scrollTop; nativeEvent.dataTransfer.setDragImage(tableContainerClone[0], offsetX, offsetY); return tableContainerClone; }; /** * Set the data and drag image for column reorder into the dataTransfer object * @param {Event} event jQuery event object * @param {number} columnIdx the index of the column being dragged */ oj.TableDndContext.prototype._setReorderColumnsDataTransfer = function(event, columnIdx) { var dataTransfer = event.originalEvent.dataTransfer; var tableIdHashCode = this._getTableDomUtils().hashCode(this._getTableDomUtils().getTableUID()); dataTransfer.setData('Text', this.component._DND_REORDER_TABLE_ID_DATA_KEY + ':' + tableIdHashCode + ':' + columnIdx); var dragImage = this._getTableDomUtils().createTableHeaderColumnDragImage(columnIdx); try { dataTransfer.setDragImage(dragImage[0], 0, 0); } catch(e) { // MS Edge doesn't allow calling setDragImage() } }; /** * Set the column draggable * @param {number|null} columnIdx column index * @param {boolean} draggable true or false */ oj.TableDndContext.prototype.setTableHeaderColumnDraggable = function(columnIdx, draggable) { // set draggable only if DnD is enabled if (!this._isColumnReorderEnabled()) { return; } var headerColumns = this._getTableDomUtils().getTableHeaderColumns(); if (headerColumns != null && headerColumns.length > 0) { var i; for (i = 0; i < headerColumns.length; i++) { var headerColumn = headerColumns[i]; if (columnIdx != null && i == columnIdx) { this._setHeaderColumnDraggable(headerColumn, draggable); } else { this._clearHeaderColumnDraggable(headerColumn); } } } }; /** * Update the state of dragging rows * @param {Event} event jQuery event object * @param {number} newRowIndex index of the row that can receive the drop */ oj.TableDndContext.prototype._updateDragRowsState = function(event, newRowIndex) { if (this._dropRowIndex != newRowIndex) { var overRow = $(event.target).closest(oj.TableDomUtils.DOM_ELEMENT._TR); this._dropRowIndex = newRowIndex; this._getTableDomUtils().displayDragOverIndicatorRow(this._dropRowIndex, true, overRow); } }; /** * @preserve Copyright (c) 2014, Oracle and/or its affiliates. * All rights reserved. */ /** * @preserve Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ /*jslint browser: true,devel:true*/ /** * @ignore */ oj.TableRendererUtils = {}; /** * Column Header Renderer * @param {Object} component component instance * @param {Object} context renderer context * @param {Object|null} options renderer options * @param {function(Object)|null} delegateRenderer delegate renderer */ oj.TableRendererUtils.columnHeaderDefaultRenderer = function(component, context, options, delegateRenderer) { var parentElement = $(context['headerContext']['parentElement']); var headerColumnDiv = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._DIV)); headerColumnDiv.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_CLASS); parentElement.empty(); parentElement.append(headerColumnDiv); //@HTMLUpdateOK // call the delegateRenderer var headerContentDiv = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._DIV)); headerContentDiv.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_TEXT_CLASS); headerColumnDiv.prepend(headerContentDiv); //@HTMLUpdateOK if (delegateRenderer != null) { delegateRenderer(headerContentDiv); } else { this.columnHeaderDefaultTextRenderer(component, headerContentDiv, context); } }; /** * Column Header with Sort Icons Renderer * @param {Object} component component instance * @param {Object} context renderer context * @param {Object|null} options renderer options * @param {function(Object)|null} delegateRenderer delegate renderer */ oj.TableRendererUtils.columnHeaderSortableIconRenderer = function(component, context, options, delegateRenderer) { var columnIdx = context['columnIndex']; var column = component._getColumnDefs()[columnIdx]; var parentElement = $(context['headerContext']['parentElement']); var headerColumnDiv = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._DIV)); headerColumnDiv.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_CLASS); parentElement.empty(); parentElement.append(headerColumnDiv); //@HTMLUpdateOK if (component._GetReadingDirection() === "rtl") { headerColumnDiv.css(oj.TableDomUtils.CSS_PROP._PADDING_LEFT, '0px'); } else { headerColumnDiv.css(oj.TableDomUtils.CSS_PROP._PADDING_RIGHT, '0px'); } var headerColumnAscDiv = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._DIV)); headerColumnAscDiv.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ASC_CLASS); headerColumnDiv.append(headerColumnAscDiv); //@HTMLUpdateOK var headerColumnAscLink = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._A)); headerColumnAscLink.attr(oj.TableDomUtils.DOM_ATTR._ARIA_HIDDEN, 'true'); headerColumnAscLink.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ASC_LINK_CLASS); headerColumnAscLink.addClass(oj.TableDomUtils.CSS_CLASSES._WIDGET_ICON_CLASS); headerColumnAscLink.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ASC_ICON_CLASS); headerColumnAscLink.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DISABLED); headerColumnAscLink.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._CLICKABLE_ICON); component._AddHoverable(headerColumnAscLink); headerColumnAscDiv.append(headerColumnAscLink); //@HTMLUpdateOK var headerColumnAscWidth = headerColumnAscDiv.width(); var headerColumnAscHeight = headerColumnAscDiv.height(); // separate link for acc var headerColumnAccAscLink = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._A)); headerColumnAccAscLink.attr(oj.TableDomUtils.DOM_ATTR._TABINDEX, '0'); headerColumnAccAscLink.attr(oj.TableDomUtils.DOM_ATTR._HREF, '#'); headerColumnAccAscLink.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ACC_ASC_LINK_CLASS); headerColumnAccAscLink.addClass(oj.TableDomUtils.CSS_CLASSES._HIDDEN_CONTENT_ACC_CLASS); headerColumnAccAscLink.attr(oj.TableDomUtils.DOM_ATTR._ARIA_LABEL, component.getTranslatedString('labelSortAsc') + ' ' + column.headerText); headerColumnAscDiv.append(headerColumnAccAscLink); //@HTMLUpdateOK var headerColumnSortPlaceholderDiv = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._DIV)); headerColumnSortPlaceholderDiv.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_SORT_PACEHOLDER_CLASS); headerColumnSortPlaceholderDiv.css(oj.TableDomUtils.CSS_PROP._DISPLAY, oj.TableDomUtils.CSS_VAL._INLINE_BLOCK); headerColumnSortPlaceholderDiv.css(oj.TableDomUtils.CSS_PROP._VERTICAL_ALIGN, oj.TableDomUtils.CSS_VAL._MIDDLE); headerColumnSortPlaceholderDiv.css(oj.TableDomUtils.CSS_PROP._WIDTH, headerColumnAscWidth + oj.TableDomUtils.CSS_VAL._PX); headerColumnSortPlaceholderDiv.css(oj.TableDomUtils.CSS_PROP._HEIGHT, headerColumnAscHeight + oj.TableDomUtils.CSS_VAL._PX); headerColumnDiv.append(headerColumnSortPlaceholderDiv); //@HTMLUpdateOK //sort descending link var headerColumnDscDiv = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._DIV)); headerColumnDscDiv.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DSC_CLASS); // descending sort is initially not visible headerColumnDscDiv.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DISABLED); headerColumnDiv.append(headerColumnDscDiv); //@HTMLUpdateOK var headerColumnDscLink = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._A)); headerColumnDscLink.attr(oj.TableDomUtils.DOM_ATTR._ARIA_HIDDEN, 'true'); headerColumnDscLink.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DSC_LINK_CLASS); headerColumnDscLink.addClass(oj.TableDomUtils.CSS_CLASSES._WIDGET_ICON_CLASS); headerColumnDscLink.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_DSC_ICON_CLASS); headerColumnDscLink.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._DISABLED); headerColumnDscLink.addClass(oj.TableDomUtils.MARKER_STYLE_CLASSES._CLICKABLE_ICON); component._AddHoverable(headerColumnDscLink); headerColumnDscDiv.append(headerColumnDscLink); //@HTMLUpdateOK // separate link for acc var headerColumnAccDscLink = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._A)); headerColumnAccDscLink.attr(oj.TableDomUtils.DOM_ATTR._TABINDEX, '0'); headerColumnAccDscLink.attr(oj.TableDomUtils.DOM_ATTR._HREF, '#'); headerColumnAccDscLink.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_ACC_DSC_LINK_CLASS); headerColumnAccDscLink.addClass(oj.TableDomUtils.CSS_CLASSES._HIDDEN_CONTENT_ACC_CLASS); headerColumnAccDscLink.attr(oj.TableDomUtils.DOM_ATTR._ARIA_LABEL, component.getTranslatedString('labelSortDsc') + ' ' + column.headerText); headerColumnDscDiv.append(headerColumnAccDscLink); //@HTMLUpdateOK // call the delegateRenderer var headerContentDiv = $(document.createElement(oj.TableDomUtils.DOM_ELEMENT._DIV)); headerContentDiv.addClass(oj.TableDomUtils.CSS_CLASSES._COLUMN_HEADER_TEXT_CLASS); headerColumnDiv.prepend(headerContentDiv); //@HTMLUpdateOK if (delegateRenderer != null) { delegateRenderer(headerContentDiv); } else { this.columnHeaderDefaultTextRenderer(component, headerContentDiv, context); } }; /** * Default column header context text renderer * @param {Object} component component instance * @param {Object} headerContentDiv header content div * @param {Object} context context object */ oj.TableRendererUtils.columnHeaderDefaultTextRenderer = function(component, headerContentDiv, context) { var columnIdx = context['columnIndex']; var column = component._getColumnDefs()[columnIdx]; headerContentDiv.text(column.headerText); }; /** * Default table body row renderer * @param {Object} component component instance * @param {number} rowIdx row index * @param {Object} row row * @param {Object} context context object */ oj.TableRendererUtils.tableBodyRowDefaultRenderer = function(component, rowIdx, row, context) { var tableBodyRow = $(context['rowContext']['parentElement']); var rowHashCode = component._getTableDomUtils().hashCode(row['key']); var columns = component._getColumnDefs(); component._getTableDomUtils().setTableBodyRowAttributes(row, tableBodyRow); var j, columnsCount = columns.length; for (j = 0; j < columnsCount; j++) { // set the cells in the inserted row with values from the row this.tableBodyCellDefaultRenderer(component, rowIdx, j, row, rowHashCode, context); } }; /** * Default table body cell renderer * @param {Object} component component instance * @param {number} rowIdx row index * @param {number} columnIdx column index * @param {Object} row row * @param {number} rowHashCode row hash code * @param {Object} context context object */ oj.TableRendererUtils.tableBodyCellDefaultRenderer = function(component, rowIdx, columnIdx, row, rowHashCode, context) { var tableBodyRow = $(context['rowContext']['parentElement']); var columns = component._getColumnDefs(); var column = columns[columnIdx]; var tableBodyCell = component._getTableDomUtils().createTableBodyCell(rowIdx, columnIdx); component._getTableDomUtils().styleTableBodyCell(columnIdx, tableBodyCell, true); component._getTableDomUtils().insertTableBodyCell(rowIdx, row['key'], rowHashCode, columnIdx, tableBodyCell, tableBodyRow, true); var data = null; if (column.field != null) { data = row['data'][column.field]; } var cellRenderer = component._getColumnRenderer(columnIdx, 'cell'); if (cellRenderer) { var cellContext = this.getRendererContextObject(component, tableBodyCell[0], {'row': row}); // Copy additional properties to top-level context to work with custom element var rendererContext = {'cellContext': cellContext, 'columnIndex': columnIdx, 'data': data, 'row': $.extend({}, row['data']), 'componentElement': cellContext['componentElement'], 'parentElement': cellContext['parentElement']}; var cellColumnContent = cellRenderer(rendererContext); if (cellColumnContent != null) { // if the renderer returned a value then we set it as the content // for the cell tableBodyCell.append(cellColumnContent); //@HTMLUpdateOK } else { // if the renderer didn't return a value then the existing // cell was manipulated. So get it and set the required // attributes just in case it was replaced or the attributes // got removed tableBodyCell = $(tableBodyRow.children(':not(' + '.' + oj.TableDomUtils.CSS_CLASSES._TABLE_DATA_CELL_ACC_SELECT_CLASS + ')')[columnIdx]); component._getTableDomUtils().setTableBodyCellAttributes(rowIdx, row['key'], rowHashCode, columnIdx, tableBodyCell); component._getTableDomUtils().styleTableBodyCell(columnIdx, tableBodyCell, false); } } else { tableBodyCell.text(data); } }; /** * Get the context object to pass into the renderer * @param {Object} component component * @param {Object} parentElement element * @param {Object} options options */ oj.TableRendererUtils.getRendererContextObject = function(component, parentElement, options) { var context = {}; context['component'] = oj.Components.getWidgetConstructor(component.element, 'ojTable'); var dataSource = component._getData(); // unwrap the datasource if we have a PagingTableDataSource if (dataSource instanceof oj.PagingTableDataSource) { dataSource = dataSource.getWrappedDataSource(); } context['datasource'] = dataSource; context['parentElement'] = parentElement; if (options['row'] != null) { var row = options['row']; var rowKey = row['key']; context['status'] = this.getRendererStatusObject(component, row); if (component._hasEditableRow()) { // Check using the editable row key var editableRowKey = component._getEditableRowKey(); // only set to edit mode for the editable row if (oj.Object.compareValues(rowKey, editableRowKey)) { context['mode'] = 'edit'; } else { context['mode'] = 'navigation'; } } else { context['mode'] = 'navigation'; } if (dataSource instanceof oj.FlattenedTreeTableDataSource) { var rowContext = row['metadata']; if (rowContext == null) { rowContext = dataSource._getMetadata(row['index']); } var i; for (i in rowContext) { if (rowContext.hasOwnProperty(i)) { context[i] = rowContext[i]; } } } } // Fix up context to work with custom element return component._FixRendererContext(context); }; /** * Get the status object to pass into the renderer * @param {Object} component component * @param {Object} row row instance * @return {Object} status object */ oj.TableRendererUtils.getRendererStatusObject = function(component, row) { return {'rowIndex': row['index'], 'rowKey': row['key'], 'currentRow': $.extend({}, component._getCurrentRow())}; }; (function() { var ojTableMeta = { "properties": { "accessibility": { "type": "Object", "properties": { "rowHeader": { "type": "string" } } }, "columns": { "type": "Array<Object>" }, "columnsDefault": { "type": "Object", "properties": { "className": { "type": "string" }, "field": { "type": "string" }, "footerClassName": { "type": "string" }, "footerRenderer": {}, "footerStyle": { "type": "string" }, "headerClassName": { "type": "string" }, "headerRenderer": {}, "headerStyle": { "type": "string" }, "headerText": { "type": "string" }, "renderer": {}, "sortable": { "type": "string", "enumValues": ["auto", "enabled", "disabled", "none"] }, "sortProperty": { "type": "string" }, "style": { "type": "string" } } }, "currentRow": { "type": "Object" }, "data": {}, "display": { "type": "string", "enumValues": ["list", "grid"] }, "dnd": { "type": "Object", "properties": { "drag": { "type": "Object", "properties": { "rows": { "type": "Object", "properties": { "dataTypes": {"type": "string|Array<string>"}, "dragStart": {}, "drag": {}, "dragEnd": {} } } } }, "drop": { "type": "Object", "properties": { "columns": { "type": "Object", "properties": { "dataTypes": {"type": "string|Array<string>"}, "dragEnter": {}, "dragOver": {}, "dragLeave": {}, "drop": {} } }, "rows": { "type": "Object", "properties": { "dataTypes": {"type": "string|Array<string>"}, "dragEnter": {}, "dragOver": {}, "dragLeave": {}, "drop": {} } } } }, "reorder": { "type": "Object", "properties": { "columns": { "type": "string", "enumValues": ["disabled", "enabled"] } } } } }, "editMode": { "type": "string", "enumValues": ["none", "rowEdit"] }, "emptyText": { "type": "string" }, "horizontalGridVisible": { "type": "string", "enumValues": ["auto", "enabled", "disabled"] }, "rowRenderer": {}, "scrollPolicy": { "type": "string", "enumValues": ["auto", "loadMoreOnScroll"] }, "scrollPolicyOptions": { "type": "Object", "properties": { "fetchSize": { "type": "number" }, "maxCount": { "type": "number" } } }, "selection": { "type": "Array<Object>" }, "selectionMode": { "type": "Object", "properties": { "row": { "type": "string", "enumValues": ["single", "multiple"] }, "column": { "type": "string", "enumValues": ["single", "multiple"] } } }, "verticalGridVisible": { "type": "string", "enumValues": ["auto", "enabled", "disabled"] } }, "methods": { "getContextByNode": {}, "getDataForVisibleRow": {}, "refreshRow": {}, }, "events": { "beforeCurrentRow": {}, "beforeRowEdit": {}, "beforeRowEditEnd": {}, "sort": {} }, "extension": { _INNER_ELEM: 'table', _WIDGET_NAME: "ojTable" } }; oj.CustomElementBridge.registerMetadata('oj-table', 'baseComponent', ojTableMeta); oj.CustomElementBridge.register('oj-table', {'metadata': oj.CustomElementBridge.getMetadata('oj-table')}); })(); });
var searchData= [ ['releasedesigneroutlets',['ReleaseDesignerOutlets',['../class_mac_inspector_1_1_app_delegate.html#a9764b869694f9505adbafcc6408bc926',1,'MacInspector.AppDelegate.ReleaseDesignerOutlets()'],['../class_mac_inspector_1_1_box_prefs_view_controller.html#a4b3620073d3184e36657805419ea98f6',1,'MacInspector.BoxPrefsViewController.ReleaseDesignerOutlets()'],['../class_mac_inspector_1_1_content_view_controller.html#a2ac0d69979da30cfcdde54f84d31b458',1,'MacInspector.ContentViewController.ReleaseDesignerOutlets()'],['../class_mac_inspector_1_1_doc_prefs_view_controller.html#a1f28b2ed0869a260dd6d7bd966dc5c28',1,'MacInspector.DocPrefsViewController.ReleaseDesignerOutlets()'],['../class_mac_inspector_1_1_inspector_view_controller.html#a0765645722857ca6f63421db6aadba8f',1,'MacInspector.InspectorViewController.ReleaseDesignerOutlets()'],['../class_mac_inspector_1_1_main_window_controller.html#a54d283721d0159437f7d5e7fee90420d',1,'MacInspector.MainWindowController.ReleaseDesignerOutlets()']]], ['replaceinspectorpanelseque',['ReplaceInspectorPanelSeque',['../class_mac_inspector_1_1_replace_inspector_panel_seque.html#aa7854ae31c81b259704888b750fdd38b',1,'MacInspector.ReplaceInspectorPanelSeque.ReplaceInspectorPanelSeque()'],['../class_mac_inspector_1_1_replace_inspector_panel_seque.html#af86d01a803e7e7ea8a32be7e94ae9e97',1,'MacInspector.ReplaceInspectorPanelSeque.ReplaceInspectorPanelSeque(string identifier, NSObject sourceController, NSObject destinationController)'],['../class_mac_inspector_1_1_replace_inspector_panel_seque.html#ab989b0a16f6034ec0809422c272832e4',1,'MacInspector.ReplaceInspectorPanelSeque.ReplaceInspectorPanelSeque(IntPtr handle)'],['../class_mac_inspector_1_1_replace_inspector_panel_seque.html#aca4610149248b54a80803e3425b59dfb',1,'MacInspector.ReplaceInspectorPanelSeque.ReplaceInspectorPanelSeque(NSObjectFlag x)']]] ];
/** * @preserve Copyright (c) 2013 British Broadcasting Corporation * (http://www.bbc.co.uk) and TAL Contributors (1) * * (1) TAL Contributors are listed in the AUTHORS file and at * https://github.com/fmtvp/TAL/AUTHORS - please extend this file, * not this notice. * * @license 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. * * All rights reserved * Please contact us for an alternative licence */ (function() { this.IteratorTest = AsyncTestCase("Iterator"); this.IteratorTest.prototype.setUp = function() { }; this.IteratorTest.prototype.tearDown = function() { }; this.IteratorTest.prototype.testClassDefinition = function(queue) { expectAsserts(2); queuedRequire(queue, ["antie/iterator","antie/class"], function(Iterator, Class) { assertEquals('Iterator should be a function', 'function', typeof Iterator); assert('Iterator should extend from Class', new Iterator() instanceof Class); }); }; this.IteratorTest.prototype.testConstructionWithArray = function(queue) { expectAsserts(1); queuedRequire(queue, ["antie/iterator"], function(Iterator) { var itemArray = ["A", "B", "C"]; var iterator = new Iterator(itemArray); assertEquals("Iterator has expected length", itemArray.length, iterator.getLength()); }); }; this.IteratorTest.prototype.testConstructionWithArrayNoArray = function(queue) { expectAsserts(1); queuedRequire(queue, ["antie/iterator"], function(Iterator) { var iterator = new Iterator(); assertEquals("Iterator constructed without an array has zero length", 0, iterator.getLength()); }); }; this.IteratorTest.prototype.testNextReturnsExpectedItems = function(queue) { expectAsserts(3); queuedRequire(queue, ["antie/iterator"], function(Iterator) { var itemArray = ["A", "B", "C"]; var iterator = new Iterator(itemArray); assertEquals("First item is as expected", iterator.next(), itemArray[0]); assertEquals("Second item is as expected", iterator.next(), itemArray[1]); assertEquals("Third item is as expected", iterator.next(), itemArray[2]); }); }; this.IteratorTest.prototype.testIsEmptyReturnsFalseWhenIteratorHasFurtherItems = function(queue) { expectAsserts(1); queuedRequire(queue, ["antie/iterator"], function(Iterator) { var itemArray = ["A"]; var iterator = new Iterator(itemArray); assertFalse("isEmpty returns false when iterator has items", iterator.isEmpty()); }); }; this.IteratorTest.prototype.testIsEmptyReturnsTrueWhenIteratorIsEmpty = function(queue) { expectAsserts(1); queuedRequire(queue, ["antie/iterator"], function(Iterator) { var itemArray = ["A"]; var iterator = new Iterator(itemArray); iterator.next(); assertFalse("isEmpty returns true when iterator has no further items", iterator.isEmpty()); }); }; this.IteratorTest.prototype.testNextReturnsUndefinedWhenEmpty = function(queue) { expectAsserts(2); queuedRequire(queue, ["antie/iterator"], function(Iterator) { var itemArray = ["A"]; var iterator = new Iterator(itemArray); assertEquals("First item is as expected", itemArray[0], iterator.next()); assertUndefined("Next returns undefined when iterator is empty", iterator.next()); }); }; this.IteratorTest.prototype.testGetPointer = function(queue) { expectAsserts(2); queuedRequire(queue, ["antie/iterator"], function(Iterator) { var itemArray = ["A"]; var iterator = new Iterator(itemArray); assertEquals("Pointer is initially at zero", 0, iterator.getPointer()); iterator.next(); assertEquals("Pointer is incremented as next is called", 1, iterator.getPointer()); }); }; this.IteratorTest.prototype.testReset = function(queue) { expectAsserts(3); queuedRequire(queue, ["antie/iterator"], function(Iterator) { var itemArray = ["A"]; var iterator = new Iterator(itemArray); assertEquals("Pointer is initially at zero", 0, iterator.getPointer()); iterator.next(); assertEquals("Pointer is incremented as next is called", 1, iterator.getPointer()); iterator.reset(); assertEquals("Pointer returns to zero after iterator is reset", 0, iterator.getPointer()); }); }; })();
const forecast = require('./forecast'); const geocode = require('./geocode'); const weatherQueryAsync = async (res, query) => { if (!query) { res.status(400).send({ error: "Please provide an address!" }); } else if (query.length < 3) { res.status(400).send({ error: "Search term too short!" }); } else { try { let geoData = await geocode.promiseFunc(query); let weatherData = await forecast.promiseFunc(geoData.lat, geoData.lon); res.status(200).send({ location: geoData.location, description: weatherData.description, currentTemp: weatherData.currentTemp, feelslike: weatherData.feelslike, uvindex: weatherData.uvindex, humidity: weatherData.humidity, wind: weatherData.wind }); } catch (error) { return res.status(500).send({ error }); } } }; exports.weatherQueryAsync = weatherQueryAsync;
/*! * VERSION: 0.2.0 * DATE: 2018-08-17 * UPDATES AND DOCS AT: http://greensock.com * * @license Copyright (c) 2008-2018, GreenSock. All rights reserved. * DrawSVGPlugin is a Club GreenSock membership benefit; You must have a valid membership to use * this code without violating the terms of use. Visit https://greensock.com/club/ to sign up or get more details. * This work is subject to the software agreement that was issued with your membership. * * @author: Jack Doyle, jack@greensock.com */ var _gsScope="undefined"!=typeof module&&module.exports&&"undefined"!=typeof global?global:this||window;(_gsScope._gsQueue||(_gsScope._gsQueue=[])).push(function(){"use strict";var e,t=_gsScope.document,p=t.defaultView?t.defaultView.getComputedStyle:function(){},l=/(?:(-|-=|\+=)?\d*\.?\d*(?:e[\-+]?\d+)?)[0-9]/gi,_=-1!==((_gsScope.navigator||{}).userAgent||"").indexOf("Edge"),g={rect:["width","height"],circle:["r","r"],ellipse:["rx","ry"],line:["x2","y2"]},C="DrawSVGPlugin",m=String.fromCharCode(103,114,101,101,110,115,111,99,107,46,99,111,109),S=String.fromCharCode(47,114,101,113,117,105,114,101,115,45,109,101,109,98,101,114,115,104,105,112,47),w=function(e){for(var t=-1!==(window?'codepen.io':"").indexOf(String.fromCharCode(103,114,101,101,110,115,111,99,107))&&-1!==e.indexOf(String.fromCharCode(108,111,99,97,108,104,111,115,116)),r=[m,String.fromCharCode(99,111,100,101,112,101,110,46,105,111),String.fromCharCode(99,111,100,101,112,101,110,46,112,108,117,109,98,105,110,103),String.fromCharCode(99,111,100,101,112,101,110,46,100,101,118),String.fromCharCode(99,115,115,45,116,114,105,99,107,115,46,99,111,109),String.fromCharCode(99,100,112,110,46,105,111),String.fromCharCode(103,97,110,110,111,110,46,116,118),String.fromCharCode(99,111,100,101,99,97,110,121,111,110,46,110,101,116),String.fromCharCode(116,104,101,109,101,102,111,114,101,115,116,46,110,101,116),String.fromCharCode(99,101,114,101,98,114,97,120,46,99,111,46,117,107),String.fromCharCode(116,121,109,112,97,110,117,115,46,110,101,116),String.fromCharCode(116,119,101,101,110,109,97,120,46,99,111,109),String.fromCharCode(116,119,101,101,110,108,105,116,101,46,99,111,109),String.fromCharCode(112,108,110,107,114,46,99,111),String.fromCharCode(104,111,116,106,97,114,46,99,111,109),String.fromCharCode(119,101,98,112,97,99,107,98,105,110,46,99,111,109),String.fromCharCode(97,114,99,104,105,118,101,46,111,114,103),String.fromCharCode(99,111,100,101,115,97,110,100,98,111,120,46,105,111),String.fromCharCode(115,116,97,99,107,98,108,105,116,122,46,99,111,109),String.fromCharCode(99,111,100,105,101,114,46,105,111),String.fromCharCode(106,115,102,105,100,100,108,101,46,110,101,116)],i=r.length;-1<--i;)if(-1!==e.indexOf(r[i]))return!0;return t&&window&&window.console&&console.log(String.fromCharCode(87,65,82,78,73,78,71,58,32,97,32,115,112,101,99,105,97,108,32,118,101,114,115,105,111,110,32,111,102,32)+C+String.fromCharCode(32,105,115,32,114,117,110,110,105,110,103,32,108,111,99,97,108,108,121,44,32,98,117,116,32,105,116,32,119,105,108,108,32,110,111,116,32,119,111,114,107,32,111,110,32,97,32,108,105,118,101,32,100,111,109,97,105,110,32,98,101,99,97,117,115,101,32,105,116,32,105,115,32,97,32,109,101,109,98,101,114,115,104,105,112,32,98,101,110,101,102,105,116,32,111,102,32,67,108,117,98,32,71,114,101,101,110,83,111,99,107,46,32,80,108,101,97,115,101,32,115,105,103,110,32,117,112,32,97,116,32,104,116,116,112,58,47,47,103,114,101,101,110,115,111,99,107,46,99,111,109,47,99,108,117,98,47,32,97,110,100,32,116,104,101,110,32,100,111,119,110,108,111,97,100,32,116,104,101,32,39,114,101,97,108,39,32,118,101,114,115,105,111,110,32,102,114,111,109,32,121,111,117,114,32,71,114,101,101,110,83,111,99,107,32,97,99,99,111,117,110,116,32,119,104,105,99,104,32,104,97,115,32,110,111,32,115,117,99,104,32,108,105,109,105,116,97,116,105,111,110,115,46,32,84,104,101,32,102,105,108,101,32,121,111,117,39,114,101,32,117,115,105,110,103,32,119,97,115,32,108,105,107,101,108,121,32,100,111,119,110,108,111,97,100,101,100,32,102,114,111,109,32,101,108,115,101,119,104,101,114,101,32,111,110,32,116,104,101,32,119,101,98,32,97,110,100,32,105,115,32,114,101,115,116,114,105,99,116,101,100,32,116,111,32,108,111,99,97,108,32,117,115,101,32,111,114,32,111,110,32,115,105,116,101,115,32,108,105,107,101,32,99,111,100,101,112,101,110,46,105,111,46)),t}(window?'codepen.io':"");function u(e,t,r,i,o,s){return r=(parseFloat(r||0)-parseFloat(e||0))*o,i=(parseFloat(i||0)-parseFloat(t||0))*s,Math.sqrt(r*r+i*i)}function c(e){return"string"!=typeof e&&e.nodeType||(e=_gsScope.TweenLite.selector(e)).length&&(e=e[0]),e}function y(e){if(!e)return 0;var t,r,i,o,s,n,a,h=(e=c(e)).tagName.toLowerCase(),f=1,d=1;"non-scaling-stroke"===e.getAttribute("vector-effect")&&(d=e.getScreenCTM(),f=Math.sqrt(d.a*d.a+d.b*d.b),d=Math.sqrt(d.d*d.d+d.c*d.c));try{r=e.getBBox()}catch(e){console.log("Error: Some browsers like Firefox won't report measurements of invisible elements (like display:none or masks inside defs).")}if(r&&(r.width||r.height)||!g[h]||(r={width:parseFloat(e.getAttribute(g[h][0])),height:parseFloat(e.getAttribute(g[h][1]))},"rect"!==h&&"line"!==h&&(r.width*=2,r.height*=2),"line"===h&&(r.x=parseFloat(e.getAttribute("x1")),r.y=parseFloat(e.getAttribute("y1")),r.width=Math.abs(r.width-r.x),r.height=Math.abs(r.height-r.y))),"path"===h)o=e.style.strokeDasharray,e.style.strokeDasharray="none",t=e.getTotalLength()||0,f!==d&&console.log("Warning: <path> length cannot be measured accurately when vector-effect is non-scaling-stroke and the element isn't proportionally scaled."),t*=(f+d)/2,e.style.strokeDasharray=o;else if("rect"===h)t=2*r.width*f+2*r.height*d;else if("line"===h)t=u(r.x,r.y,r.x+r.width,r.y+r.height,f,d);else if("polyline"===h||"polygon"===h)for(i=e.getAttribute("points").match(l)||[],"polygon"===h&&i.push(i[0],i[1]),t=0,s=2;s<i.length;s+=2)t+=u(i[s-2],i[s-1],i[s],i[s+1],f,d)||0;else"circle"!==h&&"ellipse"!==h||(n=r.width/2*f,a=r.height/2*d,t=Math.PI*(3*(n+a)-Math.sqrt((3*n+a)*(n+3*a))));return t||0}function x(e,t){if(!e)return[0,0];e=c(e),t=t||y(e)+1;var r=p(e),i=r.strokeDasharray||"",o=parseFloat(r.strokeDashoffset),s=i.indexOf(",");return s<0&&(s=i.indexOf(" ")),t<(i=s<0?t:parseFloat(i.substr(0,s))||1e-5)&&(i=t),[Math.max(0,-o),Math.max(0,i-o)]}(e=_gsScope._gsDefine.plugin({propName:"drawSVG",API:2,version:"0.2.0",global:!0,overwriteProps:["drawSVG"],init:function(e,t,r,i){if(!e.getBBox)return!1;if(!w)return window.location.href="http://"+m+S+"?plugin="+C+"&source=codepen",!1;var o,s,n,a,h,f,d,l,g,u,c=y(e)+1;return this._style=e.style,this._target=e,"function"==typeof t&&(t=t(i,e)),!0===t||"true"===t?t="0 100%":t?-1===(t+"").indexOf(" ")&&(t="0 "+t):t="0 0",o=x(e,c),h=t,f=c,d=o[0],-1===(u=h.indexOf(" "))?(l=void 0!==d?d+"":h,g=h):(l=h.substr(0,u),g=h.substr(u+1)),l=-1!==l.indexOf("%")?parseFloat(l)/100*f:parseFloat(l),s=(g=-1!==g.indexOf("%")?parseFloat(g)/100*f:parseFloat(g))<l?[g,l]:[l,g],this._length=c+10,0===o[0]&&0===s[0]?(n=Math.max(1e-5,s[1]-c),this._dash=c+n,this._offset=c-o[1]+n,this._offsetPT=this._addTween(this,"_offset",this._offset,c-s[1]+n,"drawSVG")):(this._dash=o[1]-o[0]||1e-6,this._offset=-o[0],this._dashPT=this._addTween(this,"_dash",this._dash,s[1]-s[0]||1e-5,"drawSVG"),this._offsetPT=this._addTween(this,"_offset",this._offset,-s[0],"drawSVG")),_&&(a=p(e)).strokeLinecap!==a.strokeLinejoin&&(s=parseFloat(a.strokeMiterlimit),this._addTween(e.style,"strokeMiterlimit",s,s+1e-4,"strokeMiterlimit")),this._live="non-scaling-stroke"===e.getAttribute("vector-effect")||-1!==(t+"").indexOf("live"),!0},set:function(e){if(this._firstPT){if(this._live){var t,r=y(this._target)+11;r!==this._length&&(t=r/this._length,this._length=r,this._offsetPT.s*=t,this._offsetPT.c*=t,this._dashPT?(this._dashPT.s*=t,this._dashPT.c*=t):this._dash*=t)}this._super.setRatio.call(this,e),this._style.strokeDashoffset=this._offset,this._style.strokeDasharray=1===e||0===e?this._offset<.001&&this._length-this._dash<=10?"none":this._offset===this._dash?"0px, 999999px":this._dash+"px,"+this._length+"px":this._dash+"px,"+this._length+"px"}}})).getLength=y,e.getPosition=x}),_gsScope._gsDefine&&_gsScope._gsQueue.pop()(),function(e){"use strict";var t=function(){return(_gsScope.GreenSockGlobals||_gsScope).DrawSVGPlugin};"undefined"!=typeof module&&module.exports?(require("../TweenLite.js"),module.exports=t()):"function"==typeof define&&define.amd&&define(["TweenLite"],t)}();
#!/usr/bin/env node require("./")({ standalone: true, mountNodeFS: true, }).callMain(process.argv.slice(2).map(function(arg) { return String(arg).replace(/^\//, "/fs/"); }));
// import produce from 'immer'; import signUpPageReducer from '../reducer'; // import { someAction } from '../actions'; /* eslint-disable default-case, no-param-reassign */ describe('signUpPageReducer', () => { let state; beforeEach(() => { state = { // default state params here }; }); it('returns the initial state', () => { const expectedResult = state; expect(signUpPageReducer(undefined, {})).toEqual(expectedResult); }); /** * Example state change comparison * * it('should handle the someAction action correctly', () => { * const expectedResult = produce(state, draft => { * draft.loading = true; * draft.error = false; * draft.userData.nested = false; * }); * * expect(appReducer(state, someAction())).toEqual(expectedResult); * }); */ });
'use strict'; function setCookie(name, value, expire_days) { let cookie_str = name + "=" + escape(value); if (expire_days != null) { cookie_str += ";path=/;max-age=" + expire_days * 24 * 3600; } document.cookie = cookie_str; } function getCookie(name) { if (document.cookie.length > 0) { let cookies = document.cookie.split(';'); for (let x of cookies) { let key = x.split('=')[0], value = x.split('=')[1]; if (key == name) return value; } } return ""; }
require('newrelic'); const bodyParser = require('body-parser'); const compression = require('compression'); const getConfig = require("./config"); const cookieParser = require('cookie-parser'); const cors = require('cors'); const express = require("express"); const { getApiRoutes } = require('./routes'); const helmet = require('helmet'); const Logger = require("./utils/logger"); const path = require("path"); const RateLimit = require('express-rate-limit'); const swaggerUi = require('swagger-ui-express'); const addRequestId = require('express-request-id')(); /* eslint-disable */ const pug = require("pug"); const favicon = require('serve-favicon'); /* eslint-enable */ /* ------------------------------------------------------------------ * API CONFIG * ------------------------------------------------------------------ */ const config = getConfig(process.env.NODE_ENV); const logger = new Logger({name: "code-gov-api", level: config.LOGGER_LEVEL}); const app = express(); app.set('json escape', true); if( config.USE_RATE_LIMITER) { const limiter = new RateLimit({ windowMs: parseInt(process.env.WINDOW_MS || 60000, 10), max: parseInt(process.env.MAX_IP_REQUESTS || 500, 10), delayMs:parseInt(process.env.DELAY_MS || 0, 10), headers: true }); app.use(limiter); } app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(cors()); app.use(helmet()); app.use(function(req, res, next) { res.setHeader('Server', ''); res.setHeader('Via', ''); next(); }); app.use(helmet.hsts({ maxAge: config.HSTS_MAX_AGE, preload: config.HSTS_PRELOAD, setIf: function() { return config.USE_HSTS; } })); app.use(addRequestId); app.use(compression()); app.use(function(req, res, next) { logger.info({ req: req, res: res }); next(); }); app.use('/api/docs', swaggerUi.serve, swaggerUi.setup(config.SWAGGER_DOCUMENT)); app.set('view engine', 'pug'); app.set('views', path.join(__dirname, 'views')); app.use('/static', express.static(path.join(__dirname, 'public'))); app.set('json spaces', 2); /* ------------------------------------------------------------------ * API ROUTES * ------------------------------------------------------------------ */ const router = getApiRoutes(config, new express.Router()); app.use('/api', router); /* ------------------------------------------------------------------ * ERROR HANDLING * ------------------------------------------------------------------ */ // catch 404 and forward to error handler app.use(function(req, res, next) { let err = new Error('Not Found'); err.status = 404; next(err); }); app.use(function(err, req, res, next) { logger.error({req: req, res: res, err: err}); res.status(err.status || 500) .json({ message: err.message, error: app.get('env') === 'development' ? err : {} }); }); /* ------------------------------------------------------------------ * SERVER * ------------------------------------------------------------------ */ // start the server, but only if we're not in the middle of a test if(!module.parent) { app.listen(config.PORT, () => logger.info(`Started API server at http://0.0.0.0:${config.PORT}/`)); } module.exports = app;
module.exports = { rules: [ { test: /\.(le|c)ss$/, use: [ 'style-loader', 'css-loader', 'postcss-loader', 'less-loader' ] } ] };
/* @flow */ import { warn, nextTick, emptyObject, handleError, defineReactive } from '../util/index' import { createElement } from '../vdom/create-element' import { installRenderHelpers } from './render-helpers/index' import { resolveSlots } from './render-helpers/resolve-slots' import { normalizeScopedSlots } from '../vdom/helpers/normalize-scoped-slots' import VNode, { createEmptyVNode } from '../vdom/vnode' import { isUpdatingChildComponent } from './lifecycle' export function initRender (vm: Component) { vm._vnode = null // the root of the child tree vm._staticTrees = null // v-once cached trees const options = vm.$options const parentVnode = vm.$vnode = options._parentVnode // the placeholder node in parent tree const renderContext = parentVnode && parentVnode.context vm.$slots = resolveSlots(options._renderChildren, renderContext) vm.$scopedSlots = emptyObject // bind the createElement fn to this instance // so that we get proper render context inside it. // args order: tag, data, children, normalizationType, alwaysNormalize // internal version is used by render functions compiled from templates vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false) // normalization is always applied for the public version, used in // user-written render functions. vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true) // $attrs & $listeners are exposed for easier HOC creation. // they need to be reactive so that HOCs using them are always updated const parentData = parentVnode && parentVnode.data /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, () => { !isUpdatingChildComponent && warn(`$attrs is readonly.`, vm) }, true) defineReactive(vm, '$listeners', options._parentListeners || emptyObject, () => { !isUpdatingChildComponent && warn(`$listeners is readonly.`, vm) }, true) } else { defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, null, true) defineReactive(vm, '$listeners', options._parentListeners || emptyObject, null, true) } } export let currentRenderingInstance: Component | null = null // for testing only export function setCurrentRenderingInstance (vm: Component) { currentRenderingInstance = vm } // 对Vvue实例进行渲染Mixin(混入) export function renderMixin (Vue: Class<Component>) { // install runtime convenience helpers // 将一些便利的"运行时"工具安装在Vue原型上 installRenderHelpers(Vue.prototype) Vue.prototype.$nextTick = function (fn: Function) { return nextTick(fn, this) } Vue.prototype._render = function (): VNode { const vm: Component = this const { render, _parentVnode } = vm.$options if (_parentVnode) { vm.$scopedSlots = normalizeScopedSlots( _parentVnode.data.scopedSlots, vm.$slots, vm.$scopedSlots ) } // set parent vnode. this allows render functions to have access // to the data on the placeholder node. vm.$vnode = _parentVnode // render self let vnode try { // There's no need to maintain a stack because all render fns are called // separately from one another. Nested component's render fns are called // when parent component is patched. currentRenderingInstance = vm vnode = render.call(vm._renderProxy, vm.$createElement) } catch (e) { handleError(e, vm, `render`) // return error render result, // or previous vnode to prevent render error causing blank component /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production' && vm.$options.renderError) { try { vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e) } catch (e) { handleError(e, vm, `renderError`) vnode = vm._vnode } } else { vnode = vm._vnode } } finally { currentRenderingInstance = null } // if the returned array contains only a single node, allow it if (Array.isArray(vnode) && vnode.length === 1) { vnode = vnode[0] } // return empty vnode in case the render function errored out if (!(vnode instanceof VNode)) { if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) { warn( 'Multiple root nodes returned from render function. Render function ' + 'should return a single root node.', vm ) } vnode = createEmptyVNode() } // set parent vnode.parent = _parentVnode return vnode } }
!function(){function s(i){s.msg=void 0===s.msg?0:s.msg,s.msg<i.length&&(i[s.msg].addEventListener("animationend",function(){s(i)}),i[s.msg].classList.contains("msg-visible")||(s.msg<i.length-1&&(i[s.msg].classList.contains("right-msg")&&i[s.msg+1].classList.contains("right-msg")||!i[s.msg].classList.contains("right-msg")&&!i[s.msg+1].classList.contains("right-msg")&&!i[s.msg+1].classList.contains("time"))&&i[s.msg].classList.add("no-tail"),i[s.msg].classList.add("msg-visible")),s.msg++)}window.addEventListener("load",function(){var i=document.querySelectorAll("ul.rounded-messages.reveal-messages li");i.length>0&&s(i)})}();
/* eslint-disable camelcase */ /* * Copyright (c) 2020, SmartDeviceLink Consortium, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the SmartDeviceLink Consortium Inc. nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import { LightCapabilities } from './LightCapabilities.js'; import { ModuleInfo } from './ModuleInfo.js'; import { RpcStruct } from '../RpcStruct.js'; class LightControlCapabilities extends RpcStruct { /** * Initalizes an instance of LightControlCapabilities. * @class * @param {object} parameters - An object map of parameters. */ constructor (parameters) { super(parameters); } /** * Set the ModuleName * @param {String} name - The short friendly name of the light control module. It should not be used to identify a - The desired ModuleName. * module by mobile application. * @returns {LightControlCapabilities} - The class instance for method chaining. */ setModuleName (name) { this.setParameter(LightControlCapabilities.KEY_MODULE_NAME, name); return this; } /** * Get the ModuleName * @returns {String} - the KEY_MODULE_NAME value */ getModuleName () { return this.getParameter(LightControlCapabilities.KEY_MODULE_NAME); } /** * Set the ModuleInfo * @param {ModuleInfo} info - Information about a RC module, including its id. - The desired ModuleInfo. * @returns {LightControlCapabilities} - The class instance for method chaining. */ setModuleInfo (info) { this._validateType(ModuleInfo, info); this.setParameter(LightControlCapabilities.KEY_MODULE_INFO, info); return this; } /** * Get the ModuleInfo * @returns {ModuleInfo} - the KEY_MODULE_INFO value */ getModuleInfo () { return this.getObject(ModuleInfo, LightControlCapabilities.KEY_MODULE_INFO); } /** * Set the SupportedLights * @param {LightCapabilities[]} lights - An array of available LightCapabilities that are controllable. - The desired SupportedLights. * @returns {LightControlCapabilities} - The class instance for method chaining. */ setSupportedLights (lights) { this._validateType(LightCapabilities, lights, true); this.setParameter(LightControlCapabilities.KEY_SUPPORTED_LIGHTS, lights); return this; } /** * Get the SupportedLights * @returns {LightCapabilities[]} - the KEY_SUPPORTED_LIGHTS value */ getSupportedLights () { return this.getObject(LightCapabilities, LightControlCapabilities.KEY_SUPPORTED_LIGHTS); } } LightControlCapabilities.KEY_MODULE_NAME = 'moduleName'; LightControlCapabilities.KEY_MODULE_INFO = 'moduleInfo'; LightControlCapabilities.KEY_SUPPORTED_LIGHTS = 'supportedLights'; export { LightControlCapabilities };
import React, { Component } from 'react'; class Android extends Component { render() { return ( <div> <div className="section"> <h1>Android Savegames</h1> <p> GTA:SA for Android has a savegame folder at{' '} <code>&lt;internal-storage&gt;/Android/data/com.rockstargames.gtasa*/files</code> where <code>*</code> seems to be a i18n handle. <br /> This folder usually contains: </p> <ul> <li> <dl> <dt>CINFO.BIN</dt> <dd>Contains a lot of binary stuff as the name suggests.</dd> </dl> </li> <li> <dl> <dt>gta_sa.set</dt> <dd>Contains binary data, probably game settings.</dd> </dl> </li> <li> <dl> <dt>GTASAsf*.b</dt> <dd> Savegame files (1-10), 9 & 10 seem to be cloud synced because they are present with a valid size even when they were never used. </dd> </dl> </li> <li> <dl> <dt>gtasatelem.set</dt> <dd> Starts with{' '} <code> telemv001, contains binary data along the String <code>Usage</code>. Seems like analytics. </code> </dd> </dl> </li> </ul> <h2>Savegame Layout (and differences to the PC Version)</h2> <p> The savegame layout seems to differ to the PC version in some ways. <ul> <li> Only 31 occurrences of <code>BLOCK</code> instead of 34 </li> <li>Size of 195000 bytes</li> <li> Id: <code>0x53AD8157</code> </li> </ul> <h3>Block 00</h3> <p> Block 00 contains something that fits the version (from position 0/0 to 0/4) but the title seems to contain level ids instead of the savegame title (The ingame title being "Ryder" while the value saved in the file is <code>INTRO_2</code>). <br /> Additionally, there is also the filename of the savefile in block 00 (at position 168/10). The Android block 00 is ~116 bytes bigger than the PC version. </p> <h3>Block 01</h3> <p> Block 01 also seems to be different to the PC version. It contains some keywords like <code>BEARD</code>,{' '} <code>CORNROW</code>, etc. that are not present in the PC savegame. Additionally, the mission names and the positions are different (for example <code>INTRO2</code> in the Android save opposed to{' '} <code>INT2</code> in the PC save. The mission names also seem to not match the savegame title in Block 00. There are also multiple occurrences of passages that look like charsets: </p> {/* prettier-ignore */} <div style={{maxWidth: '100%', overflowX: 'scroll'}}> <pre><code style={{color:"#000000"}}>017068 31 00 02 00 32 00 02 00 33 00 02 00 34 00 02 00 35 00 02 00 36 00 02 00 37 00 02 00 38 00 02 00 39 00 02 00 3A 00 02 00 3B 00 1...2...3...4...5...6...7...8...9...:...;.<br/> 017110 02 00 3C 00 02 00 3D 00 02 00 3E 00 02 00 3F 00 02 00 40 00 02 00 41 00 02 00 42 00 02 00 43 00 02 00 44 00 02 00 45 00 02 00 ..&lt;...=...&gt;...?...@...A...B...C...D...E...<br/> 017152 46 00 02 00 47 00 02 00 48 00 02 00 49 00 02 00 4A 00 02 00 4B 00 02 00 4C 00 02 00 4D 00 02 00 4E 00 02 00 4F 00 02 00 50 00 F...G...H...I...J...K...L...M...N...O...P.<br/> 017194 02 00 51 00 02 00 52 00 02 00 53 00 02 00 54 00 02 00 55 00 02 00 56 00 02 00 57 00 02 00 58 00 02 00 59 00 02 00 5A 00 02 00 ..Q...R...S...T...U...V...W...X...Y...Z...<br/> 017236 5B 00 02 00 5C 00 02 00 5D 00 02 00 5E 00 02 00 5F 00 02 00 60 00 02 00 61 00 02 00 62 00 02 00 63 00 02 00 64 00 02 00 65 00 [...\...]...^..._...`...a...b...c...d...e.<br/> 017278 02 00 66 00 02 00 67 00 02 00 68 00 02 00 69 00 02 00 6A 00 02 00 6B 00 02 00 6C 00 02 00 6D 00 02 00 6E 00 02 00 6F 00 02 00 ..f...g...h...i...j...k...l...m...n...o...<br/> 017320 70 00 02 00 71 00 02 00 72 00 02 00 73 00 02 00 74 00 02 00 75 00 02 00 76 00 02 00 77 00 02 00 78 00 02 00 79 00 02 00 7A 00 p...q...r...s...t...u...v...w...x...y...z.<br/> 017362 02 00 7B 00 02 00 7C 00 02 00 7D 00 02 00 7E 00 02 ..{'{...|...}'}...~..<br/> </code></pre> </div> <span style={{ fontSize: '10px' }}> Generated by <a href="http://www.wxHexEditor.org/">wxHexEditor</a> </span> </p> <h3>Block 02</h3> <p>Block 02 seems similar to the PC version, both contain no human readable text.</p> </div> </div> ); } } export default Android;
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'colordialog', 'zh-cn', { clear: '清除', highlight: '高亮', options: '颜色选项', selected: '选择颜色', title: '选择颜色' } );
import React, { Component } from "react"; import { connect } from "react-redux"; import { withRouter } from "react-router-dom"; import { removeActiveModal, saveDraftBeforeLogout, saveUser, } from "../../redux/actions"; import Helper from "../../utils/Helper"; import "./style.scss"; const mapStateToProps = () => { return {}; }; class SessionTimeout extends Component { constructor(props) { super(props); this.state = { timer: 60, counter: 60, intervalId: null, }; } componentDidMount() { const intervalIdTemp = setInterval(() => { const temp = this.state.counter; this.setState({ counter: temp - 1 }); }, 1000); setTimeout(() => { this.logout(); }, this.state.timer * 1000); this.setState({ intervalId: intervalIdTemp }); } componentWillUnmount() { clearInterval(this.state.intervalId); } logout = () => { this.props.dispatch(saveDraftBeforeLogout(true)); Helper.storeUser({}); this.props.dispatch(saveUser({})); this.hideModal(); setTimeout(() => alert("You have been logged out for inactivity. Please log back in.") ); }; hideModal = () => { this.props.dispatch(removeActiveModal()); }; render() { return ( <div id="session-timeout-modal"> <h3 className="pb-3">Session Timeout</h3> <p>{`You are being timeout in ${this.state.counter} sec due to inactivity. Please choose to stay signed in or to log off. Otherwise, you will be logged off automatically.`}</p> <div className="actions"> <button className="btn btn-primary-outline" onClick={this.logout}> Log off </button> <button className="btn btn-primary" onClick={this.hideModal}> Stay Logged in ({this.state.counter}) </button> </div> </div> ); } } export default connect(mapStateToProps)(withRouter(SessionTimeout));
/** * 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 * * https://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. */ import React from 'react' import marked from 'marked' import highlight from 'highlight.js' class Help extends React.Component { constructor(props) { super(props) this.fallback = require('../../../USAGE.md') this.state = { usage: null, loaded: false } } componentDidMount() { // We try to fetch USAGE.md from github directly, this allows to update // the inline usage docs without having to make a release every time // on the google chrome webstore. fetch('https://raw.githubusercontent.com/svrnm/DemoMonkey/main/USAGE.md') .then(response => response.text()) .then(data => this.setState({ usage: data, loaded: true })) .catch(() => { this.setState({ loaded: true, usage: this.fallback }) }) } render() { const usage = this.state.loaded ? this.state.usage : this.fallback const html = marked(usage, { gfm: true, headerIds: true, highlight: (code, lang) => { const language = highlight.getLanguage(lang) ? lang : 'plaintext' return highlight.highlight(code, { language }).value } }) return ( <div className="content"> <div className="welcome" dangerouslySetInnerHTML={{ __html: html }}></div> </div> ) } } export default Help
!function(e,t){"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){function n(e){var t=!!e&&"length"in e&&e.length,n=pe.type(e);return"function"!==n&&!pe.isWindow(e)&&("array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e)}function r(e,t,n){if(pe.isFunction(t))return pe.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return pe.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(Ce.test(t))return pe.filter(t,e,n);t=pe.filter(t,e)}return pe.grep(e,function(e){return pe.inArray(e,t)>-1!==n})}function i(e,t){do{e=e[t]}while(e&&1!==e.nodeType);return e}function o(e){var t={};return pe.each(e.match(Le)||[],function(e,n){t[n]=!0}),t}function a(){re.addEventListener?(re.removeEventListener("DOMContentLoaded",s),e.removeEventListener("load",s)):(re.detachEvent("onreadystatechange",s),e.detachEvent("onload",s))}function s(){(re.addEventListener||"load"===e.event.type||"complete"===re.readyState)&&(a(),pe.ready())}function u(e,t,n){if(void 0===n&&1===e.nodeType){var r="data-"+t.replace(_e,"-$1").toLowerCase();if(n=e.getAttribute(r),"string"==typeof n){try{n="true"===n||"false"!==n&&("null"===n?null:+n+""===n?+n:qe.test(n)?pe.parseJSON(n):n)}catch(e){}pe.data(e,t,n)}else n=void 0}return n}function l(e){var t;for(t in e)if(("data"!==t||!pe.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function c(e,t,n,r){if(He(e)){var i,o,a=pe.expando,s=e.nodeType,u=s?pe.cache:e,l=s?e[a]:e[a]&&a;if(l&&u[l]&&(r||u[l].data)||void 0!==n||"string"!=typeof t)return l||(l=s?e[a]=ne.pop()||pe.guid++:a),u[l]||(u[l]=s?{}:{toJSON:pe.noop}),"object"!=typeof t&&"function"!=typeof t||(r?u[l]=pe.extend(u[l],t):u[l].data=pe.extend(u[l].data,t)),o=u[l],r||(o.data||(o.data={}),o=o.data),void 0!==n&&(o[pe.camelCase(t)]=n),"string"==typeof t?(i=o[t],null==i&&(i=o[pe.camelCase(t)])):i=o,i}}function d(e,t,n){if(He(e)){var r,i,o=e.nodeType,a=o?pe.cache:e,s=o?e[pe.expando]:pe.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){pe.isArray(t)?t=t.concat(pe.map(t,pe.camelCase)):t in r?t=[t]:(t=pe.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;for(;i--;)delete r[t[i]];if(n?!l(r):!pe.isEmptyObject(r))return}(n||(delete a[s].data,l(a[s])))&&(o?pe.cleanData([e],!0):de.deleteExpando||a!=a.window?delete a[s]:a[s]=void 0)}}}function f(e,t,n,r){var i,o=1,a=20,s=r?function(){return r.cur()}:function(){return pe.css(e,t,"")},u=s(),l=n&&n[3]||(pe.cssNumber[t]?"":"px"),c=(pe.cssNumber[t]||"px"!==l&&+u)&&Me.exec(pe.css(e,t));if(c&&c[3]!==l){l=l||c[3],n=n||[],c=+u||1;do{o=o||".5",c/=o,pe.style(e,t,c+l)}while(o!==(o=s()/u)&&1!==o&&--a)}return n&&(c=+c||+u||0,i=n[1]?c+(n[1]+1)*n[2]:+n[2],r&&(r.unit=l,r.start=c,r.end=i)),i}function p(e){var t=ze.split("|"),n=e.createDocumentFragment();if(n.createElement)for(;t.length;)n.createElement(t.pop());return n}function h(e,t){var n,r,i=0,o=void 0!==e.getElementsByTagName?e.getElementsByTagName(t||"*"):void 0!==e.querySelectorAll?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],n=e.childNodes||e;null!=(r=n[i]);i++)!t||pe.nodeName(r,t)?o.push(r):pe.merge(o,h(r,t));return void 0===t||t&&pe.nodeName(e,t)?pe.merge([e],o):o}function g(e,t){for(var n,r=0;null!=(n=e[r]);r++)pe._data(n,"globalEval",!t||pe._data(t[r],"globalEval"))}function m(e){Be.test(e.type)&&(e.defaultChecked=e.checked)}function v(e,t,n,r,i){for(var o,a,s,u,l,c,d,f=e.length,v=p(t),y=[],x=0;f>x;x++)if(a=e[x],a||0===a)if("object"===pe.type(a))pe.merge(y,a.nodeType?[a]:a);else if(Ue.test(a)){for(u=u||v.appendChild(t.createElement("div")),l=(We.exec(a)||["",""])[1].toLowerCase(),d=Xe[l]||Xe._default,u.innerHTML=d[1]+pe.htmlPrefilter(a)+d[2],o=d[0];o--;)u=u.lastChild;if(!de.leadingWhitespace&&$e.test(a)&&y.push(t.createTextNode($e.exec(a)[0])),!de.tbody)for(a="table"!==l||Ve.test(a)?"<table>"!==d[1]||Ve.test(a)?0:u:u.firstChild,o=a&&a.childNodes.length;o--;)pe.nodeName(c=a.childNodes[o],"tbody")&&!c.childNodes.length&&a.removeChild(c);for(pe.merge(y,u.childNodes),u.textContent="";u.firstChild;)u.removeChild(u.firstChild);u=v.lastChild}else y.push(t.createTextNode(a));for(u&&v.removeChild(u),de.appendChecked||pe.grep(h(y,"input"),m),x=0;a=y[x++];)if(r&&pe.inArray(a,r)>-1)i&&i.push(a);else if(s=pe.contains(a.ownerDocument,a),u=h(v.appendChild(a),"script"),s&&g(u),n)for(o=0;a=u[o++];)Ie.test(a.type||"")&&n.push(a);return u=null,v}function y(){return!0}function x(){return!1}function b(){try{return re.activeElement}catch(e){}}function w(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)w(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=x;else if(!i)return e;return 1===o&&(a=i,i=function(e){return pe().off(e),a.apply(this,arguments)},i.guid=a.guid||(a.guid=pe.guid++)),e.each(function(){pe.event.add(this,t,i,r,n)})}function T(e,t){return pe.nodeName(e,"table")&&pe.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function C(e){return e.type=(null!==pe.find.attr(e,"type"))+"/"+e.type,e}function E(e){var t=it.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function N(e,t){if(1===t.nodeType&&pe.hasData(e)){var n,r,i,o=pe._data(e),a=pe._data(t,o),s=o.events;if(s)for(n in delete a.handle,a.events={},s)for(r=0,i=s[n].length;i>r;r++)pe.event.add(t,n,s[n][r]);a.data&&(a.data=pe.extend({},a.data))}}function k(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!de.noCloneEvent&&t[pe.expando]){for(r in i=pe._data(t),i.events)pe.removeEvent(t,r,i.handle);t.removeAttribute(pe.expando)}"script"===n&&t.text!==e.text?(C(t).text=e.text,E(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),de.html5Clone&&e.innerHTML&&!pe.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Be.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:"input"!==n&&"textarea"!==n||(t.defaultValue=e.defaultValue)}}function S(e,t,n,r){t=oe.apply([],t);var i,o,a,s,u,l,c=0,d=e.length,f=d-1,p=t[0],g=pe.isFunction(p);if(g||d>1&&"string"==typeof p&&!de.checkClone&&rt.test(p))return e.each(function(i){var o=e.eq(i);g&&(t[0]=p.call(this,i,o.html())),S(o,t,n,r)});if(d&&(l=v(t,e[0].ownerDocument,!1,e,r),i=l.firstChild,1===l.childNodes.length&&(l=i),i||r)){for(s=pe.map(h(l,"script"),C),a=s.length;d>c;c++)o=l,c!==f&&(o=pe.clone(o,!0,!0),a&&pe.merge(s,h(o,"script"))),n.call(e[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,pe.map(s,E),c=0;a>c;c++)o=s[c],Ie.test(o.type||"")&&!pe._data(o,"globalEval")&&pe.contains(u,o)&&(o.src?pe._evalUrl&&pe._evalUrl(o.src):pe.globalEval((o.text||o.textContent||o.innerHTML||"").replace(ot,"")));l=i=null}return e}function A(e,t,n){for(var r,i=t?pe.filter(t,e):e,o=0;null!=(r=i[o]);o++)n||1!==r.nodeType||pe.cleanData(h(r)),r.parentNode&&(n&&pe.contains(r.ownerDocument,r)&&g(h(r,"script")),r.parentNode.removeChild(r));return e}function D(e,t){var n=pe(t.createElement(e)).appendTo(t.body),r=pe.css(n[0],"display");return n.detach(),r}function j(e){var t=re,n=lt[e];return n||(n=D(e,t),"none"!==n&&n||(ut=(ut||pe("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement),t=(ut[0].contentWindow||ut[0].contentDocument).document,t.write(),t.close(),n=D(e,t),ut.detach()),lt[e]=n),n}function L(e,t){return{get:function(){return e()?void delete this.get:(this.get=t).apply(this,arguments)}}}function H(e){if(e in Et)return e;for(var t=e.charAt(0).toUpperCase()+e.slice(1),n=Ct.length;n--;)if(e=Ct[n]+t,e in Et)return e}function q(e,t){for(var n,r,i,o=[],a=0,s=e.length;s>a;a++)r=e[a],r.style&&(o[a]=pe._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&Re(r)&&(o[a]=pe._data(r,"olddisplay",j(r.nodeName)))):(i=Re(r),(n&&"none"!==n||!i)&&pe._data(r,"olddisplay",i?n:pe.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}function _(e,t,n){var r=bt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function F(e,t,n,r,i){for(var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;4>o;o+=2)"margin"===n&&(a+=pe.css(e,n+Oe[o],!0,i)),r?("content"===n&&(a-=pe.css(e,"padding"+Oe[o],!0,i)),"margin"!==n&&(a-=pe.css(e,"border"+Oe[o]+"Width",!0,i))):(a+=pe.css(e,"padding"+Oe[o],!0,i),"padding"!==n&&(a+=pe.css(e,"border"+Oe[o]+"Width",!0,i)));return a}function M(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=ht(e),a=de.boxSizing&&"border-box"===pe.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=gt(e,t,o),(0>i||null==i)&&(i=e.style[t]),dt.test(i))return i;r=a&&(de.boxSizingReliable()||i===e.style[t]),i=parseFloat(i)||0}return i+F(e,t,n||(a?"border":"content"),r,o)+"px"}function O(e,t,n,r,i){return new O.prototype.init(e,t,n,r,i)}function R(){return e.setTimeout(function(){Nt=void 0}),Nt=pe.now()}function P(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Oe[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function B(e,t,n){for(var r,i=($.tweeners[t]||[]).concat($.tweeners["*"]),o=0,a=i.length;a>o;o++)if(r=i[o].call(n,t,e))return r}function W(e,t,n){var r,i,o,a,s,u,l,c,d=this,f={},p=e.style,h=e.nodeType&&Re(e),g=pe._data(e,"fxshow");for(r in n.queue||(s=pe._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,u=s.empty.fire,s.empty.fire=function(){s.unqueued||u()}),s.unqueued++,d.always(function(){d.always(function(){s.unqueued--,pe.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],l=pe.css(e,"display"),c="none"===l?pe._data(e,"olddisplay")||j(e.nodeName):l,"inline"===c&&"none"===pe.css(e,"float")&&(de.inlineBlockNeedsLayout&&"inline"!==j(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",de.shrinkWrapBlocks()||d.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]})),t)if(i=t[r],St.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(h?"hide":"show")){if("show"!==i||!g||void 0===g[r])continue;h=!0}f[r]=g&&g[r]||pe.style(e,r)}else l=void 0;if(pe.isEmptyObject(f))"inline"===("none"===l?j(e.nodeName):l)&&(p.display=l);else for(r in g?"hidden"in g&&(h=g.hidden):g=pe._data(e,"fxshow",{}),o&&(g.hidden=!h),h?pe(e).show():d.done(function(){pe(e).hide()}),d.done(function(){var t;for(t in pe._removeData(e,"fxshow"),f)pe.style(e,t,f[t])}),f)a=B(h?g[r]:0,r,d),r in g||(g[r]=a.start,h&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}function I(e,t){var n,r,i,o,a;for(n in e)if(r=pe.camelCase(n),i=t[r],o=e[n],pe.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=pe.cssHooks[r],a&&"expand"in a)for(n in o=a.expand(o),delete e[r],o)n in e||(e[n]=o[n],t[n]=i);else t[r]=i}function $(e,t,n){var r,i,o=0,a=$.prefilters.length,s=pe.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;for(var t=Nt||R(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:pe.extend({},t),opts:pe.extend(!0,{specialEasing:{},easing:pe.easing._default},n),originalProperties:t,originalOptions:n,startTime:Nt||R(),duration:n.duration,tweens:[],createTween:function(t,n){var r=pe.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?(s.notifyWith(e,[l,1,0]),s.resolveWith(e,[l,t])):s.rejectWith(e,[l,t]),this}}),c=l.props;for(I(c,l.opts.specialEasing);a>o;o++)if(r=$.prefilters[o].call(l,e,c,l.opts))return pe.isFunction(r.stop)&&(pe._queueHooks(l.elem,l.opts.queue).stop=pe.proxy(r.stop,r)),r;return pe.map(c,B,l),pe.isFunction(l.opts.start)&&l.opts.start.call(e,l),pe.fx.timer(pe.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function z(e){return pe.attr(e,"class")||""}function X(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(Le)||[];if(pe.isFunction(n))for(;r=o[i++];)"+"===r.charAt(0)?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function U(e,t,n,r){function i(s){var u;return o[s]=!0,pe.each(e[s]||[],function(e,s){var l=s(t,n,r);return"string"!=typeof l||a||o[l]?a?!(u=l):void 0:(t.dataTypes.unshift(l),i(l),!1)}),u}var o={},a=e===Kt;return i(t.dataTypes[0])||!o["*"]&&i("*")}function V(e,t){var n,r,i=pe.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((i[r]?e:n||(n={}))[r]=t[r]);return n&&pe.extend(!0,e,n),e}function Y(e,t,n){for(var r,i,o,a,s=e.contents,u=e.dataTypes;"*"===u[0];)u.shift(),void 0===i&&(i=e.mimeType||t.getResponseHeader("Content-Type"));if(i)for(a in s)if(s[a]&&s[a].test(i)){u.unshift(a);break}if(u[0]in n)o=u[0];else{for(a in n){if(!u[0]||e.converters[a+" "+u[0]]){o=a;break}r||(r=a)}o=o||r}return o?(o!==u[0]&&u.unshift(o),n[o]):void 0}function J(e,t,n,r){var i,o,a,s,u,l={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)l[a.toLowerCase()]=e.converters[a];for(o=c.shift();o;)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(a=l[u+" "+o]||l["* "+o],!a)for(i in l)if(s=i.split(" "),s[1]===o&&(a=l[u+" "+s[0]]||l["* "+s[0]])){!0===a?a=l[i]:!0!==l[i]&&(o=s[0],c.unshift(s[1]));break}if(!0!==a)if(a&&e.throws)t=a(t);else try{t=a(t)}catch(e){return{state:"parsererror",error:a?e:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}function G(e){return e.style&&e.style.display||pe.css(e,"display")}function Q(e){if(!pe.contains(e.ownerDocument||re,e))return!0;for(;e&&1===e.nodeType;){if("none"===G(e)||"hidden"===e.type)return!0;e=e.parentNode}return!1}function K(e,t,n,r){var i;if(pe.isArray(t))pe.each(t,function(t,i){n||rn.test(e)?r(e,i):K(e+"["+("object"==typeof i&&null!=i?t:"")+"]",i,n,r)});else if(n||"object"!==pe.type(t))r(e,t);else for(i in t)K(e+"["+i+"]",t[i],n,r)}function Z(){try{return new e.XMLHttpRequest}catch(e){}}function ee(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}function te(e){return pe.isWindow(e)?e:9===e.nodeType&&(e.defaultView||e.parentWindow)}var ne=[],re=e.document,ie=ne.slice,oe=ne.concat,ae=ne.push,se=ne.indexOf,ue={},le=ue.toString,ce=ue.hasOwnProperty,de={},fe="1.12.4",pe=function(e,t){return new pe.fn.init(e,t)},he=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,ge=/^-ms-/,me=/-([\da-z])/gi,ve=function(e,t){return t.toUpperCase()};pe.fn=pe.prototype={jquery:fe,constructor:pe,selector:"",length:0,toArray:function(){return ie.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:ie.call(this)},pushStack:function(e){var t=pe.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e){return pe.each(this,e)},map:function(e){return this.pushStack(pe.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(ie.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:ae,sort:ne.sort,splice:ne.splice},pe.extend=pe.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,l=!1;for("boolean"==typeof a&&(l=a,a=arguments[s]||{},s++),"object"==typeof a||pe.isFunction(a)||(a={}),s===u&&(a=this,s--);u>s;s++)if(null!=(i=arguments[s]))for(r in i)e=a[r],n=i[r],a!==n&&(l&&n&&(pe.isPlainObject(n)||(t=pe.isArray(n)))?(t?(t=!1,o=e&&pe.isArray(e)?e:[]):o=e&&pe.isPlainObject(e)?e:{},a[r]=pe.extend(l,o,n)):void 0!==n&&(a[r]=n));return a},pe.extend({expando:"jQuery"+(fe+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===pe.type(e)},isArray:Array.isArray||function(e){return"array"===pe.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){var t=e&&e.toString();return!pe.isArray(e)&&t-parseFloat(t)+1>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==pe.type(e)||e.nodeType||pe.isWindow(e))return!1;try{if(e.constructor&&!ce.call(e,"constructor")&&!ce.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(e){return!1}if(!de.ownFirst)for(t in e)return ce.call(e,t);for(t in e);return void 0===t||ce.call(e,t)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?ue[le.call(e)]||"object":typeof e},globalEval:function(t){t&&pe.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(ge,"ms-").replace(me,ve)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t){var r,i=0;if(n(e))for(r=e.length;r>i&&!1!==t.call(e[i],i,e[i]);i++);else for(i in e)if(!1===t.call(e[i],i,e[i]))break;return e},trim:function(e){return null==e?"":(e+"").replace(he,"")},makeArray:function(e,t){var r=t||[];return null!=e&&(n(Object(e))?pe.merge(r,"string"==typeof e?[e]:e):ae.call(r,e)),r},inArray:function(e,t,n){var r;if(t){if(se)return se.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;n>r;)e[i++]=t[r++];if(n!=n)for(;void 0!==t[r];)e[i++]=t[r++];return e.length=i,e},grep:function(e,t,n){for(var r,i=[],o=0,a=e.length,s=!n;a>o;o++)r=!t(e[o],o),r!==s&&i.push(e[o]);return i},map:function(e,t,r){var i,o,a=0,s=[];if(n(e))for(i=e.length;i>a;a++)o=t(e[a],a,r),null!=o&&s.push(o);else for(a in e)o=t(e[a],a,r),null!=o&&s.push(o);return oe.apply([],s)},guid:1,proxy:function(e,t){var n,r,i;return"string"==typeof t&&(i=e[t],t=e,e=i),pe.isFunction(e)?(n=ie.call(arguments,2),r=function(){return e.apply(t||this,n.concat(ie.call(arguments)))},r.guid=e.guid=e.guid||pe.guid++,r):void 0},now:function(){return+new Date},support:de}),"function"==typeof Symbol&&(pe.fn[Symbol.iterator]=ne[Symbol.iterator]),pe.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){ue["[object "+t+"]"]=t.toLowerCase()});var ye=function(e){function t(e,t,n,r){var i,o,a,s,u,l,d,p,h=t&&t.ownerDocument,g=t?t.nodeType:9;if(n=n||[],"string"!=typeof e||!e||1!==g&&9!==g&&11!==g)return n;if(!r&&((t?t.ownerDocument||t:B)!==H&&L(t),t=t||H,_)){if(11!==g&&(l=ve.exec(e)))if(i=l[1]){if(9===g){if(!(a=t.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(h&&(a=h.getElementById(i))&&R(t,a)&&a.id===i)return n.push(a),n}else{if(l[2])return K.apply(n,t.getElementsByTagName(e)),n;if((i=l[3])&&w.getElementsByClassName&&t.getElementsByClassName)return K.apply(n,t.getElementsByClassName(i)),n}if(w.qsa&&!X[e+" "]&&(!F||!F.test(e))){if(1!==g)h=t,p=e;else if("object"!==t.nodeName.toLowerCase()){for((s=t.getAttribute("id"))?s=s.replace(xe,"\\$&"):t.setAttribute("id",s=P),d=N(e),o=d.length,u=fe.test(s)?"#"+s:"[id='"+s+"']";o--;)d[o]=u+" "+f(d[o]);p=d.join(","),h=ye.test(e)&&c(t.parentNode)||t}if(p)try{return K.apply(n,h.querySelectorAll(p)),n}catch(e){}finally{s===P&&t.removeAttribute("id")}}}return S(e.replace(se,"$1"),t,n,r)}function n(){function e(n,r){return t.push(n+" ")>T.cacheLength&&delete e[t.shift()],e[n+" "]=r}var t=[];return e}function r(e){return e[P]=!0,e}function i(e){var t=H.createElement("div");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function o(e,t){for(var n=e.split("|"),r=n.length;r--;)T.attrHandle[n[r]]=t}function a(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||V)-(~e.sourceIndex||V);if(r)return r;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function s(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function u(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function l(e){return r(function(t){return t=+t,r(function(n,r){for(var i,o=e([],n.length,t),a=o.length;a--;)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function c(e){return e&&void 0!==e.getElementsByTagName&&e}function d(){}function f(e){for(var t=0,n=e.length,r="";n>t;t++)r+=e[t].value;return r}function p(e,t,n){var r=t.dir,i=n&&"parentNode"===r,o=I++;return t.first?function(t,n,o){for(;t=t[r];)if(1===t.nodeType||i)return e(t,n,o)}:function(t,n,a){var s,u,l,c=[W,o];if(a){for(;t=t[r];)if((1===t.nodeType||i)&&e(t,n,a))return!0}else for(;t=t[r];)if(1===t.nodeType||i){if(l=t[P]||(t[P]={}),u=l[t.uniqueID]||(l[t.uniqueID]={}),(s=u[r])&&s[0]===W&&s[1]===o)return c[2]=s[2];if(u[r]=c,c[2]=e(t,n,a))return!0}}}function h(e){return e.length>1?function(t,n,r){for(var i=e.length;i--;)if(!e[i](t,n,r))return!1;return!0}:e[0]}function g(e,n,r){for(var i=0,o=n.length;o>i;i++)t(e,n[i],r);return r}function m(e,t,n,r,i){for(var o,a=[],s=0,u=e.length,l=null!=t;u>s;s++)(o=e[s])&&(n&&!n(o,r,i)||(a.push(o),l&&t.push(s)));return a}function v(e,t,n,i,o,a){return i&&!i[P]&&(i=v(i)),o&&!o[P]&&(o=v(o,a)),r(function(r,a,s,u){var l,c,d,f=[],p=[],h=a.length,v=r||g(t||"*",s.nodeType?[s]:s,[]),y=!e||!r&&t?v:m(v,f,e,s,u),x=n?o||(r?e:h||i)?[]:a:y;if(n&&n(y,x,s,u),i)for(l=m(x,p),i(l,[],s,u),c=l.length;c--;)(d=l[c])&&(x[p[c]]=!(y[p[c]]=d));if(r){if(o||e){if(o){for(l=[],c=x.length;c--;)(d=x[c])&&l.push(y[c]=d);o(null,x=[],l,u)}for(c=x.length;c--;)(d=x[c])&&(l=o?ee(r,d):f[c])>-1&&(r[l]=!(a[l]=d))}}else x=m(x===a?x.splice(h,x.length):x),o?o(null,a,x,u):K.apply(a,x)})}function y(e){for(var t,n,r,i=e.length,o=T.relative[e[0].type],a=o||T.relative[" "],s=o?1:0,u=p(function(e){return e===t},a,!0),l=p(function(e){return ee(t,e)>-1},a,!0),c=[function(e,n,r){var i=!o&&(r||n!==A)||((t=n).nodeType?u(e,n,r):l(e,n,r));return t=null,i}];i>s;s++)if(n=T.relative[e[s].type])c=[p(h(c),n)];else{if(n=T.filter[e[s].type].apply(null,e[s].matches),n[P]){for(r=++s;i>r&&!T.relative[e[r].type];r++);return v(s>1&&h(c),s>1&&f(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace(se,"$1"),n,r>s&&y(e.slice(s,r)),i>r&&y(e=e.slice(r)),i>r&&f(e))}c.push(n)}return h(c)}function x(e,n){var i=n.length>0,o=e.length>0,a=function(r,a,s,u,l){var c,d,f,p=0,h="0",g=r&&[],v=[],y=A,x=r||o&&T.find.TAG("*",l),b=W+=null==y?1:Math.random()||.1,w=x.length;for(l&&(A=a===H||a||l);h!==w&&null!=(c=x[h]);h++){if(o&&c){for(d=0,a||c.ownerDocument===H||(L(c),s=!_);f=e[d++];)if(f(c,a||H,s)){u.push(c);break}l&&(W=b)}i&&((c=!f&&c)&&p--,r&&g.push(c))}if(p+=h,i&&h!==p){for(d=0;f=n[d++];)f(g,v,a,s);if(r){if(p>0)for(;h--;)g[h]||v[h]||(v[h]=G.call(u));v=m(v)}K.apply(u,v),l&&!r&&v.length>0&&p+n.length>1&&t.uniqueSort(u)}return l&&(W=b,A=y),g};return i?r(a):a}var b,w,T,C,E,N,k,S,A,D,j,L,H,q,_,F,M,O,R,P="sizzle"+1*new Date,B=e.document,W=0,I=0,$=n(),z=n(),X=n(),U=function(e,t){return e===t&&(j=!0),0},V=1<<31,Y={}.hasOwnProperty,J=[],G=J.pop,Q=J.push,K=J.push,Z=J.slice,ee=function(e,t){for(var n=0,r=e.length;r>n;n++)if(e[n]===t)return n;return-1},te="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",ne="[\\x20\\t\\r\\n\\f]",re="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",ie="\\["+ne+"*("+re+")(?:"+ne+"*([*^$|!~]?=)"+ne+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+re+"))|)"+ne+"*\\]",oe=":("+re+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+ie+")*)|.*)\\)|)",ae=new RegExp(ne+"+","g"),se=new RegExp("^"+ne+"+|((?:^|[^\\\\])(?:\\\\.)*)"+ne+"+$","g"),ue=new RegExp("^"+ne+"*,"+ne+"*"),le=new RegExp("^"+ne+"*([>+~]|"+ne+")"+ne+"*"),ce=new RegExp("="+ne+"*([^\\]'\"]*?)"+ne+"*\\]","g"),de=new RegExp(oe),fe=new RegExp("^"+re+"$"),pe={ID:new RegExp("^#("+re+")"),CLASS:new RegExp("^\\.("+re+")"),TAG:new RegExp("^("+re+"|[*])"),ATTR:new RegExp("^"+ie),PSEUDO:new RegExp("^"+oe),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+ne+"*(even|odd|(([+-]|)(\\d*)n|)"+ne+"*(?:([+-]|)"+ne+"*(\\d+)|))"+ne+"*\\)|)","i"),bool:new RegExp("^(?:"+te+")$","i"),needsContext:new RegExp("^"+ne+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+ne+"*((?:-\\d)?\\d*)"+ne+"*\\)|)(?=[^-]|$)","i")},he=/^(?:input|select|textarea|button)$/i,ge=/^h\d$/i,me=/^[^{]+\{\s*\[native \w/,ve=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ye=/[+~]/,xe=/'|\\/g,be=new RegExp("\\\\([\\da-f]{1,6}"+ne+"?|("+ne+")|.)","ig"),we=function(e,t,n){var r="0x"+t-65536;return r!=r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},Te=function(){L()};try{K.apply(J=Z.call(B.childNodes),B.childNodes),J[B.childNodes.length].nodeType}catch(e){K={apply:J.length?function(e,t){Q.apply(e,Z.call(t))}:function(e,t){for(var n=e.length,r=0;e[n++]=t[r++];);e.length=n-1}}}for(b in w=t.support={},E=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return!!t&&"HTML"!==t.nodeName},L=t.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:B;return r!==H&&9===r.nodeType&&r.documentElement?(H=r,q=H.documentElement,_=!E(H),(n=H.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",Te,!1):n.attachEvent&&n.attachEvent("onunload",Te)),w.attributes=i(function(e){return e.className="i",!e.getAttribute("className")}),w.getElementsByTagName=i(function(e){return e.appendChild(H.createComment("")),!e.getElementsByTagName("*").length}),w.getElementsByClassName=me.test(H.getElementsByClassName),w.getById=i(function(e){return q.appendChild(e).id=P,!H.getElementsByName||!H.getElementsByName(P).length}),w.getById?(T.find.ID=function(e,t){if(void 0!==t.getElementById&&_){var n=t.getElementById(e);return n?[n]:[]}},T.filter.ID=function(e){var t=e.replace(be,we);return function(e){return e.getAttribute("id")===t}}):(delete T.find.ID,T.filter.ID=function(e){var t=e.replace(be,we);return function(e){var n=void 0!==e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}}),T.find.TAG=w.getElementsByTagName?function(e,t){return void 0!==t.getElementsByTagName?t.getElementsByTagName(e):w.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){for(;n=o[i++];)1===n.nodeType&&r.push(n);return r}return o},T.find.CLASS=w.getElementsByClassName&&function(e,t){return void 0!==t.getElementsByClassName&&_?t.getElementsByClassName(e):void 0},M=[],F=[],(w.qsa=me.test(H.querySelectorAll))&&(i(function(e){q.appendChild(e).innerHTML="<a id='"+P+"'></a><select id='"+P+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&F.push("[*^$]="+ne+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||F.push("\\["+ne+"*(?:value|"+te+")"),e.querySelectorAll("[id~="+P+"-]").length||F.push("~="),e.querySelectorAll(":checked").length||F.push(":checked"),e.querySelectorAll("a#"+P+"+*").length||F.push(".#.+[+~]")}),i(function(e){var t=H.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&F.push("name"+ne+"*[*^$|!~]?="),e.querySelectorAll(":enabled").length||F.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),F.push(",.*:")})),(w.matchesSelector=me.test(O=q.matches||q.webkitMatchesSelector||q.mozMatchesSelector||q.oMatchesSelector||q.msMatchesSelector))&&i(function(e){w.disconnectedMatch=O.call(e,"div"),O.call(e,"[s!='']:x"),M.push("!=",oe)}),F=F.length&&new RegExp(F.join("|")),M=M.length&&new RegExp(M.join("|")),t=me.test(q.compareDocumentPosition),R=t||me.test(q.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},U=t?function(e,t){if(e===t)return j=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1,1&n||!w.sortDetached&&t.compareDocumentPosition(e)===n?e===H||e.ownerDocument===B&&R(B,e)?-1:t===H||t.ownerDocument===B&&R(B,t)?1:D?ee(D,e)-ee(D,t):0:4&n?-1:1)}:function(e,t){if(e===t)return j=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,s=[e],u=[t];if(!i||!o)return e===H?-1:t===H?1:i?-1:o?1:D?ee(D,e)-ee(D,t):0;if(i===o)return a(e,t);for(n=e;n=n.parentNode;)s.unshift(n);for(n=t;n=n.parentNode;)u.unshift(n);for(;s[r]===u[r];)r++;return r?a(s[r],u[r]):s[r]===B?-1:u[r]===B?1:0},H):H},t.matches=function(e,n){return t(e,null,null,n)},t.matchesSelector=function(e,n){if((e.ownerDocument||e)!==H&&L(e),n=n.replace(ce,"='$1']"),w.matchesSelector&&_&&!X[n+" "]&&(!M||!M.test(n))&&(!F||!F.test(n)))try{var r=O.call(e,n);if(r||w.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){}return t(n,H,null,[e]).length>0},t.contains=function(e,t){return(e.ownerDocument||e)!==H&&L(e),R(e,t)},t.attr=function(e,t){(e.ownerDocument||e)!==H&&L(e);var n=T.attrHandle[t.toLowerCase()],r=n&&Y.call(T.attrHandle,t.toLowerCase())?n(e,t,!_):void 0;return void 0!==r?r:w.attributes||!_?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},t.uniqueSort=function(e){var t,n=[],r=0,i=0;if(j=!w.detectDuplicates,D=!w.sortStable&&e.slice(0),e.sort(U),j){for(;t=e[i++];)t===e[i]&&(r=n.push(i));for(;r--;)e.splice(n[r],1)}return D=null,e},C=t.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=C(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r++];)n+=C(t);return n},T=t.selectors={cacheLength:50,createPseudo:r,match:pe,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(be,we),e[3]=(e[3]||e[4]||e[5]||"").replace(be,we),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||t.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&t.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return pe.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&de.test(n)&&(t=N(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(be,we).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=$[e+" "];return t||(t=new RegExp("(^|"+ne+")"+e+"("+ne+"|$)"))&&$(e,function(e){return t.test("string"==typeof e.className&&e.className||void 0!==e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,n,r){return function(i){var o=t.attr(i,e);return null==o?"!="===n:!n||(o+="","="===n?o===r:"!="===n?o!==r:"^="===n?r&&0===o.indexOf(r):"*="===n?r&&o.indexOf(r)>-1:"$="===n?r&&o.slice(-r.length)===r:"~="===n?(" "+o.replace(ae," ")+" ").indexOf(r)>-1:"|="===n&&(o===r||o.slice(0,r.length+1)===r+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,d,f,p,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,v=s&&t.nodeName.toLowerCase(),y=!u&&!s,x=!1;if(m){if(o){for(;g;){for(f=t;f=f[g];)if(s?f.nodeName.toLowerCase()===v:1===f.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&y){for(f=m,d=f[P]||(f[P]={}),c=d[f.uniqueID]||(d[f.uniqueID]={}),l=c[e]||[],p=l[0]===W&&l[1],x=p&&l[2], f=p&&m.childNodes[p];f=++p&&f&&f[g]||(x=p=0)||h.pop();)if(1===f.nodeType&&++x&&f===t){c[e]=[W,p,x];break}}else if(y&&(f=t,d=f[P]||(f[P]={}),c=d[f.uniqueID]||(d[f.uniqueID]={}),l=c[e]||[],p=l[0]===W&&l[1],x=p),!1===x)for(;(f=++p&&f&&f[g]||(x=p=0)||h.pop())&&((s?f.nodeName.toLowerCase()!==v:1!==f.nodeType)||!++x||(y&&(d=f[P]||(f[P]={}),c=d[f.uniqueID]||(d[f.uniqueID]={}),c[e]=[W,x]),f!==t)););return x-=i,x===r||x%r==0&&x/r>=0}}},PSEUDO:function(e,n){var i,o=T.pseudos[e]||T.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);return o[P]?o(n):o.length>1?(i=[e,e,"",n],T.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,t){for(var r,i=o(e,n),a=i.length;a--;)r=ee(e,i[a]),e[r]=!(t[r]=i[a])}):function(e){return o(e,0,i)}):o}},pseudos:{not:r(function(e){var t=[],n=[],i=k(e.replace(se,"$1"));return i[P]?r(function(e,t,n,r){for(var o,a=i(e,null,r,[]),s=e.length;s--;)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,r,o){return t[0]=e,i(t,null,o,n),t[0]=null,!n.pop()}}),has:r(function(e){return function(n){return t(e,n).length>0}}),contains:r(function(e){return e=e.replace(be,we),function(t){return(t.textContent||t.innerText||C(t)).indexOf(e)>-1}}),lang:r(function(e){return fe.test(e||"")||t.error("unsupported lang: "+e),e=e.replace(be,we).toLowerCase(),function(t){var n;do{if(n=_?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===q},focus:function(e){return e===H.activeElement&&(!H.hasFocus||H.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return!1===e.disabled},disabled:function(e){return!0===e.disabled},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!T.pseudos.empty(e)},header:function(e){return ge.test(e.nodeName)},input:function(e){return he.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:l(function(){return[0]}),last:l(function(e,t){return[t-1]}),eq:l(function(e,t,n){return[0>n?n+t:n]}),even:l(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:l(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:l(function(e,t,n){for(var r=0>n?n+t:n;--r>=0;)e.push(r);return e}),gt:l(function(e,t,n){for(var r=0>n?n+t:n;++r<t;)e.push(r);return e})}},T.pseudos.nth=T.pseudos.eq,{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})T.pseudos[b]=s(b);for(b in{submit:!0,reset:!0})T.pseudos[b]=u(b);return d.prototype=T.filters=T.pseudos,T.setFilters=new d,N=t.tokenize=function(e,n){var r,i,o,a,s,u,l,c=z[e+" "];if(c)return n?0:c.slice(0);for(s=e,u=[],l=T.preFilter;s;){for(a in r&&!(i=ue.exec(s))||(i&&(s=s.slice(i[0].length)||s),u.push(o=[])),r=!1,(i=le.exec(s))&&(r=i.shift(),o.push({value:r,type:i[0].replace(se," ")}),s=s.slice(r.length)),T.filter)!(i=pe[a].exec(s))||l[a]&&!(i=l[a](i))||(r=i.shift(),o.push({value:r,type:a,matches:i}),s=s.slice(r.length));if(!r)break}return n?s.length:s?t.error(e):z(e,u).slice(0)},k=t.compile=function(e,t){var n,r=[],i=[],o=X[e+" "];if(!o){for(t||(t=N(e)),n=t.length;n--;)o=y(t[n]),o[P]?r.push(o):i.push(o);o=X(e,x(i,r)),o.selector=e}return o},S=t.select=function(e,t,n,r){var i,o,a,s,u,l="function"==typeof e&&e,d=!r&&N(e=l.selector||e);if(n=n||[],1===d.length){if(o=d[0]=d[0].slice(0),o.length>2&&"ID"===(a=o[0]).type&&w.getById&&9===t.nodeType&&_&&T.relative[o[1].type]){if(t=(T.find.ID(a.matches[0].replace(be,we),t)||[])[0],!t)return n;l&&(t=t.parentNode),e=e.slice(o.shift().value.length)}for(i=pe.needsContext.test(e)?0:o.length;i--&&(a=o[i],!T.relative[s=a.type]);)if((u=T.find[s])&&(r=u(a.matches[0].replace(be,we),ye.test(o[0].type)&&c(t.parentNode)||t))){if(o.splice(i,1),e=r.length&&f(o),!e)return K.apply(n,r),n;break}}return(l||k(e,d))(r,t,!_,n,!t||ye.test(e)&&c(t.parentNode)||t),n},w.sortStable=P.split("").sort(U).join("")===P,w.detectDuplicates=!!j,L(),w.sortDetached=i(function(e){return 1&e.compareDocumentPosition(H.createElement("div"))}),i(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,n){return n?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),w.attributes&&i(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||o("value",function(e,t,n){return n||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue}),i(function(e){return null==e.getAttribute("disabled")})||o(te,function(e,t,n){var r;return n?void 0:!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),t}(e);pe.find=ye,pe.expr=ye.selectors,pe.expr[":"]=pe.expr.pseudos,pe.uniqueSort=pe.unique=ye.uniqueSort,pe.text=ye.getText,pe.isXMLDoc=ye.isXML,pe.contains=ye.contains;var xe=function(e,t,n){for(var r=[],i=void 0!==n;(e=e[t])&&9!==e.nodeType;)if(1===e.nodeType){if(i&&pe(e).is(n))break;r.push(e)}return r},be=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},we=pe.expr.match.needsContext,Te=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,Ce=/^.[^:#\[\.,]*$/;pe.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?pe.find.matchesSelector(r,e)?[r]:[]:pe.find.matches(e,pe.grep(t,function(e){return 1===e.nodeType}))},pe.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(pe(e).filter(function(){for(t=0;i>t;t++)if(pe.contains(r[t],this))return!0}));for(t=0;i>t;t++)pe.find(e,r[t],n);return n=this.pushStack(i>1?pe.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},filter:function(e){return this.pushStack(r(this,e||[],!1))},not:function(e){return this.pushStack(r(this,e||[],!0))},is:function(e){return!!r(this,"string"==typeof e&&we.test(e)?pe(e):e||[],!1).length}});var Ee,Ne=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,ke=pe.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||Ee,"string"==typeof e){if(r="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:Ne.exec(e),!r||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof pe?t[0]:t,pe.merge(this,pe.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:re,!0)),Te.test(r[1])&&pe.isPlainObject(t))for(r in t)pe.isFunction(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}if(i=re.getElementById(r[2]),i&&i.parentNode){if(i.id!==r[2])return Ee.find(e);this.length=1,this[0]=i}return this.context=re,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):pe.isFunction(e)?void 0!==n.ready?n.ready(e):e(pe):(void 0!==e.selector&&(this.selector=e.selector,this.context=e.context),pe.makeArray(e,this))};ke.prototype=pe.fn,Ee=pe(re);var Se=/^(?:parents|prev(?:Until|All))/,Ae={children:!0,contents:!0,next:!0,prev:!0};pe.fn.extend({has:function(e){var t,n=pe(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(pe.contains(this,n[t]))return!0})},closest:function(e,t){for(var n,r=0,i=this.length,o=[],a=we.test(e)||"string"!=typeof e?pe(e,t||this.context):0;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?a.index(n)>-1:1===n.nodeType&&pe.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?pe.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?pe.inArray(this[0],pe(e)):pe.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(pe.uniqueSort(pe.merge(this.get(),pe(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),pe.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return xe(e,"parentNode")},parentsUntil:function(e,t,n){return xe(e,"parentNode",n)},next:function(e){return i(e,"nextSibling")},prev:function(e){return i(e,"previousSibling")},nextAll:function(e){return xe(e,"nextSibling")},prevAll:function(e){return xe(e,"previousSibling")},nextUntil:function(e,t,n){return xe(e,"nextSibling",n)},prevUntil:function(e,t,n){return xe(e,"previousSibling",n)},siblings:function(e){return be((e.parentNode||{}).firstChild,e)},children:function(e){return be(e.firstChild)},contents:function(e){return pe.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:pe.merge([],e.childNodes)}},function(e,t){pe.fn[e]=function(n,r){var i=pe.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=pe.filter(r,i)),this.length>1&&(Ae[e]||(i=pe.uniqueSort(i)),Se.test(e)&&(i=i.reverse())),this.pushStack(i)}});var De,je,Le=/\S+/g;for(je in pe.Callbacks=function(e){e="string"==typeof e?o(e):pe.extend({},e);var t,n,r,i,a=[],s=[],u=-1,l=function(){for(i=e.once,r=t=!0;s.length;u=-1)for(n=s.shift();++u<a.length;)!1===a[u].apply(n[0],n[1])&&e.stopOnFalse&&(u=a.length,n=!1);e.memory||(n=!1),t=!1,i&&(a=n?[]:"")},c={add:function(){return a&&(n&&!t&&(u=a.length-1,s.push(n)),function t(n){pe.each(n,function(n,r){pe.isFunction(r)?e.unique&&c.has(r)||a.push(r):r&&r.length&&"string"!==pe.type(r)&&t(r)})}(arguments),n&&!t&&l()),this},remove:function(){return pe.each(arguments,function(e,t){for(var n;(n=pe.inArray(t,a,n))>-1;)a.splice(n,1),u>=n&&u--}),this},has:function(e){return e?pe.inArray(e,a)>-1:a.length>0},empty:function(){return a&&(a=[]),this},disable:function(){return i=s=[],a=n="",this},disabled:function(){return!a},lock:function(){return i=!0,n||c.disable(),this},locked:function(){return!!i},fireWith:function(e,n){return i||(n=n||[],n=[e,n.slice?n.slice():n],s.push(n),t||l()),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},pe.extend({Deferred:function(e){var t=[["resolve","done",pe.Callbacks("once memory"),"resolved"],["reject","fail",pe.Callbacks("once memory"),"rejected"],["notify","progress",pe.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return pe.Deferred(function(n){pe.each(t,function(t,o){var a=pe.isFunction(e[t])&&e[t];i[o[1]](function(){var e=a&&a.apply(this,arguments);e&&pe.isFunction(e.promise)?e.promise().progress(n.notify).done(n.resolve).fail(n.reject):n[o[0]+"With"](this===r?n.promise():this,a?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?pe.extend(e,r):r}},i={};return r.pipe=r.then,pe.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t,n,r,i=0,o=ie.call(arguments),a=o.length,s=1!==a||e&&pe.isFunction(e.promise)?a:0,u=1===s?e:pe.Deferred(),l=function(e,n,r){return function(i){n[e]=this,r[e]=arguments.length>1?ie.call(arguments):i,r===t?u.notifyWith(n,r):--s||u.resolveWith(n,r)}};if(a>1)for(t=new Array(a),n=new Array(a),r=new Array(a);a>i;i++)o[i]&&pe.isFunction(o[i].promise)?o[i].promise().progress(l(i,n,t)).done(l(i,r,o)).fail(u.reject):--s;return s||u.resolveWith(r,o),u.promise()}}),pe.fn.ready=function(e){return pe.ready.promise().done(e),this},pe.extend({isReady:!1,readyWait:1,holdReady:function(e){e?pe.readyWait++:pe.ready(!0)},ready:function(e){(!0===e?--pe.readyWait:pe.isReady)||(pe.isReady=!0,!0!==e&&--pe.readyWait>0||(De.resolveWith(re,[pe]),pe.fn.triggerHandler&&(pe(re).triggerHandler("ready"),pe(re).off("ready"))))}}),pe.ready.promise=function(t){if(!De)if(De=pe.Deferred(),"complete"===re.readyState||"loading"!==re.readyState&&!re.documentElement.doScroll)e.setTimeout(pe.ready);else if(re.addEventListener)re.addEventListener("DOMContentLoaded",s),e.addEventListener("load",s);else{re.attachEvent("onreadystatechange",s),e.attachEvent("onload",s);var n=!1;try{n=null==e.frameElement&&re.documentElement}catch(e){}n&&n.doScroll&&function t(){if(!pe.isReady){try{n.doScroll("left")}catch(n){return e.setTimeout(t,50)}a(),pe.ready()}}()}return De.promise(t)},pe.ready.promise(),pe(de))break;de.ownFirst="0"===je,de.inlineBlockNeedsLayout=!1,pe(function(){var e,t,n,r;n=re.getElementsByTagName("body")[0],n&&n.style&&(t=re.createElement("div"),r=re.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),void 0!==t.style.zoom&&(t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",de.inlineBlockNeedsLayout=e=3===t.offsetWidth,e&&(n.style.zoom=1)),n.removeChild(r))}),function(){var e=re.createElement("div");de.deleteExpando=!0;try{delete e.test}catch(e){de.deleteExpando=!1}e=null}();var He=function(e){var t=pe.noData[(e.nodeName+" ").toLowerCase()],n=+e.nodeType||1;return(1===n||9===n)&&(!t||!0!==t&&e.getAttribute("classid")===t)},qe=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,_e=/([A-Z])/g;pe.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?pe.cache[e[pe.expando]]:e[pe.expando],!!e&&!l(e)},data:function(e,t,n){return c(e,t,n)},removeData:function(e,t){return d(e,t)},_data:function(e,t,n){return c(e,t,n,!0)},_removeData:function(e,t){return d(e,t,!0)}}),pe.fn.extend({data:function(e,t){var n,r,i,o=this[0],a=o&&o.attributes;if(void 0===e){if(this.length&&(i=pe.data(o),1===o.nodeType&&!pe._data(o,"parsedAttrs"))){for(n=a.length;n--;)a[n]&&(r=a[n].name,0===r.indexOf("data-")&&(r=pe.camelCase(r.slice(5)),u(o,r,i[r])));pe._data(o,"parsedAttrs",!0)}return i}return"object"==typeof e?this.each(function(){pe.data(this,e)}):arguments.length>1?this.each(function(){pe.data(this,e,t)}):o?u(o,e,pe.data(o,e)):void 0},removeData:function(e){return this.each(function(){pe.removeData(this,e)})}}),pe.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=pe._data(e,t),n&&(!r||pe.isArray(n)?r=pe._data(e,t,pe.makeArray(n)):r.push(n)),r||[]):void 0},dequeue:function(e,t){t=t||"fx";var n=pe.queue(e,t),r=n.length,i=n.shift(),o=pe._queueHooks(e,t),a=function(){pe.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return pe._data(e,n)||pe._data(e,n,{empty:pe.Callbacks("once memory").add(function(){pe._removeData(e,t+"queue"),pe._removeData(e,n)})})}}),pe.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length<n?pe.queue(this[0],e):void 0===t?this:this.each(function(){var n=pe.queue(this,e,t);pe._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&pe.dequeue(this,e)})},dequeue:function(e){return this.each(function(){pe.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=pe.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";a--;)n=pe._data(o[a],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}}),function(){var e;de.shrinkWrapBlocks=function(){return null!=e?e:(e=!1,n=re.getElementsByTagName("body")[0],n&&n.style?(t=re.createElement("div"),r=re.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),void 0!==t.style.zoom&&(t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",t.appendChild(re.createElement("div")).style.width="5px",e=3!==t.offsetWidth),n.removeChild(r),e):void 0);var t,n,r}}();var Fe=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Me=new RegExp("^(?:([+-])=|)("+Fe+")([a-z%]*)$","i"),Oe=["Top","Right","Bottom","Left"],Re=function(e,t){return e=t||e,"none"===pe.css(e,"display")||!pe.contains(e.ownerDocument,e)},Pe=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===pe.type(n))for(s in i=!0,n)Pe(e,t,s,n[s],!0,o,a);else if(void 0!==r&&(i=!0,pe.isFunction(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(pe(e),n)})),t))for(;u>s;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:l?t.call(e):u?t(e[0],n):o},Be=/^(?:checkbox|radio)$/i,We=/<([\w:-]+)/,Ie=/^$|\/(?:java|ecma)script/i,$e=/^\s+/,ze="abbr|article|aside|audio|bdi|canvas|data|datalist|details|dialog|figcaption|figure|footer|header|hgroup|main|mark|meter|nav|output|picture|progress|section|summary|template|time|video";!function(){var e=re.createElement("div"),t=re.createDocumentFragment(),n=re.createElement("input");e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",de.leadingWhitespace=3===e.firstChild.nodeType,de.tbody=!e.getElementsByTagName("tbody").length,de.htmlSerialize=!!e.getElementsByTagName("link").length,de.html5Clone="<:nav></:nav>"!==re.createElement("nav").cloneNode(!0).outerHTML,n.type="checkbox",n.checked=!0,t.appendChild(n),de.appendChecked=n.checked,e.innerHTML="<textarea>x</textarea>",de.noCloneChecked=!!e.cloneNode(!0).lastChild.defaultValue,t.appendChild(e),n=re.createElement("input"),n.setAttribute("type","radio"),n.setAttribute("checked","checked"),n.setAttribute("name","t"),e.appendChild(n),de.checkClone=e.cloneNode(!0).cloneNode(!0).lastChild.checked,de.noCloneEvent=!!e.addEventListener,e[pe.expando]=1,de.attributes=!e.getAttribute(pe.expando)}();var Xe={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>"],_default:de.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]};Xe.optgroup=Xe.option,Xe.tbody=Xe.tfoot=Xe.colgroup=Xe.caption=Xe.thead,Xe.th=Xe.td;var Ue=/<|&#?\w+;/,Ve=/<tbody/i;!function(){var t,n,r=re.createElement("div");for(t in{submit:!0,change:!0,focusin:!0})n="on"+t,(de[t]=n in e)||(r.setAttribute(n,"t"),de[t]=!1===r.attributes[n].expando);r=null}();var Ye=/^(?:input|select|textarea)$/i,Je=/^key/,Ge=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Qe=/^(?:focusinfocus|focusoutblur)$/,Ke=/^([^.]*)(?:\.(.+)|)/;pe.event={global:{},add:function(e,t,n,r,i){var o,a,s,u,l,c,d,f,p,h,g,m=pe._data(e);if(m){for(n.handler&&(u=n,n=u.handler,i=u.selector),n.guid||(n.guid=pe.guid++),(a=m.events)||(a=m.events={}),(c=m.handle)||(c=m.handle=function(e){return void 0===pe||e&&pe.event.triggered===e.type?void 0:pe.event.dispatch.apply(c.elem,arguments)},c.elem=e),t=(t||"").match(Le)||[""],s=t.length;s--;)o=Ke.exec(t[s])||[],p=g=o[1],h=(o[2]||"").split(".").sort(),p&&(l=pe.event.special[p]||{},p=(i?l.delegateType:l.bindType)||p,l=pe.event.special[p]||{},d=pe.extend({type:p,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&pe.expr.match.needsContext.test(i),namespace:h.join(".")},u),(f=a[p])||(f=a[p]=[],f.delegateCount=0,l.setup&&!1!==l.setup.call(e,r,h,c)||(e.addEventListener?e.addEventListener(p,c,!1):e.attachEvent&&e.attachEvent("on"+p,c))),l.add&&(l.add.call(e,d),d.handler.guid||(d.handler.guid=n.guid)),i?f.splice(f.delegateCount++,0,d):f.push(d),pe.event.global[p]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,d,f,p,h,g,m=pe.hasData(e)&&pe._data(e);if(m&&(c=m.events)){for(t=(t||"").match(Le)||[""],l=t.length;l--;)if(s=Ke.exec(t[l])||[],p=g=s[1],h=(s[2]||"").split(".").sort(),p){for(d=pe.event.special[p]||{},p=(r?d.delegateType:d.bindType)||p,f=c[p]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;o--;)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,d.remove&&d.remove.call(e,a));u&&!f.length&&(d.teardown&&!1!==d.teardown.call(e,h,m.handle)||pe.removeEvent(e,p,m.handle),delete c[p])}else for(p in c)pe.event.remove(e,p+t[l],n,r,!0);pe.isEmptyObject(c)&&(delete m.handle,pe._removeData(e,"events"))}},trigger:function(t,n,r,i){var o,a,s,u,l,c,d,f=[r||re],p=ce.call(t,"type")?t.type:t,h=ce.call(t,"namespace")?t.namespace.split("."):[];if(s=c=r=r||re,3!==r.nodeType&&8!==r.nodeType&&!Qe.test(p+pe.event.triggered)&&(p.indexOf(".")>-1&&(h=p.split("."),p=h.shift(),h.sort()),a=p.indexOf(":")<0&&"on"+p,t=t[pe.expando]?t:new pe.Event(p,"object"==typeof t&&t),t.isTrigger=i?2:3,t.namespace=h.join("."),t.rnamespace=t.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=r),n=null==n?[t]:pe.makeArray(n,[t]),l=pe.event.special[p]||{},i||!l.trigger||!1!==l.trigger.apply(r,n))){if(!i&&!l.noBubble&&!pe.isWindow(r)){for(u=l.delegateType||p,Qe.test(u+p)||(s=s.parentNode);s;s=s.parentNode)f.push(s),c=s;c===(r.ownerDocument||re)&&f.push(c.defaultView||c.parentWindow||e)}for(d=0;(s=f[d++])&&!t.isPropagationStopped();)t.type=d>1?u:l.bindType||p,o=(pe._data(s,"events")||{})[t.type]&&pe._data(s,"handle"),o&&o.apply(s,n),o=a&&s[a],o&&o.apply&&He(s)&&(t.result=o.apply(s,n),!1===t.result&&t.preventDefault());if(t.type=p,!i&&!t.isDefaultPrevented()&&(!l._default||!1===l._default.apply(f.pop(),n))&&He(r)&&a&&r[p]&&!pe.isWindow(r)){c=r[a],c&&(r[a]=null),pe.event.triggered=p;try{r[p]()}catch(e){}pe.event.triggered=void 0,c&&(r[a]=c)}return t.result}},dispatch:function(e){e=pe.event.fix(e);var t,n,r,i,o,a=[],s=ie.call(arguments),u=(pe._data(this,"events")||{})[e.type]||[],l=pe.event.special[e.type]||{};if(s[0]=e,e.delegateTarget=this,!l.preDispatch||!1!==l.preDispatch.call(this,e)){for(a=pe.event.handlers.call(this,e,u),t=0;(i=a[t++])&&!e.isPropagationStopped();)for(e.currentTarget=i.elem,n=0;(o=i.handlers[n++])&&!e.isImmediatePropagationStopped();)e.rnamespace&&!e.rnamespace.test(o.namespace)||(e.handleObj=o,e.data=o.data,r=((pe.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,s),void 0!==r&&!1===(e.result=r)&&(e.preventDefault(),e.stopPropagation()));return l.postDispatch&&l.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,r,i,o,a=[],s=t.delegateCount,u=e.target;if(s&&u.nodeType&&("click"!==e.type||isNaN(e.button)||e.button<1))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(!0!==u.disabled||"click"!==e.type)){for(r=[],n=0;s>n;n++)o=t[n],i=o.selector+" ",void 0===r[i]&&(r[i]=o.needsContext?pe(i,this).index(u)>-1:pe.find(i,this,null,[u]).length),r[i]&&r.push(o);r.length&&a.push({elem:u,handlers:r})}return s<t.length&&a.push({elem:this,handlers:t.slice(s)}),a},fix:function(e){if(e[pe.expando])return e;var t,n,r,i=e.type,o=e,a=this.fixHooks[i];for(a||(this.fixHooks[i]=a=Ge.test(i)?this.mouseHooks:Je.test(i)?this.keyHooks:{}),r=a.props?this.props.concat(a.props):this.props,e=new pe.Event(o),t=r.length;t--;)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||re),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,a.filter?a.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget detail eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,o=t.button,a=t.fromElement;return null==e.pageX&&null!=t.clientX&&(r=e.target.ownerDocument||re,i=r.documentElement,n=r.body,e.pageX=t.clientX+(i&&i.scrollLeft||n&&n.scrollLeft||0)-(i&&i.clientLeft||n&&n.clientLeft||0),e.pageY=t.clientY+(i&&i.scrollTop||n&&n.scrollTop||0)-(i&&i.clientTop||n&&n.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?t.toElement:a),e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==b()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===b()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return pe.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(e){return pe.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n){var r=pe.extend(new pe.Event,n,{type:e,isSimulated:!0});pe.event.trigger(r,null,t),r.isDefaultPrevented()&&n.preventDefault()}},pe.removeEvent=re.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n)}:function(e,t,n){var r="on"+t;e.detachEvent&&(void 0===e[r]&&(e[r]=null),e.detachEvent(r,n))},pe.Event=function(e,t){return this instanceof pe.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&!1===e.returnValue?y:x):this.type=e,t&&pe.extend(this,t),this.timeStamp=e&&e.timeStamp||pe.now(),void(this[pe.expando]=!0)):new pe.Event(e,t)},pe.Event.prototype={constructor:pe.Event,isDefaultPrevented:x,isPropagationStopped:x,isImmediatePropagationStopped:x,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=y,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=y,e&&!this.isSimulated&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=y,e&&e.stopImmediatePropagation&&e.stopImmediatePropagation(),this.stopPropagation()}},pe.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){pe.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return i&&(i===r||pe.contains(r,i))||(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),de.submit||(pe.event.special.submit={setup:function(){return!pe.nodeName(this,"form")&&void pe.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,n=pe.nodeName(t,"input")||pe.nodeName(t,"button")?pe.prop(t,"form"):void 0;n&&!pe._data(n,"submit")&&(pe.event.add(n,"submit._submit",function(e){e._submitBubble=!0}),pe._data(n,"submit",!0))})},postDispatch:function(e){e._submitBubble&&(delete e._submitBubble,this.parentNode&&!e.isTrigger&&pe.event.simulate("submit",this.parentNode,e))},teardown:function(){return!pe.nodeName(this,"form")&&void pe.event.remove(this,"._submit")}}),de.change||(pe.event.special.change={setup:function(){return Ye.test(this.nodeName)?("checkbox"!==this.type&&"radio"!==this.type||(pe.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._justChanged=!0)}),pe.event.add(this,"click._change",function(e){this._justChanged&&!e.isTrigger&&(this._justChanged=!1),pe.event.simulate("change",this,e)})),!1):void pe.event.add(this,"beforeactivate._change",function(e){var t=e.target;Ye.test(t.nodeName)&&!pe._data(t,"change")&&(pe.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||pe.event.simulate("change",this.parentNode,e)}),pe._data(t,"change",!0))})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return pe.event.remove(this,"._change"),!Ye.test(this.nodeName)}}),de.focusin||pe.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){pe.event.simulate(t,e.target,pe.event.fix(e))};pe.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=pe._data(r,t);i||r.addEventListener(e,n,!0),pe._data(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=pe._data(r,t)-1;i?pe._data(r,t,i):(r.removeEventListener(e,n,!0),pe._removeData(r,t))}}}),pe.fn.extend({on:function(e,t,n,r){return w(this,e,t,n,r)},one:function(e,t,n,r){return w(this,e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,pe(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return!1!==t&&"function"!=typeof t||(n=t,t=void 0),!1===n&&(n=x),this.each(function(){pe.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){pe.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?pe.event.trigger(e,t,n,!0):void 0}});var Ze=/ jQuery\d+="(?:null|\d+)"/g,et=new RegExp("<(?:"+ze+")[\\s/>]","i"),tt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,nt=/<script|<style|<link/i,rt=/checked\s*(?:[^=]|=\s*.checked.)/i,it=/^true\/(.*)/,ot=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,at=p(re),st=at.appendChild(re.createElement("div"));pe.extend({htmlPrefilter:function(e){return e.replace(tt,"<$1></$2>")},clone:function(e,t,n){var r,i,o,a,s,u=pe.contains(e.ownerDocument,e);if(de.html5Clone||pe.isXMLDoc(e)||!et.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(st.innerHTML=e.outerHTML,st.removeChild(o=st.firstChild)),!(de.noCloneEvent&&de.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||pe.isXMLDoc(e)))for(r=h(o),s=h(e),a=0;null!=(i=s[a]);++a)r[a]&&k(i,r[a]);if(t)if(n)for(s=s||h(e),r=r||h(o),a=0;null!=(i=s[a]);a++)N(i,r[a]);else N(e,o);return r=h(o,"script"),r.length>0&&g(r,!u&&h(e,"script")),r=s=i=null,o},cleanData:function(e,t){for(var n,r,i,o,a=0,s=pe.expando,u=pe.cache,l=de.attributes,c=pe.event.special;null!=(n=e[a]);a++)if((t||He(n))&&(i=n[s],o=i&&u[i])){if(o.events)for(r in o.events)c[r]?pe.event.remove(n,r):pe.removeEvent(n,r,o.handle);u[i]&&(delete u[i],l||void 0===n.removeAttribute?n[s]=void 0:n.removeAttribute(s),ne.push(i))}}}),pe.fn.extend({domManip:S,detach:function(e){return A(this,e,!0)},remove:function(e){return A(this,e)},text:function(e){return Pe(this,function(e){return void 0===e?pe.text(this):this.empty().append((this[0]&&this[0].ownerDocument||re).createTextNode(e))},null,e,arguments.length)},append:function(){return S(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=T(this,e);t.appendChild(e)}})},prepend:function(){return S(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=T(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return S(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return S(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){for(1===e.nodeType&&pe.cleanData(h(e,!1));e.firstChild;)e.removeChild(e.firstChild);e.options&&pe.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return pe.clone(this,e,t)})},html:function(e){return Pe(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Ze,""):void 0;if("string"==typeof e&&!nt.test(e)&&(de.htmlSerialize||!et.test(e))&&(de.leadingWhitespace||!$e.test(e))&&!Xe[(We.exec(e)||["",""])[1].toLowerCase()]){e=pe.htmlPrefilter(e);try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(pe.cleanData(h(t,!1)),t.innerHTML=e);t=0}catch(e){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=[];return S(this,arguments,function(t){var n=this.parentNode;pe.inArray(this,e)<0&&(pe.cleanData(h(this)),n&&n.replaceChild(t,this))},e)}}),pe.each({appendTo:"append", prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){pe.fn[e]=function(e){for(var n,r=0,i=[],o=pe(e),a=o.length-1;a>=r;r++)n=r===a?this:this.clone(!0),pe(o[r])[t](n),ae.apply(i,n.get());return this.pushStack(i)}});var ut,lt={HTML:"block",BODY:"block"},ct=/^margin/,dt=new RegExp("^("+Fe+")(?!px)[a-z%]+$","i"),ft=function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];for(o in i=n.apply(e,r||[]),t)e.style[o]=a[o];return i},pt=re.documentElement;!function(){var t,n,r,i,o,a,s=re.createElement("div"),u=re.createElement("div");if(u.style){function l(){var l,c,d=re.documentElement;d.appendChild(s),u.style.cssText="-webkit-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",t=r=a=!1,n=o=!0,e.getComputedStyle&&(c=e.getComputedStyle(u),t="1%"!==(c||{}).top,a="2px"===(c||{}).marginLeft,r="4px"===(c||{width:"4px"}).width,u.style.marginRight="50%",n="4px"===(c||{marginRight:"4px"}).marginRight,l=u.appendChild(re.createElement("div")),l.style.cssText=u.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",l.style.marginRight=l.style.width="0",u.style.width="1px",o=!parseFloat((e.getComputedStyle(l)||{}).marginRight),u.removeChild(l)),u.style.display="none",i=0===u.getClientRects().length,i&&(u.style.display="",u.innerHTML="<table><tr><td></td><td>t</td></tr></table>",u.childNodes[0].style.borderCollapse="separate",l=u.getElementsByTagName("td"),l[0].style.cssText="margin:0;border:0;padding:0;display:none",i=0===l[0].offsetHeight,i&&(l[0].style.display="",l[1].style.display="none",i=0===l[0].offsetHeight)),d.removeChild(s)}u.style.cssText="float:left;opacity:.5",de.opacity="0.5"===u.style.opacity,de.cssFloat=!!u.style.cssFloat,u.style.backgroundClip="content-box",u.cloneNode(!0).style.backgroundClip="",de.clearCloneStyle="content-box"===u.style.backgroundClip,s=re.createElement("div"),s.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",u.innerHTML="",s.appendChild(u),de.boxSizing=""===u.style.boxSizing||""===u.style.MozBoxSizing||""===u.style.WebkitBoxSizing,pe.extend(de,{reliableHiddenOffsets:function(){return null==t&&l(),i},boxSizingReliable:function(){return null==t&&l(),r},pixelMarginRight:function(){return null==t&&l(),n},pixelPosition:function(){return null==t&&l(),t},reliableMarginRight:function(){return null==t&&l(),o},reliableMarginLeft:function(){return null==t&&l(),a}})}}();var ht,gt,mt=/^(top|right|bottom|left)$/;e.getComputedStyle?(ht=function(t){var n=t.ownerDocument.defaultView;return n&&n.opener||(n=e),n.getComputedStyle(t)},gt=function(e,t,n){var r,i,o,a,s=e.style;return n=n||ht(e),a=n?n.getPropertyValue(t)||n[t]:void 0,""!==a&&void 0!==a||pe.contains(e.ownerDocument,e)||(a=pe.style(e,t)),n&&!de.pixelMarginRight()&&dt.test(a)&&ct.test(t)&&(r=s.width,i=s.minWidth,o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o),void 0===a?a:a+""}):pt.currentStyle&&(ht=function(e){return e.currentStyle},gt=function(e,t,n){var r,i,o,a,s=e.style;return n=n||ht(e),a=n?n[t]:void 0,null==a&&s&&s[t]&&(a=s[t]),dt.test(a)&&!mt.test(t)&&(r=s.left,i=e.runtimeStyle,o=i&&i.left,o&&(i.left=e.currentStyle.left),s.left="fontSize"===t?"1em":a,a=s.pixelLeft+"px",s.left=r,o&&(i.left=o)),void 0===a?a:a+""||"auto"});var vt=/alpha\([^)]*\)/i,yt=/opacity\s*=\s*([^)]*)/i,xt=/^(none|table(?!-c[ea]).+)/,bt=new RegExp("^("+Fe+")(.*)$","i"),wt={position:"absolute",visibility:"hidden",display:"block"},Tt={letterSpacing:"0",fontWeight:"400"},Ct=["Webkit","O","Moz","ms"],Et=re.createElement("div").style;pe.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=gt(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{float:de.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=pe.camelCase(t),u=e.style;if(t=pe.cssProps[s]||(pe.cssProps[s]=H(s)||s),a=pe.cssHooks[t]||pe.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:u[t];if(o=typeof n,"string"===o&&(i=Me.exec(n))&&i[1]&&(n=f(e,t,i),o="number"),null!=n&&n==n&&("number"===o&&(n+=i&&i[3]||(pe.cssNumber[s]?"":"px")),de.clearCloneStyle||""!==n||0!==t.indexOf("background")||(u[t]="inherit"),!(a&&"set"in a&&void 0===(n=a.set(e,n,r)))))try{u[t]=n}catch(e){}}},css:function(e,t,n,r){var i,o,a,s=pe.camelCase(t);return t=pe.cssProps[s]||(pe.cssProps[s]=H(s)||s),a=pe.cssHooks[t]||pe.cssHooks[s],a&&"get"in a&&(o=a.get(e,!0,n)),void 0===o&&(o=gt(e,t,r)),"normal"===o&&t in Tt&&(o=Tt[t]),""===n||n?(i=parseFloat(o),!0===n||isFinite(i)?i||0:o):o}}),pe.each(["height","width"],function(e,t){pe.cssHooks[t]={get:function(e,n,r){return n?xt.test(pe.css(e,"display"))&&0===e.offsetWidth?ft(e,wt,function(){return M(e,t,r)}):M(e,t,r):void 0},set:function(e,n,r){var i=r&&ht(e);return _(e,n,r?F(e,t,r,de.boxSizing&&"border-box"===pe.css(e,"boxSizing",!1,i),i):0)}}}),de.opacity||(pe.cssHooks.opacity={get:function(e,t){return yt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=pe.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===pe.trim(o.replace(vt,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=vt.test(o)?o.replace(vt,i):o+" "+i)}}),pe.cssHooks.marginRight=L(de.reliableMarginRight,function(e,t){return t?ft(e,{display:"inline-block"},gt,[e,"marginRight"]):void 0}),pe.cssHooks.marginLeft=L(de.reliableMarginLeft,function(e,t){return t?(parseFloat(gt(e,"marginLeft"))||(pe.contains(e.ownerDocument,e)?e.getBoundingClientRect().left-ft(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}):0))+"px":void 0}),pe.each({margin:"",padding:"",border:"Width"},function(e,t){pe.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];4>r;r++)i[e+Oe[r]+t]=o[r]||o[r-2]||o[0];return i}},ct.test(e)||(pe.cssHooks[e+t].set=_)}),pe.fn.extend({css:function(e,t){return Pe(this,function(e,t,n){var r,i,o={},a=0;if(pe.isArray(t)){for(r=ht(e),i=t.length;i>a;a++)o[t[a]]=pe.css(e,t[a],!1,r);return o}return void 0!==n?pe.style(e,t,n):pe.css(e,t)},e,t,arguments.length>1)},show:function(){return q(this,!0)},hide:function(){return q(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){Re(this)?pe(this).show():pe(this).hide()})}}),pe.Tween=O,O.prototype={constructor:O,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||pe.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(pe.cssNumber[n]?"":"px")},cur:function(){var e=O.propHooks[this.prop];return e&&e.get?e.get(this):O.propHooks._default.get(this)},run:function(e){var t,n=O.propHooks[this.prop];return this.options.duration?this.pos=t=pe.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):O.propHooks._default.set(this),this}},O.prototype.init.prototype=O.prototype,O.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=pe.css(e.elem,e.prop,""),t&&"auto"!==t?t:0)},set:function(e){pe.fx.step[e.prop]?pe.fx.step[e.prop](e):1!==e.elem.nodeType||null==e.elem.style[pe.cssProps[e.prop]]&&!pe.cssHooks[e.prop]?e.elem[e.prop]=e.now:pe.style(e.elem,e.prop,e.now+e.unit)}}},O.propHooks.scrollTop=O.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},pe.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},pe.fx=O.prototype.init,pe.fx.step={};var Nt,kt,St=/^(?:toggle|show|hide)$/,At=/queueHooks$/;pe.Animation=pe.extend($,{tweeners:{"*":[function(e,t){var n=this.createTween(e,t);return f(n.elem,e,Me.exec(t),n),n}]},tweener:function(e,t){pe.isFunction(e)?(t=e,e=["*"]):e=e.match(Le);for(var n,r=0,i=e.length;i>r;r++)n=e[r],$.tweeners[n]=$.tweeners[n]||[],$.tweeners[n].unshift(t)},prefilters:[W],prefilter:function(e,t){t?$.prefilters.unshift(e):$.prefilters.push(e)}}),pe.speed=function(e,t,n){var r=e&&"object"==typeof e?pe.extend({},e):{complete:n||!n&&t||pe.isFunction(e)&&e,duration:e,easing:n&&t||t&&!pe.isFunction(t)&&t};return r.duration=pe.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in pe.fx.speeds?pe.fx.speeds[r.duration]:pe.fx.speeds._default,null!=r.queue&&!0!==r.queue||(r.queue="fx"),r.old=r.complete,r.complete=function(){pe.isFunction(r.old)&&r.old.call(this),r.queue&&pe.dequeue(this,r.queue)},r},pe.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Re).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=pe.isEmptyObject(e),o=pe.speed(t,n,r),a=function(){var t=$(this,pe.extend({},e),o);(i||pe._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||!1===o.queue?this.each(a):this.queue(o.queue,a)},stop:function(e,t,n){var r=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=void 0),t&&!1!==e&&this.queue(e||"fx",[]),this.each(function(){var t=!0,i=null!=e&&e+"queueHooks",o=pe.timers,a=pe._data(this);if(i)a[i]&&a[i].stop&&r(a[i]);else for(i in a)a[i]&&a[i].stop&&At.test(i)&&r(a[i]);for(i=o.length;i--;)o[i].elem!==this||null!=e&&o[i].queue!==e||(o[i].anim.stop(n),t=!1,o.splice(i,1));!t&&n||pe.dequeue(this,e)})},finish:function(e){return!1!==e&&(e=e||"fx"),this.each(function(){var t,n=pe._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=pe.timers,a=r?r.length:0;for(n.finish=!0,pe.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}}),pe.each(["toggle","show","hide"],function(e,t){var n=pe.fn[t];pe.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(P(t,!0),e,r,i)}}),pe.each({slideDown:P("show"),slideUp:P("hide"),slideToggle:P("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){pe.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),pe.timers=[],pe.fx.tick=function(){var e,t=pe.timers,n=0;for(Nt=pe.now();n<t.length;n++)e=t[n],e()||t[n]!==e||t.splice(n--,1);t.length||pe.fx.stop(),Nt=void 0},pe.fx.timer=function(e){pe.timers.push(e),e()?pe.fx.start():pe.timers.pop()},pe.fx.interval=13,pe.fx.start=function(){kt||(kt=e.setInterval(pe.fx.tick,pe.fx.interval))},pe.fx.stop=function(){e.clearInterval(kt),kt=null},pe.fx.speeds={slow:600,fast:200,_default:400},pe.fn.delay=function(t,n){return t=pe.fx&&pe.fx.speeds[t]||t,n=n||"fx",this.queue(n,function(n,r){var i=e.setTimeout(n,t);r.stop=function(){e.clearTimeout(i)}})},function(){var e,t=re.createElement("input"),n=re.createElement("div"),r=re.createElement("select"),i=r.appendChild(re.createElement("option"));n=re.createElement("div"),n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",e=n.getElementsByTagName("a")[0],t.setAttribute("type","checkbox"),n.appendChild(t),e=n.getElementsByTagName("a")[0],e.style.cssText="top:1px",de.getSetAttribute="t"!==n.className,de.style=/top/.test(e.getAttribute("style")),de.hrefNormalized="/a"===e.getAttribute("href"),de.checkOn=!!t.value,de.optSelected=i.selected,de.enctype=!!re.createElement("form").enctype,r.disabled=!0,de.optDisabled=!i.disabled,t=re.createElement("input"),t.setAttribute("value",""),de.input=""===t.getAttribute("value"),t.value="t",t.setAttribute("type","radio"),de.radioValue="t"===t.value}();var Dt=/\r/g,jt=/[\x20\t\r\n\f]+/g;pe.fn.extend({val:function(e){var t,n,r,i=this[0];return arguments.length?(r=pe.isFunction(e),this.each(function(n){var i;1===this.nodeType&&(i=r?e.call(this,n,pe(this).val()):e,null==i?i="":"number"==typeof i?i+="":pe.isArray(i)&&(i=pe.map(i,function(e){return null==e?"":e+""})),t=pe.valHooks[this.type]||pe.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))})):i?(t=pe.valHooks[i.type]||pe.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:(n=i.value,"string"==typeof n?n.replace(Dt,""):null==n?"":n)):void 0}}),pe.extend({valHooks:{option:{get:function(e){var t=pe.find.attr(e,"value");return null!=t?t:pe.trim(pe.text(e)).replace(jt," ")}},select:{get:function(e){for(var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;s>u;u++)if(n=r[u],(n.selected||u===i)&&(de.optDisabled?!n.disabled:null===n.getAttribute("disabled"))&&(!n.parentNode.disabled||!pe.nodeName(n.parentNode,"optgroup"))){if(t=pe(n).val(),o)return t;a.push(t)}return a},set:function(e,t){for(var n,r,i=e.options,o=pe.makeArray(t),a=i.length;a--;)if(r=i[a],pe.inArray(pe.valHooks.option.get(r),o)>-1)try{r.selected=n=!0}catch(e){r.scrollHeight}else r.selected=!1;return n||(e.selectedIndex=-1),i}}}}),pe.each(["radio","checkbox"],function(){pe.valHooks[this]={set:function(e,t){return pe.isArray(t)?e.checked=pe.inArray(pe(e).val(),t)>-1:void 0}},de.checkOn||(pe.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Lt,Ht,qt=pe.expr.attrHandle,_t=/^(?:checked|selected)$/i,Ft=de.getSetAttribute,Mt=de.input;pe.fn.extend({attr:function(e,t){return Pe(this,pe.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){pe.removeAttr(this,e)})}}),pe.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return void 0===e.getAttribute?pe.prop(e,t,n):(1===o&&pe.isXMLDoc(e)||(t=t.toLowerCase(),i=pe.attrHooks[t]||(pe.expr.match.bool.test(t)?Ht:Lt)),void 0!==n?null===n?void pe.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:(r=pe.find.attr(e,t),null==r?void 0:r))},attrHooks:{type:{set:function(e,t){if(!de.radioValue&&"radio"===t&&pe.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(Le);if(o&&1===e.nodeType)for(;n=o[i++];)r=pe.propFix[n]||n,pe.expr.match.bool.test(n)?Mt&&Ft||!_t.test(n)?e[r]=!1:e[pe.camelCase("default-"+n)]=e[r]=!1:pe.attr(e,n,""),e.removeAttribute(Ft?n:r)}}),Ht={set:function(e,t,n){return!1===t?pe.removeAttr(e,n):Mt&&Ft||!_t.test(n)?e.setAttribute(!Ft&&pe.propFix[n]||n,n):e[pe.camelCase("default-"+n)]=e[n]=!0,n}},pe.each(pe.expr.match.bool.source.match(/\w+/g),function(e,t){var n=qt[t]||pe.find.attr;Mt&&Ft||!_t.test(t)?qt[t]=function(e,t,r){var i,o;return r||(o=qt[t],qt[t]=i,i=null!=n(e,t,r)?t.toLowerCase():null,qt[t]=o),i}:qt[t]=function(e,t,n){return n?void 0:e[pe.camelCase("default-"+t)]?t.toLowerCase():null}}),Mt&&Ft||(pe.attrHooks.value={set:function(e,t,n){return pe.nodeName(e,"input")?void(e.defaultValue=t):Lt&&Lt.set(e,t,n)}}),Ft||(Lt={set:function(e,t,n){var r=e.getAttributeNode(n);return r||e.setAttributeNode(r=e.ownerDocument.createAttribute(n)),r.value=t+="","value"===n||t===e.getAttribute(n)?t:void 0}},qt.id=qt.name=qt.coords=function(e,t,n){var r;return n?void 0:(r=e.getAttributeNode(t))&&""!==r.value?r.value:null},pe.valHooks.button={get:function(e,t){var n=e.getAttributeNode(t);return n&&n.specified?n.value:void 0},set:Lt.set},pe.attrHooks.contenteditable={set:function(e,t,n){Lt.set(e,""!==t&&t,n)}},pe.each(["width","height"],function(e,t){pe.attrHooks[t]={set:function(e,n){return""===n?(e.setAttribute(t,"auto"),n):void 0}}})),de.style||(pe.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var Ot=/^(?:input|select|textarea|button|object)$/i,Rt=/^(?:a|area)$/i;pe.fn.extend({prop:function(e,t){return Pe(this,pe.prop,e,t,arguments.length>1)},removeProp:function(e){return e=pe.propFix[e]||e,this.each(function(){try{this[e]=void 0,delete this[e]}catch(e){}})}}),pe.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&pe.isXMLDoc(e)||(t=pe.propFix[t]||t,i=pe.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=pe.find.attr(e,"tabindex");return t?parseInt(t,10):Ot.test(e.nodeName)||Rt.test(e.nodeName)&&e.href?0:-1}}},propFix:{for:"htmlFor",class:"className"}}),de.hrefNormalized||pe.each(["href","src"],function(e,t){pe.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),de.optSelected||(pe.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),pe.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){pe.propFix[this.toLowerCase()]=this}),de.enctype||(pe.propFix.enctype="encoding");var Pt=/[\t\r\n\f]/g;pe.fn.extend({addClass:function(e){var t,n,r,i,o,a,s,u=0;if(pe.isFunction(e))return this.each(function(t){pe(this).addClass(e.call(this,t,z(this)))});if("string"==typeof e&&e)for(t=e.match(Le)||[];n=this[u++];)if(i=z(n),r=1===n.nodeType&&(" "+i+" ").replace(Pt," ")){for(a=0;o=t[a++];)r.indexOf(" "+o+" ")<0&&(r+=o+" ");s=pe.trim(r),i!==s&&pe.attr(n,"class",s)}return this},removeClass:function(e){var t,n,r,i,o,a,s,u=0;if(pe.isFunction(e))return this.each(function(t){pe(this).removeClass(e.call(this,t,z(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof e&&e)for(t=e.match(Le)||[];n=this[u++];)if(i=z(n),r=1===n.nodeType&&(" "+i+" ").replace(Pt," ")){for(a=0;o=t[a++];)for(;r.indexOf(" "+o+" ")>-1;)r=r.replace(" "+o+" "," ");s=pe.trim(r),i!==s&&pe.attr(n,"class",s)}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):pe.isFunction(e)?this.each(function(n){pe(this).toggleClass(e.call(this,n,z(this),t),t)}):this.each(function(){var t,r,i,o;if("string"===n)for(r=0,i=pe(this),o=e.match(Le)||[];t=o[r++];)i.hasClass(t)?i.removeClass(t):i.addClass(t);else void 0!==e&&"boolean"!==n||(t=z(this),t&&pe._data(this,"__className__",t),pe.attr(this,"class",t||!1===e?"":pe._data(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;for(t=" "+e+" ";n=this[r++];)if(1===n.nodeType&&(" "+z(n)+" ").replace(Pt," ").indexOf(t)>-1)return!0;return!1}}),pe.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(e,t){pe.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),pe.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}});var Bt=e.location,Wt=pe.now(),It=/\?/,$t=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;pe.parseJSON=function(t){if(e.JSON&&e.JSON.parse)return e.JSON.parse(t+"");var n,r=null,i=pe.trim(t+"");return i&&!pe.trim(i.replace($t,function(e,t,i,o){return n&&t&&(r=0),0===r?e:(n=i||t,r+=!o-!i,"")}))?Function("return "+i)():pe.error("Invalid JSON: "+t)},pe.parseXML=function(t){var n,r;if(!t||"string"!=typeof t)return null;try{e.DOMParser?(r=new e.DOMParser,n=r.parseFromString(t,"text/xml")):(n=new e.ActiveXObject("Microsoft.XMLDOM"),n.async="false",n.loadXML(t))}catch(e){n=void 0}return n&&n.documentElement&&!n.getElementsByTagName("parsererror").length||pe.error("Invalid XML: "+t),n};var zt=/#.*$/,Xt=/([?&])_=[^&]*/,Ut=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Vt=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Yt=/^(?:GET|HEAD)$/,Jt=/^\/\//,Gt=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Qt={},Kt={},Zt="*/".concat("*"),en=Bt.href,tn=Gt.exec(en.toLowerCase())||[];pe.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:en,type:"GET",isLocal:Vt.test(tn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Zt,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":pe.parseJSON,"text xml":pe.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?V(V(e,pe.ajaxSettings),t):V(pe.ajaxSettings,e)},ajaxPrefilter:X(Qt),ajaxTransport:X(Kt),ajax:function(t,n){function r(t,n,r,i){var o,d,y,x,w,C=n;2!==b&&(b=2,u&&e.clearTimeout(u),c=void 0,s=i||"",T.readyState=t>0?4:0,o=t>=200&&300>t||304===t,r&&(x=Y(f,T,r)),x=J(f,x,T,o),o?(f.ifModified&&(w=T.getResponseHeader("Last-Modified"),w&&(pe.lastModified[a]=w),w=T.getResponseHeader("etag"),w&&(pe.etag[a]=w)),204===t||"HEAD"===f.type?C="nocontent":304===t?C="notmodified":(C=x.state,d=x.data,y=x.error,o=!y)):(y=C,!t&&C||(C="error",0>t&&(t=0))),T.status=t,T.statusText=(n||C)+"",o?g.resolveWith(p,[d,C,T]):g.rejectWith(p,[T,C,y]),T.statusCode(v),v=void 0,l&&h.trigger(o?"ajaxSuccess":"ajaxError",[T,f,o?d:y]),m.fireWith(p,[T,C]),l&&(h.trigger("ajaxComplete",[T,f]),--pe.active||pe.event.trigger("ajaxStop")))}"object"==typeof t&&(n=t,t=void 0),n=n||{};var i,o,a,s,u,l,c,d,f=pe.ajaxSetup({},n),p=f.context||f,h=f.context&&(p.nodeType||p.jquery)?pe(p):pe.event,g=pe.Deferred(),m=pe.Callbacks("once memory"),v=f.statusCode||{},y={},x={},b=0,w="canceled",T={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!d)for(d={};t=Ut.exec(s);)d[t[1].toLowerCase()]=t[2];t=d[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?s:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=x[n]=x[n]||e,y[e]=t),this},overrideMimeType:function(e){return b||(f.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)v[t]=[v[t],e[t]];else T.always(e[T.status]);return this},abort:function(e){var t=e||w;return c&&c.abort(t),r(0,t),this}};if(g.promise(T).complete=m.add,T.success=T.done,T.error=T.fail,f.url=((t||f.url||en)+"").replace(zt,"").replace(Jt,tn[1]+"//"),f.type=n.method||n.type||f.method||f.type,f.dataTypes=pe.trim(f.dataType||"*").toLowerCase().match(Le)||[""],null==f.crossDomain&&(i=Gt.exec(f.url.toLowerCase()),f.crossDomain=!(!i||i[1]===tn[1]&&i[2]===tn[2]&&(i[3]||("http:"===i[1]?"80":"443"))===(tn[3]||("http:"===tn[1]?"80":"443")))),f.data&&f.processData&&"string"!=typeof f.data&&(f.data=pe.param(f.data,f.traditional)),U(Qt,f,n,T),2===b)return T;for(o in l=pe.event&&f.global,l&&0==pe.active++&&pe.event.trigger("ajaxStart"),f.type=f.type.toUpperCase(),f.hasContent=!Yt.test(f.type),a=f.url,f.hasContent||(f.data&&(a=f.url+=(It.test(a)?"&":"?")+f.data,delete f.data),!1===f.cache&&(f.url=Xt.test(a)?a.replace(Xt,"$1_="+Wt++):a+(It.test(a)?"&":"?")+"_="+Wt++)),f.ifModified&&(pe.lastModified[a]&&T.setRequestHeader("If-Modified-Since",pe.lastModified[a]),pe.etag[a]&&T.setRequestHeader("If-None-Match",pe.etag[a])),(f.data&&f.hasContent&&!1!==f.contentType||n.contentType)&&T.setRequestHeader("Content-Type",f.contentType),T.setRequestHeader("Accept",f.dataTypes[0]&&f.accepts[f.dataTypes[0]]?f.accepts[f.dataTypes[0]]+("*"!==f.dataTypes[0]?", "+Zt+"; q=0.01":""):f.accepts["*"]),f.headers)T.setRequestHeader(o,f.headers[o]);if(f.beforeSend&&(!1===f.beforeSend.call(p,T,f)||2===b))return T.abort();for(o in w="abort",{success:1,error:1,complete:1})T[o](f[o]);if(c=U(Kt,f,n,T)){if(T.readyState=1,l&&h.trigger("ajaxSend",[T,f]),2===b)return T;f.async&&f.timeout>0&&(u=e.setTimeout(function(){T.abort("timeout")},f.timeout));try{b=1,c.send(y,r)}catch(e){if(!(2>b))throw e;r(-1,e)}}else r(-1,"No Transport");return T},getJSON:function(e,t,n){return pe.get(e,t,n,"json")},getScript:function(e,t){return pe.get(e,void 0,t,"script")}}),pe.each(["get","post"],function(e,t){pe[t]=function(e,n,r,i){return pe.isFunction(n)&&(i=i||r,r=n,n=void 0),pe.ajax(pe.extend({url:e,type:t,dataType:i,data:n,success:r},pe.isPlainObject(e)&&e))}}),pe._evalUrl=function(e){return pe.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,throws:!0})},pe.fn.extend({wrapAll:function(e){if(pe.isFunction(e))return this.each(function(t){pe(this).wrapAll(e.call(this,t))});if(this[0]){var t=pe(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return pe.isFunction(e)?this.each(function(t){pe(this).wrapInner(e.call(this,t))}):this.each(function(){var t=pe(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=pe.isFunction(e);return this.each(function(n){pe(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){pe.nodeName(this,"body")||pe(this).replaceWith(this.childNodes)}).end()}}),pe.expr.filters.hidden=function(e){return de.reliableHiddenOffsets()?e.offsetWidth<=0&&e.offsetHeight<=0&&!e.getClientRects().length:Q(e)},pe.expr.filters.visible=function(e){return!pe.expr.filters.hidden(e)};var nn=/%20/g,rn=/\[\]$/,on=/\r?\n/g,an=/^(?:submit|button|image|reset|file)$/i,sn=/^(?:input|select|textarea|keygen)/i;pe.param=function(e,t){var n,r=[],i=function(e,t){t=pe.isFunction(t)?t():null==t?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(void 0===t&&(t=pe.ajaxSettings&&pe.ajaxSettings.traditional),pe.isArray(e)||e.jquery&&!pe.isPlainObject(e))pe.each(e,function(){i(this.name,this.value)});else for(n in e)K(n,e[n],t,i);return r.join("&").replace(nn,"+")},pe.fn.extend({serialize:function(){return pe.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=pe.prop(this,"elements");return e?pe.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!pe(this).is(":disabled")&&sn.test(this.nodeName)&&!an.test(e)&&(this.checked||!Be.test(e))}).map(function(e,t){var n=pe(this).val();return null==n?null:pe.isArray(n)?pe.map(n,function(e){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),pe.ajaxSettings.xhr=void 0!==e.ActiveXObject?function(){return this.isLocal?ee():re.documentMode>8?Z():/^(get|post|head|put|delete|options)$/i.test(this.type)&&Z()||ee()}:Z;var un=0,ln={},cn=pe.ajaxSettings.xhr();e.attachEvent&&e.attachEvent("onunload",function(){for(var e in ln)ln[e](void 0,!0)}),de.cors=!!cn&&"withCredentials"in cn,cn=de.ajax=!!cn,cn&&pe.ajaxTransport(function(t){var n;if(!t.crossDomain||de.cors)return{send:function(r,i){var o,a=t.xhr(),s=++un;if(a.open(t.type,t.url,t.async,t.username,t.password),t.xhrFields)for(o in t.xhrFields)a[o]=t.xhrFields[o];for(o in t.mimeType&&a.overrideMimeType&&a.overrideMimeType(t.mimeType),t.crossDomain||r["X-Requested-With"]||(r["X-Requested-With"]="XMLHttpRequest"),r)void 0!==r[o]&&a.setRequestHeader(o,r[o]+"");a.send(t.hasContent&&t.data||null),n=function(e,r){var o,u,l;if(n&&(r||4===a.readyState))if(delete ln[s],n=void 0,a.onreadystatechange=pe.noop,r)4!==a.readyState&&a.abort();else{l={},o=a.status,"string"==typeof a.responseText&&(l.text=a.responseText);try{u=a.statusText}catch(e){u=""}o||!t.isLocal||t.crossDomain?1223===o&&(o=204):o=l.text?200:404}l&&i(o,u,l,a.getAllResponseHeaders())},t.async?4===a.readyState?e.setTimeout(n):a.onreadystatechange=ln[s]=n:n()},abort:function(){n&&n(void 0,!0)}}}),pe.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return pe.globalEval(e),e}}}),pe.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),pe.ajaxTransport("script",function(e){if(e.crossDomain){var t,n=re.head||pe("head")[0]||re.documentElement;return{send:function(r,i){t=re.createElement("script"),t.async=!0,e.scriptCharset&&(t.charset=e.scriptCharset),t.src=e.url,t.onload=t.onreadystatechange=function(e,n){(n||!t.readyState||/loaded|complete/.test(t.readyState))&&(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),t=null,n||i(200,"success"))},n.insertBefore(t,n.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var dn=[],fn=/(=)\?(?=&|$)|\?\?/;pe.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=dn.pop()||pe.expando+"_"+Wt++;return this[e]=!0,e}}),pe.ajaxPrefilter("json jsonp",function(t,n,r){var i,o,a,s=!1!==t.jsonp&&(fn.test(t.url)?"url":"string"==typeof t.data&&0===(t.contentType||"").indexOf("application/x-www-form-urlencoded")&&fn.test(t.data)&&"data");return s||"jsonp"===t.dataTypes[0]?(i=t.jsonpCallback=pe.isFunction(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback,s?t[s]=t[s].replace(fn,"$1"+i):!1!==t.jsonp&&(t.url+=(It.test(t.url)?"&":"?")+t.jsonp+"="+i),t.converters["script json"]=function(){return a||pe.error(i+" was not called"),a[0]},t.dataTypes[0]="json",o=e[i],e[i]=function(){a=arguments},r.always(function(){void 0===o?pe(e).removeProp(i):e[i]=o,t[i]&&(t.jsonpCallback=n.jsonpCallback,dn.push(i)),a&&pe.isFunction(o)&&o(a[0]),a=o=void 0}),"script"):void 0}),pe.parseHTML=function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||re;var r=Te.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=v([e],t,i),i&&i.length&&pe(i).remove(),pe.merge([],r.childNodes))};var pn=pe.fn.load;pe.fn.load=function(e,t,n){if("string"!=typeof e&&pn)return pn.apply(this,arguments);var r,i,o,a=this,s=e.indexOf(" ");return s>-1&&(r=pe.trim(e.slice(s,e.length)),e=e.slice(0,s)),pe.isFunction(t)?(n=t,t=void 0):t&&"object"==typeof t&&(i="POST"),a.length>0&&pe.ajax({url:e,type:i||"GET",dataType:"html",data:t}).done(function(e){o=arguments,a.html(r?pe("<div>").append(pe.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},pe.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){pe.fn[t]=function(e){return this.on(t,e)}}),pe.expr.filters.animated=function(e){return pe.grep(pe.timers,function(t){return e===t.elem}).length},pe.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l,c=pe.css(e,"position"),d=pe(e),f={};"static"===c&&(e.style.position="relative"),s=d.offset(),o=pe.css(e,"top"),u=pe.css(e,"left"),l=("absolute"===c||"fixed"===c)&&pe.inArray("auto",[o,u])>-1,l?(r=d.position(),a=r.top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),pe.isFunction(t)&&(t=t.call(e,n,pe.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):d.css(f)}},pe.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){pe.offset.setOffset(this,e,t)});var t,n,r={top:0,left:0},i=this[0],o=i&&i.ownerDocument;return o?(t=o.documentElement,pe.contains(t,i)?(void 0!==i.getBoundingClientRect&&(r=i.getBoundingClientRect()),n=te(o),{top:r.top+(n.pageYOffset||t.scrollTop)-(t.clientTop||0),left:r.left+(n.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}):r):void 0},position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===pe.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),pe.nodeName(e[0],"html")||(n=e.offset()),n.top+=pe.css(e[0],"borderTopWidth",!0),n.left+=pe.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-pe.css(r,"marginTop",!0),left:t.left-n.left-pe.css(r,"marginLeft",!0)}}},offsetParent:function(){ return this.map(function(){for(var e=this.offsetParent;e&&!pe.nodeName(e,"html")&&"static"===pe.css(e,"position");)e=e.offsetParent;return e||pt})}}),pe.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n=/Y/.test(t);pe.fn[e]=function(r){return Pe(this,function(e,r,i){var o=te(e);return void 0===i?o?t in o?o[t]:o.document.documentElement[r]:e[r]:void(o?o.scrollTo(n?pe(o).scrollLeft():i,n?i:pe(o).scrollTop()):e[r]=i)},e,r,arguments.length,null)}}),pe.each(["top","left"],function(e,t){pe.cssHooks[t]=L(de.pixelPosition,function(e,n){return n?(n=gt(e,t),dt.test(n)?pe(e).position()[t]+"px":n):void 0})}),pe.each({Height:"height",Width:"width"},function(e,t){pe.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){pe.fn[r]=function(r,i){var o=arguments.length&&(n||"boolean"!=typeof r),a=n||(!0===r||!0===i?"margin":"border");return Pe(this,function(t,n,r){var i;return pe.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(i=t.documentElement,Math.max(t.body["scroll"+e],i["scroll"+e],t.body["offset"+e],i["offset"+e],i["client"+e])):void 0===r?pe.css(t,n,a):pe.style(t,n,r,a)},t,o?r:void 0,o,null)}})}),pe.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}}),pe.fn.size=function(){return this.length},pe.fn.andSelf=pe.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return pe});var hn=e.jQuery,gn=e.$;return pe.noConflict=function(t){return e.$===pe&&(e.$=gn),t&&e.jQuery===pe&&(e.jQuery=hn),pe},t||(e.jQuery=e.$=pe),pe});
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _SVG = require('./SVG'); var _SVG2 = _interopRequireDefault(_SVG); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var MdOpen = function MdOpen(props) { return _react2.default.createElement( _SVG2.default, { style: props.style, className: props.className, fill: props.color, width: props.fontSize, height: props.fontSize, viewBox: '0 0 1024 1024', onClick: props.onClick, rotate: props.rotate ? 1 : 0, shake: props.shake ? 1 : 0, beat: props.beat ? 1 : 0 }, _react2.default.createElement('path', { d: 'M810.68 810.664h-597.36v-597.328h266.68v-85.336h-266.68c-46.938 0-85.32 38.394-85.32 85.336v597.328c0 46.942 38.382 85.336 85.32 85.336h597.36c46.938 0 85.32-38.394 85.32-85.336v-266.664h-85.32v266.664zM576 128v85.336h174.948l-430.95 430.93 59.732 59.732 430.952-430.94v174.942h85.318v-320h-320z' }) ); }; MdOpen.defaultProps = { // style style: {}, color: '#000000', fontSize: '22px', // animation shake: false, beat: false, rotate: false }; MdOpen.propTypes = { // style style: _propTypes2.default.object, color: _propTypes2.default.string, fontSize: _propTypes2.default.string, // animation shake: _propTypes2.default.bool, beat: _propTypes2.default.bool, rotate: _propTypes2.default.bool, // functions onClick: _propTypes2.default.func }; exports.default = MdOpen; module.exports = exports['default']; //# sourceMappingURL=MdOpen.js.map
/* eslint-disable */ // rename this file from _test_[name] to test_[name] to activate // and remove above this line QUnit.test("test: Court Record Check", function (assert) { let done = assert.async(); // number of asserts assert.expect(1); frappe.run_serially([ // insert a new Court Record Check () => frappe.tests.make('Court Record Check', [ // values to be set {key: 'value'} ]), () => { assert.equal(cur_frm.doc.key, 'value'); }, () => done() ]); });
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("pdfjs-dist/build/pdf",[],e):"object"==typeof exports?exports["pdfjs-dist/build/pdf"]=e():t["pdfjs-dist/build/pdf"]=t.pdfjsDistBuildPdf=e()}(this,function(){return function(t){function e(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,e),i.l=!0,i.exports}var n={};return e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,n,r){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:r})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=13)}([function(t,e,n){"use strict";(function(t){function r(t){nt=t}function i(){return nt}function a(t){nt>=$.infos&&console.log("Info: "+t)}function s(t){nt>=$.warnings&&console.log("Warning: "+t)}function o(t){console.log("Deprecated API usage: "+t)}function c(t){throw nt>=$.errors&&(console.log("Error: "+t),console.log(l())),new Error(t)}function l(){try{throw new Error}catch(t){return t.stack?t.stack.split("\n").slice(2).join("\n"):""}}function h(t,e){t||c(e)}function u(t,e){try{var n=new URL(t);if(!n.origin||"null"===n.origin)return!1}catch(t){return!1}var r=new URL(e,n);return n.origin===r.origin}function d(t){if(!t)return!1;switch(t.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function f(t,e){if(!t)return null;try{var n=e?new URL(t,e):new URL(t);if(d(n))return n}catch(t){}return null}function p(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!1}),n}function g(t){var e;return function(){return t&&(e=Object.create(null),t(e),t=null),e}}function m(t){return"string"!=typeof t?(s("The argument for removeNullCharacters must be a string."),t):t.replace(ft,"")}function A(t){h(null!==t&&"object"==typeof t&&void 0!==t.length,"Invalid argument for bytesToString");var e=t.length;if(e<8192)return String.fromCharCode.apply(null,t);for(var n=[],r=0;r<e;r+=8192){var i=Math.min(r+8192,e),a=t.subarray(r,i);n.push(String.fromCharCode.apply(null,a))}return n.join("")}function v(t){h("string"==typeof t,"Invalid argument for stringToBytes");for(var e=t.length,n=new Uint8Array(e),r=0;r<e;++r)n[r]=255&t.charCodeAt(r);return n}function b(t){return void 0!==t.length?t.length:(h(void 0!==t.byteLength),t.byteLength)}function y(t){if(1===t.length&&t[0]instanceof Uint8Array)return t[0];var e,n,r,i=0,a=t.length;for(e=0;e<a;e++)n=t[e],r=b(n),i+=r;var s=0,o=new Uint8Array(i);for(e=0;e<a;e++)n=t[e],n instanceof Uint8Array||(n="string"==typeof n?v(n):new Uint8Array(n)),r=n.byteLength,o.set(n,s),s+=r;return o}function x(t){return String.fromCharCode(t>>24&255,t>>16&255,t>>8&255,255&t)}function S(t){for(var e=1,n=0;t>e;)e<<=1,n++;return n}function w(t,e){return t[e]<<24>>24}function k(t,e){return t[e]<<8|t[e+1]}function C(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}function _(){var t=new Uint8Array(2);return t[0]=1,1===new Uint16Array(t.buffer)[0]}function T(){try{return new Function(""),!0}catch(t){return!1}}function P(t){var e,n=t.length,r=[];if("þ"===t[0]&&"ÿ"===t[1])for(e=2;e<n;e+=2)r.push(String.fromCharCode(t.charCodeAt(e)<<8|t.charCodeAt(e+1)));else for(e=0;e<n;++e){var i=vt[t.charCodeAt(e)];r.push(i?String.fromCharCode(i):t.charAt(e))}return r.join("")}function L(t){return decodeURIComponent(escape(t))}function E(t){return unescape(encodeURIComponent(t))}function R(t){for(var e in t)return!1;return!0}function I(t){return"boolean"==typeof t}function F(t){return"number"==typeof t&&(0|t)===t}function O(t){return"number"==typeof t}function N(t){return"string"==typeof t}function M(t){return t instanceof Array}function D(t){return"object"==typeof t&&null!==t&&void 0!==t.byteLength}function j(t){return 32===t||9===t||13===t||10===t}function U(){return"undefined"==typeof __pdfjsdev_webpack__&&("object"==typeof process&&process+""=="[object process]")}function B(){var t={};return t.promise=new Promise(function(e,n){t.resolve=e,t.reject=n}),t}function W(t,e,n){this.sourceName=t,this.targetName=e,this.comObj=n,this.callbackIndex=1,this.postMessageTransfers=!0;var r=this.callbacksCapabilities=Object.create(null),i=this.actionHandler=Object.create(null);this._onComObjOnMessage=function(t){var e=t.data;if(e.targetName===this.sourceName)if(e.isReply){var a=e.callbackId;if(e.callbackId in r){var s=r[a];delete r[a],"error"in e?s.reject(e.error):s.resolve(e.data)}else c("Cannot resolve callback "+a)}else if(e.action in i){var o=i[e.action];if(e.callbackId){var l=this.sourceName,h=e.sourceName;Promise.resolve().then(function(){return o[0].call(o[1],e.data)}).then(function(t){n.postMessage({sourceName:l,targetName:h,isReply:!0,callbackId:e.callbackId,data:t})},function(t){t instanceof Error&&(t+=""),n.postMessage({sourceName:l,targetName:h,isReply:!0,callbackId:e.callbackId,error:t})})}else o[0].call(o[1],e.data)}else c("Unknown action from worker: "+e.action)}.bind(this),n.addEventListener("message",this._onComObjOnMessage)}function G(t,e,n){var r=new Image;r.onload=function(){n.resolve(t,r)},r.onerror=function(){n.resolve(t,null),s("Error during JPEG image loading")},r.src=e}var X=(n(14),"undefined"!=typeof window?window:void 0!==t?t:"undefined"!=typeof self?self:void 0),H=[.001,0,0,.001,0,0],z={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},Y={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},q={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},V={INVISIBLE:1,HIDDEN:2,PRINT:4,NOZOOM:8,NOROTATE:16,NOVIEW:32,READONLY:64,LOCKED:128,TOGGLENOVIEW:256,LOCKEDCONTENTS:512},J={READONLY:1,REQUIRED:2,NOEXPORT:4,MULTILINE:4096,PASSWORD:8192,NOTOGGLETOOFF:16384,RADIO:32768,PUSHBUTTON:65536,COMBO:131072,EDIT:262144,SORT:524288,FILESELECT:1048576,MULTISELECT:2097152,DONOTSPELLCHECK:4194304,DONOTSCROLL:8388608,COMB:16777216,RICHTEXT:33554432,RADIOSINUNISON:33554432,COMMITONSELCHANGE:67108864},Q={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},K={UNKNOWN:0,FLATE:1,LZW:2,DCT:3,JPX:4,JBIG:5,A85:6,AHX:7,CCF:8,RL:9},Z={UNKNOWN:0,TYPE1:1,TYPE1C:2,CIDFONTTYPE0:3,CIDFONTTYPE0C:4,TRUETYPE:5,CIDFONTTYPE2:6,TYPE3:7,OPENTYPE:8,TYPE0:9,MMTYPE1:10},$={errors:0,warnings:1,infos:5},tt={NONE:0,BINARY:1,STREAM:2},et={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotations:78,endAnnotations:79,beginAnnotation:80,endAnnotation:81,paintJpegXObject:82,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91},nt=$.warnings,rt={unknown:"unknown",forms:"forms",javaScript:"javaScript",smask:"smask",shadingPattern:"shadingPattern",font:"font"},it={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},at=function(){function t(t,e){this.name="PasswordException",this.message=t,this.code=e}return t.prototype=new Error,t.constructor=t,t}(),st=function(){function t(t,e){this.name="UnknownErrorException",this.message=t,this.details=e}return t.prototype=new Error,t.constructor=t,t}(),ot=function(){function t(t){this.name="InvalidPDFException",this.message=t}return t.prototype=new Error,t.constructor=t,t}(),ct=function(){function t(t){this.name="MissingPDFException",this.message=t}return t.prototype=new Error,t.constructor=t,t}(),lt=function(){function t(t,e){this.name="UnexpectedResponseException",this.message=t,this.status=e}return t.prototype=new Error,t.constructor=t,t}(),ht=function(){function t(t){this.message=t}return t.prototype=new Error,t.prototype.name="NotImplementedException",t.constructor=t,t}(),ut=function(){function t(t,e){this.begin=t,this.end=e,this.message="Missing data ["+t+", "+e+")"}return t.prototype=new Error,t.prototype.name="MissingDataException",t.constructor=t,t}(),dt=function(){function t(t){this.message=t}return t.prototype=new Error,t.prototype.name="XRefParseException",t.constructor=t,t}(),ft=/\x00/g,pt=function(){function t(t,e){this.buffer=t,this.byteLength=t.length,this.length=void 0===e?this.byteLength>>2:e,n(this.length)}function e(t){return{get:function(){var e=this.buffer,n=t<<2;return(e[n]|e[n+1]<<8|e[n+2]<<16|e[n+3]<<24)>>>0},set:function(e){var n=this.buffer,r=t<<2;n[r]=255&e,n[r+1]=e>>8&255,n[r+2]=e>>16&255,n[r+3]=e>>>24&255}}}function n(n){for(;r<n;)Object.defineProperty(t.prototype,r,e(r)),r++}t.prototype=Object.create(null);var r=0;return t}();e.Uint32ArrayView=pt;var gt=[1,0,0,1,0,0],mt=function(){function t(){}var e=["rgb(",0,",",0,",",0,")"];t.makeCssRgb=function(t,n,r){return e[1]=t,e[3]=n,e[5]=r,e.join("")},t.transform=function(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]},t.applyTransform=function(t,e){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]},t.applyInverseTransform=function(t,e){var n=e[0]*e[3]-e[1]*e[2];return[(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/n,(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/n]},t.getAxialAlignedBoundingBox=function(e,n){var r=t.applyTransform(e,n),i=t.applyTransform(e.slice(2,4),n),a=t.applyTransform([e[0],e[3]],n),s=t.applyTransform([e[2],e[1]],n);return[Math.min(r[0],i[0],a[0],s[0]),Math.min(r[1],i[1],a[1],s[1]),Math.max(r[0],i[0],a[0],s[0]),Math.max(r[1],i[1],a[1],s[1])]},t.inverseTransform=function(t){var e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]},t.apply3dTransform=function(t,e){return[t[0]*e[0]+t[1]*e[1]+t[2]*e[2],t[3]*e[0]+t[4]*e[1]+t[5]*e[2],t[6]*e[0]+t[7]*e[1]+t[8]*e[2]]},t.singularValueDecompose2dScale=function(t){var e=[t[0],t[2],t[1],t[3]],n=t[0]*e[0]+t[1]*e[2],r=t[0]*e[1]+t[1]*e[3],i=t[2]*e[0]+t[3]*e[2],a=t[2]*e[1]+t[3]*e[3],s=(n+a)/2,o=Math.sqrt((n+a)*(n+a)-4*(n*a-i*r))/2,c=s+o||1,l=s-o||1;return[Math.sqrt(c),Math.sqrt(l)]},t.normalizeRect=function(t){var e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e},t.intersect=function(e,n){function r(t,e){return t-e}var i=[e[0],e[2],n[0],n[2]].sort(r),a=[e[1],e[3],n[1],n[3]].sort(r),s=[];return e=t.normalizeRect(e),n=t.normalizeRect(n),(i[0]===e[0]&&i[1]===n[0]||i[0]===n[0]&&i[1]===e[0])&&(s[0]=i[1],s[2]=i[2],(a[0]===e[1]&&a[1]===n[1]||a[0]===n[1]&&a[1]===e[1])&&(s[1]=a[1],s[3]=a[2],s))},t.sign=function(t){return t<0?-1:1};var n=["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM","","X","XX","XXX","XL","L","LX","LXX","LXXX","XC","","I","II","III","IV","V","VI","VII","VIII","IX"];return t.toRoman=function(t,e){h(F(t)&&t>0,"The number should be a positive integer.");for(var r,i=[];t>=1e3;)t-=1e3,i.push("M");r=t/100|0,t%=100,i.push(n[r]),r=t/10|0,t%=10,i.push(n[10+r]),i.push(n[20+t]);var a=i.join("");return e?a.toLowerCase():a},t.appendToArray=function(t,e){Array.prototype.push.apply(t,e)},t.prependToArray=function(t,e){Array.prototype.unshift.apply(t,e)},t.extendObj=function(t,e){for(var n in e)t[n]=e[n]},t.getInheritableProperty=function(t,e,n){for(;t&&!t.has(e);)t=t.get("Parent");return t?n?t.getArray(e):t.get(e):null},t.inherit=function(t,e,n){t.prototype=Object.create(e.prototype),t.prototype.constructor=t;for(var r in n)t.prototype[r]=n[r]},t.loadScript=function(t,e){var n=document.createElement("script"),r=!1;n.setAttribute("src",t),e&&(n.onload=function(){r||e(),r=!0}),document.getElementsByTagName("head")[0].appendChild(n)},t}(),At=function(){function t(t,e,n,r,i,a){this.viewBox=t,this.scale=e,this.rotation=n,this.offsetX=r,this.offsetY=i;var s,o,c,l,h=(t[2]+t[0])/2,u=(t[3]+t[1])/2;switch(n%=360,n=n<0?n+360:n){case 180:s=-1,o=0,c=0,l=1;break;case 90:s=0,o=1,c=1,l=0;break;case 270:s=0,o=-1,c=-1,l=0;break;default:s=1,o=0,c=0,l=-1}a&&(c=-c,l=-l);var d,f,p,g;0===s?(d=Math.abs(u-t[1])*e+r,f=Math.abs(h-t[0])*e+i,p=Math.abs(t[3]-t[1])*e,g=Math.abs(t[2]-t[0])*e):(d=Math.abs(h-t[0])*e+r,f=Math.abs(u-t[1])*e+i,p=Math.abs(t[2]-t[0])*e,g=Math.abs(t[3]-t[1])*e),this.transform=[s*e,o*e,c*e,l*e,d-s*e*h-c*e*u,f-o*e*h-l*e*u],this.width=p,this.height=g,this.fontScale=e}return t.prototype={clone:function(e){e=e||{};var n="scale"in e?e.scale:this.scale,r="rotation"in e?e.rotation:this.rotation;return new t(this.viewBox.slice(),n,r,this.offsetX,this.offsetY,e.dontFlip)},convertToViewportPoint:function(t,e){return mt.applyTransform([t,e],this.transform)},convertToViewportRectangle:function(t){var e=mt.applyTransform([t[0],t[1]],this.transform),n=mt.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],n[0],n[1]]},convertToPdfPoint:function(t,e){return mt.applyInverseTransform([t,e],this.transform)}},t}(),vt=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364],bt=function(){function t(t,e,n){for(;t.length<n;)t+=e;return t}function e(){this.started=Object.create(null),this.times=[],this.enabled=!0}return e.prototype={time:function(t){this.enabled&&(t in this.started&&s("Timer is already running for "+t),this.started[t]=Date.now())},timeEnd:function(t){this.enabled&&(t in this.started||s("Timer has not been started for "+t),this.times.push({name:t,start:this.started[t],end:Date.now()}),delete this.started[t])},toString:function(){var e,n,r=this.times,i="",a=0;for(e=0,n=r.length;e<n;++e){var s=r[e].name;s.length>a&&(a=s.length)}for(e=0,n=r.length;e<n;++e){var o=r[e],c=o.end-o.start;i+=t(o.name," ",a)+" "+c+"ms\n"}return i}},e}(),yt=function(t,e){if("undefined"!=typeof Blob)return new Blob([t],{type:e});s('The "Blob" constructor is not supported.')},xt=function(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";return function(e,n,r){if(!r&&"undefined"!=typeof URL&&URL.createObjectURL){var i=yt(e,n);return URL.createObjectURL(i)}for(var a="data:"+n+";base64,",s=0,o=e.length;s<o;s+=3){var c=255&e[s],l=255&e[s+1],h=255&e[s+2];a+=t[c>>2]+t[(3&c)<<4|l>>4]+t[s+1<o?(15&l)<<2|h>>6:64]+t[s+2<o?63&h:64]}return a}}();W.prototype={on:function(t,e,n){var r=this.actionHandler;r[t]&&c('There is already an actionName called "'+t+'"'),r[t]=[e,n]},send:function(t,e,n){var r={sourceName:this.sourceName,targetName:this.targetName,action:t,data:e};this.postMessage(r,n)},sendWithPromise:function(t,e,n){var r=this.callbackIndex++,i={sourceName:this.sourceName,targetName:this.targetName,action:t,data:e,callbackId:r},a=B();this.callbacksCapabilities[r]=a;try{this.postMessage(i,n)}catch(t){a.reject(t)}return a.promise},postMessage:function(t,e){e&&this.postMessageTransfers?this.comObj.postMessage(t,e):this.comObj.postMessage(t)},destroy:function(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}},e.FONT_IDENTITY_MATRIX=H,e.IDENTITY_MATRIX=gt,e.OPS=et,e.VERBOSITY_LEVELS=$,e.UNSUPPORTED_FEATURES=rt,e.AnnotationBorderStyleType=Q,e.AnnotationFieldFlag=J,e.AnnotationFlag=V,e.AnnotationType=q,e.FontType=Z,e.ImageKind=Y,e.CMapCompressionType=tt,e.InvalidPDFException=ot,e.MessageHandler=W,e.MissingDataException=ut,e.MissingPDFException=ct,e.NotImplementedException=ht,e.PageViewport=At,e.PasswordException=at,e.PasswordResponses=it,e.StatTimer=bt,e.StreamType=K,e.TextRenderingMode=z,e.UnexpectedResponseException=lt,e.UnknownErrorException=st,e.Util=mt,e.XRefParseException=dt,e.arrayByteLength=b,e.arraysToBytes=y,e.assert=h,e.bytesToString=A,e.createBlob=yt,e.createPromiseCapability=B,e.createObjectURL=xt,e.deprecated=o,e.error=c,e.getLookupTableFactory=g,e.getVerbosityLevel=i,e.globalScope=X,e.info=a,e.isArray=M,e.isArrayBuffer=D,e.isBool=I,e.isEmptyObj=R,e.isInt=F,e.isNum=O,e.isString=N,e.isSpace=j,e.isNodeJS=U,e.isSameOrigin=u,e.createValidAbsoluteUrl=f,e.isLittleEndian=_,e.isEvalSupported=T,e.loadJpegStream=G,e.log2=S,e.readInt8=w,e.readUint16=k,e.readUint32=C,e.removeNullCharacters=m,e.setVerbosityLevel=r,e.shadow=p,e.string32=x,e.stringToBytes=v,e.stringToPDFString=P,e.stringToUTF8String=L,e.utf8StringToString=E,e.warn=s}).call(e,n(6))},function(t,e,n){"use strict";function r(){}function i(t,e){var n=e&&e.url;if(t.href=t.title=n?u(n):"",n){var r=e.target;void 0===r&&(r=s("externalLinkTarget")),t.target=w[r];var i=e.rel;void 0===i&&(i=s("externalLinkRel")),t.rel=i}}function a(t){var e=t.indexOf("#"),n=t.indexOf("?"),r=Math.min(e>0?e:t.length,n>0?n:t.length);return t.substring(t.lastIndexOf("/",r)+1,r)}function s(t){var e=l.globalScope.PDFJS;switch(t){case"pdfBug":return!!e&&e.pdfBug;case"disableAutoFetch":return!!e&&e.disableAutoFetch;case"disableStream":return!!e&&e.disableStream;case"disableRange":return!!e&&e.disableRange;case"disableFontFace":return!!e&&e.disableFontFace;case"disableCreateObjectURL":return!!e&&e.disableCreateObjectURL;case"disableWebGL":return!e||e.disableWebGL;case"cMapUrl":return e?e.cMapUrl:null;case"cMapPacked":return!!e&&e.cMapPacked;case"postMessageTransfers":return!e||e.postMessageTransfers;case"workerPort":return e?e.workerPort:null;case"workerSrc":return e?e.workerSrc:null;case"disableWorker":return!!e&&e.disableWorker;case"maxImageSize":return e?e.maxImageSize:-1;case"imageResourcesPath":return e?e.imageResourcesPath:"";case"isEvalSupported":return!e||e.isEvalSupported;case"externalLinkTarget":if(!e)return S.NONE;switch(e.externalLinkTarget){case S.NONE:case S.SELF:case S.BLANK:case S.PARENT:case S.TOP:return e.externalLinkTarget}return d("PDFJS.externalLinkTarget is invalid: "+e.externalLinkTarget),e.externalLinkTarget=S.NONE,S.NONE;case"externalLinkRel":return e?e.externalLinkRel:A;case"enableStats":return!(!e||!e.enableStats);case"pdfjsNext":return!(!e||!e.pdfjsNext);default:throw new Error("Unknown default setting: "+t)}}function o(){switch(s("externalLinkTarget")){case S.NONE:return!1;case S.SELF:case S.BLANK:case S.PARENT:case S.TOP:return!0}}function c(t,e){return f("isValidUrl(), please use createValidAbsoluteUrl() instead."),null!==p(t,e?"http://example.com":null)}var l=n(0),h=l.assert,u=l.removeNullCharacters,d=l.warn,f=l.deprecated,p=l.createValidAbsoluteUrl,g=l.stringToBytes,m=l.CMapCompressionType,A="noopener noreferrer nofollow";r.prototype={create:function(t,e){h(t>0&&e>0,"invalid canvas size");var n=document.createElement("canvas"),r=n.getContext("2d");return n.width=t,n.height=e,{canvas:n,context:r}},reset:function(t,e,n){h(t.canvas,"canvas is not specified"),h(e>0&&n>0,"invalid canvas size"),t.canvas.width=e,t.canvas.height=n},destroy:function(t){h(t.canvas,"canvas is not specified"),t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}};var v,b=function(){function t(t){this.baseUrl=t.baseUrl||null,this.isCompressed=t.isCompressed||!1}return t.prototype={fetch:function(t){var e=t.name;return e?new Promise(function(t,n){var r=this.baseUrl+e+(this.isCompressed?".bcmap":""),i=new XMLHttpRequest;i.open("GET",r,!0),this.isCompressed&&(i.responseType="arraybuffer"),i.onreadystatechange=function(){if(i.readyState===XMLHttpRequest.DONE){if(200===i.status||0===i.status){var e;if(this.isCompressed&&i.response?e=new Uint8Array(i.response):!this.isCompressed&&i.responseText&&(e=g(i.responseText)),e)return void t({cMapData:e,compressionType:this.isCompressed?m.BINARY:m.NONE})}n(new Error("Unable to load "+(this.isCompressed?"binary ":"")+"CMap at: "+r))}}.bind(this),i.send(null)}.bind(this)):Promise.reject(new Error("CMap name must be specified."))}},t}(),y=function(){function t(){}var e=["ms","Moz","Webkit","O"],n=Object.create(null);return t.getProp=function(t,r){if(1===arguments.length&&"string"==typeof n[t])return n[t];r=r||document.documentElement;var i,a,s=r.style;if("string"==typeof s[t])return n[t]=t;a=t.charAt(0).toUpperCase()+t.slice(1);for(var o=0,c=e.length;o<c;o++)if(i=e[o]+a,"string"==typeof s[i])return n[t]=i;return n[t]="undefined"},t.setProp=function(t,e,n){var r=this.getProp(t);"undefined"!==r&&(e.style[r]=n)},t}(),x=function(){function t(t,e){this.message=t,this.type=e}return t.prototype=new Error,t.prototype.name="RenderingCancelledException",t.constructor=t,t}();v=function(){var t=document.createElement("canvas");return t.width=t.height=1,void 0!==t.getContext("2d").createImageData(1,1).data.buffer};var S={NONE:0,SELF:1,BLANK:2,PARENT:3,TOP:4},w=["","_self","_blank","_parent","_top"];e.CustomStyle=y,e.addLinkAttributes=i,e.isExternalLinkTargetSet=o,e.isValidUrl=c,e.getFilenameFromUrl=a,e.LinkTarget=S,e.RenderingCancelledException=x,e.hasCanvasTypedArrays=v,e.getDefaultSetting=s,e.DEFAULT_LINK_REL=A,e.DOMCanvasFactory=r,e.DOMCMapReaderFactory=b},function(t,e,n){"use strict";function r(){}var i=n(0),a=n(1),s=i.AnnotationBorderStyleType,o=i.AnnotationType,c=i.stringToPDFString,l=i.Util,h=a.addLinkAttributes,u=a.LinkTarget,d=a.getFilenameFromUrl,f=i.warn,p=a.CustomStyle,g=a.getDefaultSetting;r.prototype={create:function(t){switch(t.data.annotationType){case o.LINK:return new A(t);case o.TEXT:return new v(t);case o.WIDGET:switch(t.data.fieldType){case"Tx":return new y(t);case"Btn":if(t.data.radioButton)return new S(t);if(t.data.checkBox)return new x(t);f("Unimplemented button widget annotation: pushbutton");break;case"Ch":return new w(t)}return new b(t);case o.POPUP:return new k(t);case o.LINE:return new _(t);case o.HIGHLIGHT:return new T(t);case o.UNDERLINE:return new P(t);case o.SQUIGGLY:return new L(t);case o.STRIKEOUT:return new E(t);case o.FILEATTACHMENT:return new R(t);default:return new m(t)}}};var m=function(){function t(t,e,n){this.isRenderable=e||!1,this.data=t.data,this.layer=t.layer,this.page=t.page,this.viewport=t.viewport,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderInteractiveForms=t.renderInteractiveForms,e&&(this.container=this._createContainer(n))}return t.prototype={_createContainer:function(t){var e=this.data,n=this.page,r=this.viewport,i=document.createElement("section"),a=e.rect[2]-e.rect[0],o=e.rect[3]-e.rect[1];i.setAttribute("data-annotation-id",e.id);var c=l.normalizeRect([e.rect[0],n.view[3]-e.rect[1]+n.view[1],e.rect[2],n.view[3]-e.rect[3]+n.view[1]]);if(p.setProp("transform",i,"matrix("+r.transform.join(",")+")"),p.setProp("transformOrigin",i,-c[0]+"px "+-c[1]+"px"),!t&&e.borderStyle.width>0){i.style.borderWidth=e.borderStyle.width+"px",e.borderStyle.style!==s.UNDERLINE&&(a-=2*e.borderStyle.width,o-=2*e.borderStyle.width);var h=e.borderStyle.horizontalCornerRadius,u=e.borderStyle.verticalCornerRadius;if(h>0||u>0){var d=h+"px / "+u+"px";p.setProp("borderRadius",i,d)}switch(e.borderStyle.style){case s.SOLID:i.style.borderStyle="solid";break;case s.DASHED:i.style.borderStyle="dashed";break;case s.BEVELED:f("Unimplemented border style: beveled");break;case s.INSET:f("Unimplemented border style: inset");break;case s.UNDERLINE:i.style.borderBottomStyle="solid"}e.color?i.style.borderColor=l.makeCssRgb(0|e.color[0],0|e.color[1],0|e.color[2]):i.style.borderWidth=0}return i.style.left=c[0]+"px",i.style.top=c[1]+"px",i.style.width=a+"px",i.style.height=o+"px",i},_createPopup:function(t,e,n){e||(e=document.createElement("div"),e.style.height=t.style.height,e.style.width=t.style.width,t.appendChild(e));var r=new C({container:t,trigger:e,color:n.color,title:n.title,contents:n.contents,hideWrapper:!0}),i=r.render();i.style.left=t.style.width,t.appendChild(i)},render:function(){throw new Error("Abstract method AnnotationElement.render called")}},t}(),A=function(){function t(t){m.call(this,t,!0)}return l.inherit(t,m,{render:function(){this.container.className="linkAnnotation";var t=document.createElement("a");return h(t,{url:this.data.url,target:this.data.newWindow?u.BLANK:void 0}),this.data.url||(this.data.action?this._bindNamedAction(t,this.data.action):this._bindLink(t,this.data.dest)),this.container.appendChild(t),this.container},_bindLink:function(t,e){var n=this;t.href=this.linkService.getDestinationHash(e),t.onclick=function(){return e&&n.linkService.navigateTo(e),!1},e&&(t.className="internalLink")},_bindNamedAction:function(t,e){var n=this;t.href=this.linkService.getAnchorUrl(""),t.onclick=function(){return n.linkService.executeNamedAction(e),!1},t.className="internalLink"}}),t}(),v=function(){function t(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);m.call(this,t,e)}return l.inherit(t,m,{render:function(){this.container.className="textAnnotation";var t=document.createElement("img");return t.style.height=this.container.style.height,t.style.width=this.container.style.width,t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.alt="[{{type}} Annotation]",t.dataset.l10nId="text_annotation_type",t.dataset.l10nArgs=JSON.stringify({type:this.data.name}),this.data.hasPopup||this._createPopup(this.container,t,this.data),this.container.appendChild(t),this.container}}),t}(),b=function(){function t(t,e){m.call(this,t,e)}return l.inherit(t,m,{render:function(){return this.container}}),t}(),y=function(){function t(t){var e=t.renderInteractiveForms||!t.data.hasAppearance&&!!t.data.fieldValue;b.call(this,t,e)}var e=["left","center","right"];return l.inherit(t,b,{render:function(){this.container.className="textWidgetAnnotation";var t=null;if(this.renderInteractiveForms){if(this.data.multiLine?(t=document.createElement("textarea"),t.textContent=this.data.fieldValue):(t=document.createElement("input"),t.type="text",t.setAttribute("value",this.data.fieldValue)),t.disabled=this.data.readOnly,null!==this.data.maxLen&&(t.maxLength=this.data.maxLen),this.data.comb){var n=this.data.rect[2]-this.data.rect[0],r=n/this.data.maxLen;t.classList.add("comb"),t.style.letterSpacing="calc("+r+"px - 1ch)"}}else{t=document.createElement("div"),t.textContent=this.data.fieldValue,t.style.verticalAlign="middle",t.style.display="table-cell";var i=null;this.data.fontRefName&&(i=this.page.commonObjs.getData(this.data.fontRefName)),this._setTextStyle(t,i)}return null!==this.data.textAlignment&&(t.style.textAlign=e[this.data.textAlignment]),this.container.appendChild(t),this.container},_setTextStyle:function(t,e){var n=t.style;if(n.fontSize=this.data.fontSize+"px",n.direction=this.data.fontDirection<0?"rtl":"ltr",e){n.fontWeight=e.black?e.bold?"900":"bold":e.bold?"bold":"normal",n.fontStyle=e.italic?"italic":"normal";var r=e.loadedName?'"'+e.loadedName+'", ':"",i=e.fallbackName||"Helvetica, sans-serif";n.fontFamily=r+i}}}),t}(),x=function(){function t(t){b.call(this,t,t.renderInteractiveForms)}return l.inherit(t,b,{render:function(){this.container.className="buttonWidgetAnnotation checkBox";var t=document.createElement("input");return t.disabled=this.data.readOnly,t.type="checkbox",this.data.fieldValue&&"Off"!==this.data.fieldValue&&t.setAttribute("checked",!0),this.container.appendChild(t),this.container}}),t}(),S=function(){function t(t){b.call(this,t,t.renderInteractiveForms)}return l.inherit(t,b,{render:function(){this.container.className="buttonWidgetAnnotation radioButton";var t=document.createElement("input");return t.disabled=this.data.readOnly,t.type="radio",t.name=this.data.fieldName,this.data.fieldValue===this.data.buttonValue&&t.setAttribute("checked",!0),this.container.appendChild(t),this.container}}),t}(),w=function(){function t(t){b.call(this,t,t.renderInteractiveForms)}return l.inherit(t,b,{render:function(){this.container.className="choiceWidgetAnnotation";var t=document.createElement("select");t.disabled=this.data.readOnly,this.data.combo||(t.size=this.data.options.length,this.data.multiSelect&&(t.multiple=!0));for(var e=0,n=this.data.options.length;e<n;e++){var r=this.data.options[e],i=document.createElement("option");i.textContent=r.displayValue,i.value=r.exportValue,this.data.fieldValue.indexOf(r.displayValue)>=0&&i.setAttribute("selected",!0),t.appendChild(i)}return this.container.appendChild(t),this.container}}),t}(),k=function(){function t(t){var e=!(!t.data.title&&!t.data.contents);m.call(this,t,e)}var e=["Line"];return l.inherit(t,m,{render:function(){if(this.container.className="popupAnnotation",e.indexOf(this.data.parentType)>=0)return this.container;var t='[data-annotation-id="'+this.data.parentId+'"]',n=this.layer.querySelector(t);if(!n)return this.container;var r=new C({container:this.container,trigger:n,color:this.data.color,title:this.data.title,contents:this.data.contents}),i=parseFloat(n.style.left),a=parseFloat(n.style.width);return p.setProp("transformOrigin",this.container,-(i+a)+"px -"+n.style.top),this.container.style.left=i+a+"px",this.container.appendChild(r.render()),this.container}}),t}(),C=function(){function t(t){this.container=t.container,this.trigger=t.trigger,this.color=t.color,this.title=t.title,this.contents=t.contents,this.hideWrapper=t.hideWrapper||!1,this.pinned=!1}return t.prototype={render:function(){var t=document.createElement("div");t.className="popupWrapper",this.hideElement=this.hideWrapper?t:this.container,this.hideElement.setAttribute("hidden",!0);var e=document.createElement("div");e.className="popup";var n=this.color;if(n){var r=.7*(255-n[0])+n[0],i=.7*(255-n[1])+n[1],a=.7*(255-n[2])+n[2];e.style.backgroundColor=l.makeCssRgb(0|r,0|i,0|a)}var s=this._formatContents(this.contents),o=document.createElement("h1");return o.textContent=this.title,this.trigger.addEventListener("click",this._toggle.bind(this)),this.trigger.addEventListener("mouseover",this._show.bind(this,!1)),this.trigger.addEventListener("mouseout",this._hide.bind(this,!1)),e.addEventListener("click",this._hide.bind(this,!0)),e.appendChild(o),e.appendChild(s),t.appendChild(e),t},_formatContents:function(t){for(var e=document.createElement("p"),n=t.split(/(?:\r\n?|\n)/),r=0,i=n.length;r<i;++r){var a=n[r];e.appendChild(document.createTextNode(a)),r<i-1&&e.appendChild(document.createElement("br"))}return e},_toggle:function(){this.pinned?this._hide(!0):this._show(!0)},_show:function(t){t&&(this.pinned=!0),this.hideElement.hasAttribute("hidden")&&(this.hideElement.removeAttribute("hidden"),this.container.style.zIndex+=1)},_hide:function(t){t&&(this.pinned=!1),this.hideElement.hasAttribute("hidden")||this.pinned||(this.hideElement.setAttribute("hidden",!0),this.container.style.zIndex-=1)}},t}(),_=function(){function t(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);m.call(this,t,e,!0)}var e="http://www.w3.org/2000/svg";return l.inherit(t,m,{render:function(){this.container.className="lineAnnotation" ;var t=this.data,n=t.rect[2]-t.rect[0],r=t.rect[3]-t.rect[1],i=document.createElementNS(e,"svg:svg");i.setAttributeNS(null,"version","1.1"),i.setAttributeNS(null,"width",n+"px"),i.setAttributeNS(null,"height",r+"px"),i.setAttributeNS(null,"preserveAspectRatio","none"),i.setAttributeNS(null,"viewBox","0 0 "+n+" "+r);var a=document.createElementNS(e,"svg:line");return a.setAttributeNS(null,"x1",t.rect[2]-t.lineCoordinates[0]),a.setAttributeNS(null,"y1",t.rect[3]-t.lineCoordinates[1]),a.setAttributeNS(null,"x2",t.rect[2]-t.lineCoordinates[2]),a.setAttributeNS(null,"y2",t.rect[3]-t.lineCoordinates[3]),a.setAttributeNS(null,"stroke-width",t.borderStyle.width),a.setAttributeNS(null,"stroke","transparent"),i.appendChild(a),this.container.append(i),this._createPopup(this.container,a,this.data),this.container}}),t}(),T=function(){function t(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);m.call(this,t,e,!0)}return l.inherit(t,m,{render:function(){return this.container.className="highlightAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),t}(),P=function(){function t(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);m.call(this,t,e,!0)}return l.inherit(t,m,{render:function(){return this.container.className="underlineAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),t}(),L=function(){function t(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);m.call(this,t,e,!0)}return l.inherit(t,m,{render:function(){return this.container.className="squigglyAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),t}(),E=function(){function t(t){var e=!!(t.data.hasPopup||t.data.title||t.data.contents);m.call(this,t,e,!0)}return l.inherit(t,m,{render:function(){return this.container.className="strikeoutAnnotation",this.data.hasPopup||this._createPopup(this.container,null,this.data),this.container}}),t}(),R=function(){function t(t){m.call(this,t,!0);var e=this.data.file;this.filename=d(e.filename),this.content=e.content,this.linkService.onFileAttachmentAnnotation({id:c(e.filename),filename:e.filename,content:e.content})}return l.inherit(t,m,{render:function(){this.container.className="fileAttachmentAnnotation";var t=document.createElement("div");return t.style.height=this.container.style.height,t.style.width=this.container.style.width,t.addEventListener("dblclick",this._download.bind(this)),this.data.hasPopup||!this.data.title&&!this.data.contents||this._createPopup(this.container,t,this.data),this.container.appendChild(t),this.container},_download:function(){if(!this.downloadManager)return void f("Download cannot be started due to unavailable download manager");this.downloadManager.downloadData(this.content,this.filename,"")}}),t}(),I=function(){return{render:function(t){for(var e=new r,n=0,i=t.annotations.length;n<i;n++){var a=t.annotations[n];if(a){var s=e.create({data:a,layer:t.div,page:t.page,viewport:t.viewport,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||g("imageResourcesPath"),renderInteractiveForms:t.renderInteractiveForms||!1});s.isRenderable&&t.div.appendChild(s.render())}}},update:function(t){for(var e=0,n=t.annotations.length;e<n;e++){var r=t.annotations[e],i=t.div.querySelector('[data-annotation-id="'+r.id+'"]');i&&p.setProp("transform",i,"matrix("+t.viewport.transform.join(",")+")")}t.div.removeAttribute("hidden")}}}();e.AnnotationLayer=I},function(t,e,n){"use strict";function r(t,e,n,r){var a=new V;arguments.length>1&&S("getDocument is called with pdfDataRangeTransport, passwordCallback or progressCallback argument"),e&&(e instanceof J||(e=Object.create(e),e.length=t.length,e.initialData=t.initialData,e.abort||(e.abort=function(){})),t=Object.create(t),t.range=e),a.onPassword=n||null,a.onProgress=r||null;var s;"string"==typeof t?s={url:t}:T(t)?s={data:t}:t instanceof J?s={range:t}:("object"!=typeof t&&x("Invalid parameter in getDocument, need either Uint8Array, string or a parameter object"),t.url||t.data||t.range||x("Invalid parameter object: need either .data, .range or .url"),s=t);var o={},c=null,l=null;for(var h in s)if("url"!==h||"undefined"==typeof window)if("range"!==h)if("worker"!==h)if("data"!==h||s[h]instanceof Uint8Array)o[h]=s[h];else{var u=s[h];"string"==typeof u?o[h]=E(u):"object"!=typeof u||null===u||isNaN(u.length)?T(u)?o[h]=new Uint8Array(u):x("Invalid PDF binary data: either typed array, string or array-like object is expected in the data property."):o[h]=new Uint8Array(u)}else l=s[h];else c=s[h];else o[h]=new URL(s[h],window.location).href;o.rangeChunkSize=o.rangeChunkSize||W,o.disableNativeImageDecoder=!0===o.disableNativeImageDecoder,o.ignoreErrors=!0!==o.stopAtErrors;var f=o.CMapReaderFactory||B;if(!l){var p=j("workerPort");l=p?new Z(null,p):new Z,a._worker=l}var g=a.docId;return l.promise.then(function(){if(a.destroyed)throw new Error("Loading aborted");return i(l,o,c,g).then(function(t){if(a.destroyed)throw new Error("Loading aborted");var e=new d(g,t,l.port),n=new $(e,a,c,f);a._transport=n,e.send("Ready",null)})}).catch(a._capability.reject),a}function i(t,e,n,r){return t.destroyed?Promise.reject(new Error("Worker was destroyed")):(e.disableAutoFetch=j("disableAutoFetch"),e.disableStream=j("disableStream"),e.chunkedViewerLoading=!!n,n&&(e.length=n.length,e.initialData=n.initialData),t.messageHandler.sendWithPromise("GetDocRequest",{docId:r,source:e,disableRange:j("disableRange"),maxImageSize:j("maxImageSize"),disableFontFace:j("disableFontFace"),disableCreateObjectURL:j("disableCreateObjectURL"),postMessageTransfers:j("postMessageTransfers")&&!X,docBaseUrl:e.docBaseUrl,disableNativeImageDecoder:e.disableNativeImageDecoder,ignoreErrors:e.ignoreErrors}).then(function(e){if(t.destroyed)throw new Error("Worker was destroyed");return e}))}var a,s=n(0),o=n(11),c=n(10),l=n(7),h=n(1),u=s.InvalidPDFException,d=s.MessageHandler,f=s.MissingPDFException,p=s.PageViewport,g=s.PasswordException,m=s.StatTimer,A=s.UnexpectedResponseException,v=s.UnknownErrorException,b=s.Util,y=s.createPromiseCapability,x=s.error,S=s.deprecated,w=s.getVerbosityLevel,k=s.info,C=s.isInt,_=s.isArray,T=s.isArrayBuffer,P=s.isSameOrigin,L=s.loadJpegStream,E=s.stringToBytes,R=s.globalScope,I=s.warn,F=o.FontFaceObject,O=o.FontLoader,N=c.CanvasGraphics,M=l.Metadata,D=h.RenderingCancelledException,j=h.getDefaultSetting,U=h.DOMCanvasFactory,B=h.DOMCMapReaderFactory,W=65536,G=!1,X=!1,H="undefined"!=typeof document&&document.currentScript?document.currentScript.src:null,z=null,Y=!1;if("undefined"==typeof __pdfjsdev_webpack__){"undefined"==typeof window?(G=!0,void 0===require.ensure&&(require.ensure=require("node-ensure")),Y=!0):"undefined"!=typeof require&&"function"==typeof require.ensure&&(Y=!0),"undefined"!=typeof requirejs&&requirejs.toUrl&&(a=requirejs.toUrl("pdfjs-dist/build/pdf.worker.js"));var q="undefined"!=typeof requirejs&&requirejs.load;z=Y?function(t){require.ensure([],function(){var e=require("./pdf.worker.js");t(e.WorkerMessageHandler)})}:q?function(t){requirejs(["pdfjs-dist/build/pdf.worker"],function(e){t(e.WorkerMessageHandler)})}:null}var V=function(){function t(){this._capability=y(),this._transport=null,this._worker=null,this.docId="d"+e++,this.destroyed=!1,this.onPassword=null,this.onProgress=null,this.onUnsupportedFeature=null}var e=0;return t.prototype={get promise(){return this._capability.promise},destroy:function(){return this.destroyed=!0,(this._transport?this._transport.destroy():Promise.resolve()).then(function(){this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}.bind(this))},then:function(t,e){return this.promise.then.apply(this.promise,arguments)}},t}(),J=function(){function t(t,e){this.length=t,this.initialData=e,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._readyCapability=y()}return t.prototype={addRangeListener:function(t){this._rangeListeners.push(t)},addProgressListener:function(t){this._progressListeners.push(t)},addProgressiveReadListener:function(t){this._progressiveReadListeners.push(t)},onDataRange:function(t,e){for(var n=this._rangeListeners,r=0,i=n.length;r<i;++r)n[r](t,e)},onDataProgress:function(t){this._readyCapability.promise.then(function(){for(var e=this._progressListeners,n=0,r=e.length;n<r;++n)e[n](t)}.bind(this))},onDataProgressiveRead:function(t){this._readyCapability.promise.then(function(){for(var e=this._progressiveReadListeners,n=0,r=e.length;n<r;++n)e[n](t)}.bind(this))},transportReady:function(){this._readyCapability.resolve()},requestDataRange:function(t,e){throw new Error("Abstract method PDFDataRangeTransport.requestDataRange")},abort:function(){}},t}(),Q=function(){function t(t,e,n){this.pdfInfo=t,this.transport=e,this.loadingTask=n}return t.prototype={get numPages(){return this.pdfInfo.numPages},get fingerprint(){return this.pdfInfo.fingerprint},getPage:function(t){return this.transport.getPage(t)},getPageIndex:function(t){return this.transport.getPageIndex(t)},getDestinations:function(){return this.transport.getDestinations()},getDestination:function(t){return this.transport.getDestination(t)},getPageLabels:function(){return this.transport.getPageLabels()},getAttachments:function(){return this.transport.getAttachments()},getJavaScript:function(){return this.transport.getJavaScript()},getOutline:function(){return this.transport.getOutline()},getMetadata:function(){return this.transport.getMetadata()},getData:function(){return this.transport.getData()},getDownloadInfo:function(){return this.transport.downloadInfoCapability.promise},getStats:function(){return this.transport.getStats()},cleanup:function(){this.transport.startCleanup()},destroy:function(){return this.loadingTask.destroy()}},t}(),K=function(){function t(t,e,n){this.pageIndex=t,this.pageInfo=e,this.transport=n,this.stats=new m,this.stats.enabled=j("enableStats"),this.commonObjs=n.commonObjs,this.objs=new tt,this.cleanupAfterRender=!1,this.pendingCleanup=!1,this.intentStates=Object.create(null),this.destroyed=!1}return t.prototype={get pageNumber(){return this.pageIndex+1},get rotate(){return this.pageInfo.rotate},get ref(){return this.pageInfo.ref},get userUnit(){return this.pageInfo.userUnit},get view(){return this.pageInfo.view},getViewport:function(t,e){return arguments.length<2&&(e=this.rotate),new p(this.view,t,e,0,0)},getAnnotations:function(t){var e=t&&t.intent||null;return this.annotationsPromise&&this.annotationsIntent===e||(this.annotationsPromise=this.transport.getAnnotations(this.pageIndex,e),this.annotationsIntent=e),this.annotationsPromise},render:function(t){function e(t){var e=a.renderTasks.indexOf(s);e>=0&&a.renderTasks.splice(e,1),c.cleanupAfterRender&&(c.pendingCleanup=!0),c._tryCleanup(),t?s.capability.reject(t):s.capability.resolve(),n.timeEnd("Rendering"),n.timeEnd("Overall")}var n=this.stats;n.time("Overall"),this.pendingCleanup=!1;var r="print"===t.intent?"print":"display",i=t.canvasFactory||new U;this.intentStates[r]||(this.intentStates[r]=Object.create(null));var a=this.intentStates[r];a.displayReadyCapability||(a.receivingOperatorList=!0,a.displayReadyCapability=y(),a.operatorList={fnArray:[],argsArray:[],lastChunk:!1},this.stats.time("Page Request"),this.transport.messageHandler.send("RenderPageRequest",{pageIndex:this.pageNumber-1,intent:r,renderInteractiveForms:!0===t.renderInteractiveForms}));var s=new nt(e,t,this.objs,this.commonObjs,a.operatorList,this.pageNumber,i);s.useRequestAnimationFrame="print"!==r,a.renderTasks||(a.renderTasks=[]),a.renderTasks.push(s);var o=s.task;t.continueCallback&&(S("render is used with continueCallback parameter"),o.onContinue=t.continueCallback);var c=this;return a.displayReadyCapability.promise.then(function(t){if(c.pendingCleanup)return void e();n.time("Rendering"),s.initializeGraphics(t),s.operatorListChanged()},function(t){e(t)}),o},getOperatorList:function(){function t(){if(n.operatorList.lastChunk){n.opListReadCapability.resolve(n.operatorList);var t=n.renderTasks.indexOf(e);t>=0&&n.renderTasks.splice(t,1)}}this.intentStates.oplist||(this.intentStates.oplist=Object.create(null));var e,n=this.intentStates.oplist;return n.opListReadCapability||(e={},e.operatorListChanged=t,n.receivingOperatorList=!0,n.opListReadCapability=y(),n.renderTasks=[],n.renderTasks.push(e),n.operatorList={fnArray:[],argsArray:[],lastChunk:!1},this.transport.messageHandler.send("RenderPageRequest",{pageIndex:this.pageIndex,intent:"oplist"})),n.opListReadCapability.promise},getTextContent:function(t){return t=t||{},this.transport.messageHandler.sendWithPromise("GetTextContent",{pageIndex:this.pageNumber-1,normalizeWhitespace:!0===t.normalizeWhitespace,combineTextItems:!0!==t.disableCombineTextItems})},_destroy:function(){this.destroyed=!0,this.transport.pageCache[this.pageIndex]=null;var t=[];return Object.keys(this.intentStates).forEach(function(e){if("oplist"!==e){this.intentStates[e].renderTasks.forEach(function(e){var n=e.capability.promise.catch(function(){});t.push(n),e.cancel()})}},this),this.objs.clear(),this.annotationsPromise=null,this.pendingCleanup=!1,Promise.all(t)},destroy:function(){S("page destroy method, use cleanup() instead"),this.cleanup()},cleanup:function(){this.pendingCleanup=!0,this._tryCleanup()},_tryCleanup:function(){this.pendingCleanup&&!Object.keys(this.intentStates).some(function(t){var e=this.intentStates[t];return 0!==e.renderTasks.length||e.receivingOperatorList},this)&&(Object.keys(this.intentStates).forEach(function(t){delete this.intentStates[t]},this),this.objs.clear(),this.annotationsPromise=null,this.pendingCleanup=!1)},_startRenderPage:function(t,e){var n=this.intentStates[e];n.displayReadyCapability&&n.displayReadyCapability.resolve(t)},_renderPageChunk:function(t,e){var n,r,i=this.intentStates[e];for(n=0,r=t.length;n<r;n++)i.operatorList.fnArray.push(t.fnArray[n]),i.operatorList.argsArray.push(t.argsArray[n]);for(i.operatorList.lastChunk=t.lastChunk,n=0;n<i.renderTasks.length;n++)i.renderTasks[n].operatorListChanged();t.lastChunk&&(i.receivingOperatorList=!1,this._tryCleanup())}},t}(),Z=function(){function t(){return void 0!==a?a:j("workerSrc")?j("workerSrc"):H?H.replace(/(\.(?:min\.)?js)$/i,".worker$1"):void x("No PDFJS.workerSrc specified")}function e(){return s?s.promise:(s=y(),(z||function(e){b.loadScript(t(),function(){e(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler)})})(s.resolve),s.promise)}function n(t){this._listeners=[],this._defer=t,this._deferred=Promise.resolve(void 0)}function r(t){var e="importScripts('"+t+"');";return URL.createObjectURL(new Blob([e]))}function i(t,e){if(this.name=t,this.destroyed=!1,this._readyCapability=y(),this._port=null,this._webWorker=null,this._messageHandler=null,e)return void this._initializeFromPort(e);this._initialize()}var s,o=0;return n.prototype={postMessage:function(t,e){function n(t){if("object"!=typeof t||null===t)return t;if(r.has(t))return r.get(t);var i,a;if((a=t.buffer)&&T(a)){var s=e&&e.indexOf(a)>=0;return i=t===a?t:s?new t.constructor(a,t.byteOffset,t.byteLength):new t.constructor(t),r.set(t,i),i}i=_(t)?[]:{},r.set(t,i);for(var o in t){for(var c,l=t;!(c=Object.getOwnPropertyDescriptor(l,o));)l=Object.getPrototypeOf(l);void 0!==c.value&&"function"!=typeof c.value&&(i[o]=n(c.value))}return i}if(!this._defer)return void this._listeners.forEach(function(e){e.call(this,{data:t})},this);var r=new WeakMap,i={data:n(t)};this._deferred.then(function(){this._listeners.forEach(function(t){t.call(this,i)},this)}.bind(this))},addEventListener:function(t,e){this._listeners.push(e)},removeEventListener:function(t,e){var n=this._listeners.indexOf(e);this._listeners.splice(n,1)},terminate:function(){this._listeners=[]}},i.prototype={get promise(){return this._readyCapability.promise},get port(){return this._port},get messageHandler(){return this._messageHandler},_initializeFromPort:function(t){this._port=t,this._messageHandler=new d("main","worker",t),this._messageHandler.on("ready",function(){}),this._readyCapability.resolve()},_initialize:function(){if(!G&&!j("disableWorker")&&"undefined"!=typeof Worker){var e=t();try{P(window.location.href,e)||(e=r(new URL(e,window.location).href));var n=new Worker(e),i=new d("main","worker",n),a=function(){n.removeEventListener("error",s),i.destroy(),n.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()}.bind(this),s=function(t){this._webWorker||a()}.bind(this);n.addEventListener("error",s),i.on("test",function(t){if(n.removeEventListener("error",s),this.destroyed)return void a();t&&t.supportTypedArray?(this._messageHandler=i,this._port=n,this._webWorker=n,t.supportTransfers||(X=!0),this._readyCapability.resolve(),i.send("configure",{verbosity:w()})):(this._setupFakeWorker(),i.destroy(),n.terminate())}.bind(this)),i.on("console_log",function(t){console.log.apply(console,t)}),i.on("console_error",function(t){console.error.apply(console,t)}),i.on("ready",function(t){if(n.removeEventListener("error",s),this.destroyed)return void a();try{o()}catch(t){this._setupFakeWorker()}}.bind(this));var o=function(){var t=j("postMessageTransfers")&&!X,e=new Uint8Array([t?255:0]);try{i.send("test",e,[e.buffer])}catch(t){k("Cannot use postMessage transfers"),e[0]=0,i.send("test",e)}};return void o()}catch(t){k("The worker has been disabled.")}}this._setupFakeWorker()},_setupFakeWorker:function(){G||j("disableWorker")||(I("Setting up fake worker."),G=!0),e().then(function(t){if(this.destroyed)return void this._readyCapability.reject(new Error("Worker was destroyed"));var e=Uint8Array!==Float32Array,r=new n(e);this._port=r;var i="fake"+o++,a=new d(i+"_worker",i,r);t.setup(a,r);var s=new d(i,i+"_worker",r);this._messageHandler=s,this._readyCapability.resolve()}.bind(this))},destroy:function(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}},i}(),$=function(){function t(t,e,n,r){this.messageHandler=t,this.loadingTask=e,this.pdfDataRangeTransport=n,this.commonObjs=new tt,this.fontLoader=new O(e.docId),this.CMapReaderFactory=new r({baseUrl:j("cMapUrl"),isCompressed:j("cMapPacked")}),this.destroyed=!1,this.destroyCapability=null,this._passwordCapability=null,this.pageCache=[],this.pagePromises=[],this.downloadInfoCapability=y(),this.setupMessageHandler()}return t.prototype={destroy:function(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=y(),this._passwordCapability&&this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));var t=[];this.pageCache.forEach(function(e){e&&t.push(e._destroy())}),this.pageCache=[],this.pagePromises=[];var e=this,n=this.messageHandler.sendWithPromise("Terminate",null);return t.push(n),Promise.all(t).then(function(){e.fontLoader.clear(),e.pdfDataRangeTransport&&(e.pdfDataRangeTransport.abort(),e.pdfDataRangeTransport=null),e.messageHandler&&(e.messageHandler.destroy(),e.messageHandler=null),e.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise},setupMessageHandler:function(){var t=this.messageHandler,e=this.loadingTask,n=this.pdfDataRangeTransport;n&&(n.addRangeListener(function(e,n){t.send("OnDataRange",{begin:e,chunk:n})}),n.addProgressListener(function(e){t.send("OnDataProgress",{loaded:e})}),n.addProgressiveReadListener(function(e){t.send("OnDataRange",{chunk:e})}),t.on("RequestDataRange",function(t){n.requestDataRange(t.begin,t.end)},this)),t.on("GetDoc",function(t){var e=t.pdfInfo;this.numPages=t.pdfInfo.numPages;var n=this.loadingTask,r=new Q(e,this,n);this.pdfDocument=r,n._capability.resolve(r)},this),t.on("PasswordRequest",function(t){if(this._passwordCapability=y(),e.onPassword){var n=function(t){this._passwordCapability.resolve({password:t})}.bind(this);e.onPassword(n,t.code)}else this._passwordCapability.reject(new g(t.message,t.code));return this._passwordCapability.promise},this),t.on("PasswordException",function(t){e._capability.reject(new g(t.message,t.code))},this),t.on("InvalidPDF",function(t){this.loadingTask._capability.reject(new u(t.message))},this),t.on("MissingPDF",function(t){this.loadingTask._capability.reject(new f(t.message))},this),t.on("UnexpectedResponse",function(t){this.loadingTask._capability.reject(new A(t.message,t.status))},this),t.on("UnknownError",function(t){this.loadingTask._capability.reject(new v(t.message,t.details))},this),t.on("DataLoaded",function(t){this.downloadInfoCapability.resolve(t)},this),t.on("PDFManagerReady",function(t){this.pdfDataRangeTransport&&this.pdfDataRangeTransport.transportReady()},this),t.on("StartRenderPage",function(t){if(!this.destroyed){var e=this.pageCache[t.pageIndex];e.stats.timeEnd("Page Request"),e._startRenderPage(t.transparency,t.intent)}},this),t.on("RenderPageChunk",function(t){if(!this.destroyed){this.pageCache[t.pageIndex]._renderPageChunk(t.operatorList,t.intent)}},this),t.on("commonobj",function(t){if(!this.destroyed){var e=t[0],n=t[1];if(!this.commonObjs.hasData(e))switch(n){case"Font":var r=t[2];if("error"in r){var i=r.error;I("Error during font loading: "+i),this.commonObjs.resolve(e,i);break}var a=null;j("pdfBug")&&R.FontInspector&&R.FontInspector.enabled&&(a={registerFont:function(t,e){R.FontInspector.fontAdded(t,e)}});var s=new F(r,{isEvalSuported:j("isEvalSupported"),disableFontFace:j("disableFontFace"),fontRegistry:a});this.fontLoader.bind([s],function(t){this.commonObjs.resolve(e,s)}.bind(this));break;case"FontPath":this.commonObjs.resolve(e,t[2]);break;default:x("Got unknown common object type "+n)}}},this),t.on("obj",function(t){if(!this.destroyed){var e,n=t[0],r=t[1],i=t[2],a=this.pageCache[r];if(!a.objs.hasData(n))switch(i){case"JpegStream":e=t[3],L(n,e,a.objs);break;case"Image":e=t[3],a.objs.resolve(n,e);e&&"data"in e&&e.data.length>8e6&&(a.cleanupAfterRender=!0);break;default:x("Got unknown object type "+i)}}},this),t.on("DocProgress",function(t){if(!this.destroyed){var e=this.loadingTask;e.onProgress&&e.onProgress({loaded:t.loaded,total:t.total})}},this),t.on("PageError",function(t){if(!this.destroyed){var e=this.pageCache[t.pageNum-1],n=e.intentStates[t.intent];if(n.displayReadyCapability?n.displayReadyCapability.reject(t.error):x(t.error),n.operatorList){n.operatorList.lastChunk=!0;for(var r=0;r<n.renderTasks.length;r++)n.renderTasks[r].operatorListChanged()}}},this),t.on("UnsupportedFeature",function(t){if(!this.destroyed){var e=t.featureId,n=this.loadingTask;n.onUnsupportedFeature&&n.onUnsupportedFeature(e),rt.notify(e)}},this),t.on("JpegDecode",function(t){if(this.destroyed)return Promise.reject(new Error("Worker was destroyed"));if("undefined"==typeof document)return Promise.reject(new Error('"document" is not defined.'));var e=t[0],n=t[1];return 3!==n&&1!==n?Promise.reject(new Error("Only 3 components or 1 component can be returned")):new Promise(function(t,r){var i=new Image;i.onload=function(){var e=i.width,r=i.height,a=e*r,s=4*a,o=new Uint8Array(a*n),c=document.createElement("canvas");c.width=e,c.height=r;var l=c.getContext("2d");l.drawImage(i,0,0);var h,u,d=l.getImageData(0,0,e,r).data;if(3===n)for(h=0,u=0;h<s;h+=4,u+=3)o[u]=d[h],o[u+1]=d[h+1],o[u+2]=d[h+2];else if(1===n)for(h=0,u=0;h<s;h+=4,u++)o[u]=d[h];t({data:o,width:e,height:r})},i.onerror=function(){r(new Error("JpegDecode failed to load image"))},i.src=e})},this),t.on("FetchBuiltInCMap",function(t){return this.destroyed?Promise.reject(new Error("Worker was destroyed")):this.CMapReaderFactory.fetch({name:t.name})},this)},getData:function(){return this.messageHandler.sendWithPromise("GetData",null)},getPage:function(t,e){if(!C(t)||t<=0||t>this.numPages)return Promise.reject(new Error("Invalid page request"));var n=t-1;if(n in this.pagePromises)return this.pagePromises[n];var r=this.messageHandler.sendWithPromise("GetPage",{pageIndex:n}).then(function(t){if(this.destroyed)throw new Error("Transport destroyed");var e=new K(n,t,this);return this.pageCache[n]=e,e}.bind(this));return this.pagePromises[n]=r,r},getPageIndex:function(t){return this.messageHandler.sendWithPromise("GetPageIndex",{ref:t}).catch(function(t){return Promise.reject(new Error(t))})},getAnnotations:function(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})},getDestinations:function(){return this.messageHandler.sendWithPromise("GetDestinations",null)},getDestination:function(t){return this.messageHandler.sendWithPromise("GetDestination",{id:t})},getPageLabels:function(){return this.messageHandler.sendWithPromise("GetPageLabels",null)},getAttachments:function(){return this.messageHandler.sendWithPromise("GetAttachments",null)},getJavaScript:function(){return this.messageHandler.sendWithPromise("GetJavaScript",null)},getOutline:function(){return this.messageHandler.sendWithPromise("GetOutline",null)},getMetadata:function(){return this.messageHandler.sendWithPromise("GetMetadata",null).then(function(t){return{info:t[0],metadata:t[1]?new M(t[1]):null}})},getStats:function(){return this.messageHandler.sendWithPromise("GetStats",null)},startCleanup:function(){this.messageHandler.sendWithPromise("Cleanup",null).then(function(){for(var t=0,e=this.pageCache.length;t<e;t++){var n=this.pageCache[t];n&&n.cleanup()}this.commonObjs.clear(),this.fontLoader.clear()}.bind(this))}},t}(),tt=function(){function t(){this.objs=Object.create(null)}return t.prototype={ensureObj:function(t){if(this.objs[t])return this.objs[t];var e={capability:y(),data:null,resolved:!1};return this.objs[t]=e,e},get:function(t,e){if(e)return this.ensureObj(t).capability.promise.then(e),null;var n=this.objs[t];return n&&n.resolved||x("Requesting object that isn't resolved yet "+t),n.data},resolve:function(t,e){var n=this.ensureObj(t);n.resolved=!0,n.data=e,n.capability.resolve(e)},isResolved:function(t){var e=this.objs;return!!e[t]&&e[t].resolved},hasData:function(t){return this.isResolved(t)},getData:function(t){var e=this.objs;return e[t]&&e[t].resolved?e[t].data:null},clear:function(){this.objs=Object.create(null)}},t}(),et=function(){function t(t){this._internalRenderTask=t,this.onContinue=null}return t.prototype={get promise(){return this._internalRenderTask.capability.promise},cancel:function(){this._internalRenderTask.cancel()},then:function(t,e){return this.promise.then.apply(this.promise,arguments)}},t}(),nt=function(){function t(t,e,n,r,i,a,s){this.callback=t,this.params=e,this.objs=n,this.commonObjs=r,this.operatorListIdx=null,this.operatorList=i,this.pageNumber=a,this.canvasFactory=s,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this.useRequestAnimationFrame=!1,this.cancelled=!1,this.capability=y(),this.task=new et(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this)}return t.prototype={initializeGraphics:function(t){if(!this.cancelled){j("pdfBug")&&R.StepperManager&&R.StepperManager.enabled&&(this.stepper=R.StepperManager.create(this.pageNumber-1),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());var e=this.params;this.gfx=new N(e.canvasContext,this.commonObjs,this.objs,this.canvasFactory,e.imageLayer),this.gfx.beginDrawing(e.transform,e.viewport,t),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback&&this.graphicsReadyCallback()}},cancel:function(){this.running=!1,this.cancelled=!0,j("pdfjsNext")?this.callback(new D("Rendering cancelled, page "+this.pageNumber,"canvas")):this.callback("cancelled")},operatorListChanged:function(){if(!this.graphicsReady)return void(this.graphicsReadyCallback||(this.graphicsReadyCallback=this._continueBound));this.stepper&&this.stepper.updateOperatorList(this.operatorList),this.running||this._continue()},_continue:function(){this.running=!0,this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())},_scheduleNext:function(){this.useRequestAnimationFrame&&"undefined"!=typeof window?window.requestAnimationFrame(this._nextBound):Promise.resolve(void 0).then(this._nextBound)},_next:function(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),this.callback())))}},t}(),rt=function(){var t=[];return{listen:function(e){S("Global UnsupportedManager.listen is used: use PDFDocumentLoadingTask.onUnsupportedFeature instead"),t.push(e)},notify:function(e){for(var n=0,r=t.length;n<r;n++)t[n](e)}}}();e.version="1.8.199",e.build="74b31ab1",e.getDocument=r,e.PDFDataRangeTransport=J,e.PDFWorker=Z,e.PDFDocumentProxy=Q,e.PDFPageProxy=K,e._UnsupportedManager=rt},function(t,e,n){"use strict";var r=n(0),i=r.FONT_IDENTITY_MATRIX,a=r.IDENTITY_MATRIX,s=r.ImageKind,o=r.OPS,c=r.Util,l=r.isNum,h=r.isArray,u=r.warn,d=r.createObjectURL,f={fontStyle:"normal",fontWeight:"normal",fillColor:"#000000"},p=function(){function t(t,e,n){for(var r=-1,i=e;i<n;i++){var a=255&(r^t[i]);r=r>>>8^o[a]}return-1^r}function e(e,n,r,i){var a=i,s=n.length;r[a]=s>>24&255,r[a+1]=s>>16&255,r[a+2]=s>>8&255,r[a+3]=255&s,a+=4,r[a]=255&e.charCodeAt(0),r[a+1]=255&e.charCodeAt(1),r[a+2]=255&e.charCodeAt(2),r[a+3]=255&e.charCodeAt(3),a+=4,r.set(n,a),a+=n.length;var o=t(r,i+4,a);r[a]=o>>24&255,r[a+1]=o>>16&255,r[a+2]=o>>8&255,r[a+3]=255&o}function n(t,e,n){for(var r=1,i=0,a=e;a<n;++a)r=(r+(255&t[a]))%65521,i=(i+r)%65521;return i<<16|r}function r(t,r,o){var c,l,h,u=t.width,f=t.height,p=t.data;switch(r){case s.GRAYSCALE_1BPP:l=0,c=1,h=u+7>>3;break;case s.RGB_24BPP:l=2,c=8,h=3*u;break;case s.RGBA_32BPP:l=6,c=8,h=4*u;break;default:throw new Error("invalid format")}var g,m,A=new Uint8Array((1+h)*f),v=0,b=0;for(g=0;g<f;++g)A[v++]=0,A.set(p.subarray(b,b+h),v),b+=h,v+=h;if(r===s.GRAYSCALE_1BPP)for(v=0,g=0;g<f;g++)for(v++,m=0;m<h;m++)A[v++]^=255;var y=new Uint8Array([u>>24&255,u>>16&255,u>>8&255,255&u,f>>24&255,f>>16&255,f>>8&255,255&f,c,l,0,0,0]),x=A.length,S=Math.ceil(x/65535),w=new Uint8Array(2+x+5*S+4),k=0;w[k++]=120,w[k++]=156;for(var C=0;x>65535;)w[k++]=0,w[k++]=255,w[k++]=255,w[k++]=0,w[k++]=0,w.set(A.subarray(C,C+65535),k),k+=65535,C+=65535,x-=65535;w[k++]=1,w[k++]=255&x,w[k++]=x>>8&255,w[k++]=255&~x,w[k++]=(65535&~x)>>8&255,w.set(A.subarray(C),k),k+=A.length-C;var _=n(A,0,A.length);w[k++]=_>>24&255,w[k++]=_>>16&255,w[k++]=_>>8&255,w[k++]=255&_;var T=i.length+3*a+y.length+w.length,P=new Uint8Array(T),L=0;return P.set(i,L),L+=i.length,e("IHDR",y,P,L),L+=a+y.length,e("IDATA",w,P,L),L+=a+w.length,e("IEND",new Uint8Array(0),P,L),d(P,"image/png",o)}for(var i=new Uint8Array([137,80,78,71,13,10,26,10]),a=12,o=new Int32Array(256),c=0;c<256;c++){for(var l=c,h=0;h<8;h++)l=1&l?3988292384^l>>1&2147483647:l>>1&2147483647;o[c]=l}return function(t,e){return r(t,void 0===t.kind?s.GRAYSCALE_1BPP:t.kind,e)}}(),g=function(){function t(){this.fontSizeScale=1,this.fontWeight=f.fontWeight,this.fontSize=0,this.textMatrix=a,this.fontMatrix=i,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRise=0,this.fillColor=f.fillColor,this.strokeColor="#000000",this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.lineJoin="",this.lineCap="",this.miterLimit=0,this.dashArray=[],this.dashPhase=0,this.dependencies=[],this.activeClipUrl=null,this.clipGroup=null,this.maskId=""}return t.prototype={clone:function(){return Object.create(this)},setCurrentPoint:function(t,e){this.x=t,this.y=e}},t}(),m=function(){function t(t){for(var e=[],n=[],r=t.length,i=0;i<r;i++)"save"!==t[i].fn?"restore"===t[i].fn?e=n.pop():e.push(t[i]):(e.push({fnId:92,fn:"group",items:[]}),n.push(e),e=e[e.length-1].items);return e}function e(t){if(t===(0|t))return t.toString();var e=t.toFixed(10),n=e.length-1;if("0"!==e[n])return e;do{n-- }while("0"===e[n]);return e.substr(0,"."===e[n]?n:n+1)}function n(t){if(0===t[4]&&0===t[5]){if(0===t[1]&&0===t[2])return 1===t[0]&&1===t[3]?"":"scale("+e(t[0])+" "+e(t[3])+")";if(t[0]===t[3]&&t[1]===-t[2]){return"rotate("+e(180*Math.acos(t[0])/Math.PI)+")"}}else if(1===t[0]&&0===t[1]&&0===t[2]&&1===t[3])return"translate("+e(t[4])+" "+e(t[5])+")";return"matrix("+e(t[0])+" "+e(t[1])+" "+e(t[2])+" "+e(t[3])+" "+e(t[4])+" "+e(t[5])+")"}function r(t,e,n){this.current=new g,this.transformMatrix=a,this.transformStack=[],this.extraStack=[],this.commonObjs=t,this.objs=e,this.pendingEOFill=!1,this.embedFonts=!1,this.embeddedFonts=Object.create(null),this.cssStyle=null,this.forceDataSchema=!!n}var s="http://www.w3.org/2000/svg",m="http://www.w3.org/1999/xlink",A=["butt","round","square"],v=["miter","round","bevel"],b=0,y=0;return r.prototype={save:function(){this.transformStack.push(this.transformMatrix);var t=this.current;this.extraStack.push(t),this.current=t.clone()},restore:function(){this.transformMatrix=this.transformStack.pop(),this.current=this.extraStack.pop(),this.tgrp=null},group:function(t){this.save(),this.executeOpTree(t),this.restore()},loadDependencies:function(t){for(var e=t.fnArray,n=e.length,r=t.argsArray,i=this,a=0;a<n;a++)if(o.dependency===e[a])for(var s=r[a],c=0,l=s.length;c<l;c++){var h,u=s[c],d="g_"===u.substring(0,2);h=d?new Promise(function(t){i.commonObjs.get(u,t)}):new Promise(function(t){i.objs.get(u,t)}),this.current.dependencies.push(h)}return Promise.all(this.current.dependencies)},transform:function(t,e,n,r,i,a){var s=[t,e,n,r,i,a];this.transformMatrix=c.transform(this.transformMatrix,s),this.tgrp=null},getSVG:function(t,e){this.viewport=e;var n=this._initialize(e);return this.loadDependencies(t).then(function(){this.transformMatrix=a;var e=this.convertOpList(t);return this.executeOpTree(e),n}.bind(this))},convertOpList:function(e){var n=e.argsArray,r=e.fnArray,i=r.length,a=[],s=[];for(var c in o)a[o[c]]=c;for(var l=0;l<i;l++){var h=r[l];s.push({fnId:h,fn:a[h],args:n[l]})}return t(s)},executeOpTree:function(t){for(var e=t.length,n=0;n<e;n++){var r=t[n].fn,i=t[n].fnId,a=t[n].args;switch(0|i){case o.beginText:this.beginText();break;case o.setLeading:this.setLeading(a);break;case o.setLeadingMoveText:this.setLeadingMoveText(a[0],a[1]);break;case o.setFont:this.setFont(a);break;case o.showText:case o.showSpacedText:this.showText(a[0]);break;case o.endText:this.endText();break;case o.moveText:this.moveText(a[0],a[1]);break;case o.setCharSpacing:this.setCharSpacing(a[0]);break;case o.setWordSpacing:this.setWordSpacing(a[0]);break;case o.setHScale:this.setHScale(a[0]);break;case o.setTextMatrix:this.setTextMatrix(a[0],a[1],a[2],a[3],a[4],a[5]);break;case o.setLineWidth:this.setLineWidth(a[0]);break;case o.setLineJoin:this.setLineJoin(a[0]);break;case o.setLineCap:this.setLineCap(a[0]);break;case o.setMiterLimit:this.setMiterLimit(a[0]);break;case o.setFillRGBColor:this.setFillRGBColor(a[0],a[1],a[2]);break;case o.setStrokeRGBColor:this.setStrokeRGBColor(a[0],a[1],a[2]);break;case o.setDash:this.setDash(a[0],a[1]);break;case o.setGState:this.setGState(a[0]);break;case o.fill:this.fill();break;case o.eoFill:this.eoFill();break;case o.stroke:this.stroke();break;case o.fillStroke:this.fillStroke();break;case o.eoFillStroke:this.eoFillStroke();break;case o.clip:this.clip("nonzero");break;case o.eoClip:this.clip("evenodd");break;case o.paintSolidColorImageMask:this.paintSolidColorImageMask();break;case o.paintJpegXObject:this.paintJpegXObject(a[0],a[1],a[2]);break;case o.paintImageXObject:this.paintImageXObject(a[0]);break;case o.paintInlineImageXObject:this.paintInlineImageXObject(a[0]);break;case o.paintImageMaskXObject:this.paintImageMaskXObject(a[0]);break;case o.paintFormXObjectBegin:this.paintFormXObjectBegin(a[0],a[1]);break;case o.paintFormXObjectEnd:this.paintFormXObjectEnd();break;case o.closePath:this.closePath();break;case o.closeStroke:this.closeStroke();break;case o.closeFillStroke:this.closeFillStroke();break;case o.nextLine:this.nextLine();break;case o.transform:this.transform(a[0],a[1],a[2],a[3],a[4],a[5]);break;case o.constructPath:this.constructPath(a[0],a[1]);break;case o.endPath:this.endPath();break;case 92:this.group(t[n].items);break;default:u("Unimplemented operator "+r)}}},setWordSpacing:function(t){this.current.wordSpacing=t},setCharSpacing:function(t){this.current.charSpacing=t},nextLine:function(){this.moveText(0,this.current.leading)},setTextMatrix:function(t,n,r,i,a,o){var c=this.current;this.current.textMatrix=this.current.lineMatrix=[t,n,r,i,a,o],this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,c.xcoords=[],c.tspan=document.createElementNS(s,"svg:tspan"),c.tspan.setAttributeNS(null,"font-family",c.fontFamily),c.tspan.setAttributeNS(null,"font-size",e(c.fontSize)+"px"),c.tspan.setAttributeNS(null,"y",e(-c.y)),c.txtElement=document.createElementNS(s,"svg:text"),c.txtElement.appendChild(c.tspan)},beginText:function(){this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0,this.current.textMatrix=a,this.current.lineMatrix=a,this.current.tspan=document.createElementNS(s,"svg:tspan"),this.current.txtElement=document.createElementNS(s,"svg:text"),this.current.txtgrp=document.createElementNS(s,"svg:g"),this.current.xcoords=[]},moveText:function(t,n){var r=this.current;this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=n,r.xcoords=[],r.tspan=document.createElementNS(s,"svg:tspan"),r.tspan.setAttributeNS(null,"font-family",r.fontFamily),r.tspan.setAttributeNS(null,"font-size",e(r.fontSize)+"px"),r.tspan.setAttributeNS(null,"y",e(-r.y))},showText:function(t){var r=this.current,i=r.font,a=r.fontSize;if(0!==a){var s,o=r.charSpacing,c=r.wordSpacing,h=r.fontDirection,u=r.textHScale*h,d=t.length,p=i.vertical,g=a*r.fontMatrix[0],m=0;for(s=0;s<d;++s){var A=t[s];if(null!==A)if(l(A))m+=-A*a*.001;else{r.xcoords.push(r.x+m*u);var v=A.width,b=A.fontChar,y=v*g+o*h;m+=y,r.tspan.textContent+=b}else m+=h*c}p?r.y-=m*u:r.x+=m*u,r.tspan.setAttributeNS(null,"x",r.xcoords.map(e).join(" ")),r.tspan.setAttributeNS(null,"y",e(-r.y)),r.tspan.setAttributeNS(null,"font-family",r.fontFamily),r.tspan.setAttributeNS(null,"font-size",e(r.fontSize)+"px"),r.fontStyle!==f.fontStyle&&r.tspan.setAttributeNS(null,"font-style",r.fontStyle),r.fontWeight!==f.fontWeight&&r.tspan.setAttributeNS(null,"font-weight",r.fontWeight),r.fillColor!==f.fillColor&&r.tspan.setAttributeNS(null,"fill",r.fillColor),r.txtElement.setAttributeNS(null,"transform",n(r.textMatrix)+" scale(1, -1)"),r.txtElement.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve"),r.txtElement.appendChild(r.tspan),r.txtgrp.appendChild(r.txtElement),this._ensureTransformGroup().appendChild(r.txtElement)}},setLeadingMoveText:function(t,e){this.setLeading(-e),this.moveText(t,e)},addFontStyle:function(t){this.cssStyle||(this.cssStyle=document.createElementNS(s,"svg:style"),this.cssStyle.setAttributeNS(null,"type","text/css"),this.defs.appendChild(this.cssStyle));var e=d(t.data,t.mimetype,this.forceDataSchema);this.cssStyle.textContent+='@font-face { font-family: "'+t.loadedName+'"; src: url('+e+"); }\n"},setFont:function(t){var n=this.current,r=this.commonObjs.get(t[0]),a=t[1];this.current.font=r,this.embedFonts&&r.data&&!this.embeddedFonts[r.loadedName]&&(this.addFontStyle(r),this.embeddedFonts[r.loadedName]=r),n.fontMatrix=r.fontMatrix?r.fontMatrix:i;var o=r.black?r.bold?"bolder":"bold":r.bold?"bold":"normal",c=r.italic?"italic":"normal";a<0?(a=-a,n.fontDirection=-1):n.fontDirection=1,n.fontSize=a,n.fontFamily=r.loadedName,n.fontWeight=o,n.fontStyle=c,n.tspan=document.createElementNS(s,"svg:tspan"),n.tspan.setAttributeNS(null,"y",e(-n.y)),n.xcoords=[]},endText:function(){},setLineWidth:function(t){this.current.lineWidth=t},setLineCap:function(t){this.current.lineCap=A[t]},setLineJoin:function(t){this.current.lineJoin=v[t]},setMiterLimit:function(t){this.current.miterLimit=t},setStrokeRGBColor:function(t,e,n){var r=c.makeCssRgb(t,e,n);this.current.strokeColor=r},setFillRGBColor:function(t,e,n){var r=c.makeCssRgb(t,e,n);this.current.fillColor=r,this.current.tspan=document.createElementNS(s,"svg:tspan"),this.current.xcoords=[]},setDash:function(t,e){this.current.dashArray=t,this.current.dashPhase=e},constructPath:function(t,n){var r=this.current,i=r.x,a=r.y;r.path=document.createElementNS(s,"svg:path");for(var c=[],l=t.length,h=0,u=0;h<l;h++)switch(0|t[h]){case o.rectangle:i=n[u++],a=n[u++];var d=n[u++],f=n[u++],p=i+d,g=a+f;c.push("M",e(i),e(a),"L",e(p),e(a),"L",e(p),e(g),"L",e(i),e(g),"Z");break;case o.moveTo:i=n[u++],a=n[u++],c.push("M",e(i),e(a));break;case o.lineTo:i=n[u++],a=n[u++],c.push("L",e(i),e(a));break;case o.curveTo:i=n[u+4],a=n[u+5],c.push("C",e(n[u]),e(n[u+1]),e(n[u+2]),e(n[u+3]),e(i),e(a)),u+=6;break;case o.curveTo2:i=n[u+2],a=n[u+3],c.push("C",e(i),e(a),e(n[u]),e(n[u+1]),e(n[u+2]),e(n[u+3])),u+=4;break;case o.curveTo3:i=n[u+2],a=n[u+3],c.push("C",e(n[u]),e(n[u+1]),e(i),e(a),e(i),e(a)),u+=4;break;case o.closePath:c.push("Z")}r.path.setAttributeNS(null,"d",c.join(" ")),r.path.setAttributeNS(null,"stroke-miterlimit",e(r.miterLimit)),r.path.setAttributeNS(null,"stroke-linecap",r.lineCap),r.path.setAttributeNS(null,"stroke-linejoin",r.lineJoin),r.path.setAttributeNS(null,"stroke-width",e(r.lineWidth)+"px"),r.path.setAttributeNS(null,"stroke-dasharray",r.dashArray.map(e).join(" ")),r.path.setAttributeNS(null,"stroke-dashoffset",e(r.dashPhase)+"px"),r.path.setAttributeNS(null,"fill","none"),this._ensureTransformGroup().appendChild(r.path),r.element=r.path,r.setCurrentPoint(i,a)},endPath:function(){},clip:function(t){var e=this.current,r="clippath"+b;b++;var i=document.createElementNS(s,"svg:clipPath");i.setAttributeNS(null,"id",r),i.setAttributeNS(null,"transform",n(this.transformMatrix));var a=e.element.cloneNode();"evenodd"===t?a.setAttributeNS(null,"clip-rule","evenodd"):a.setAttributeNS(null,"clip-rule","nonzero"),i.appendChild(a),this.defs.appendChild(i),e.activeClipUrl&&(e.clipGroup=null,this.extraStack.forEach(function(t){t.clipGroup=null})),e.activeClipUrl="url(#"+r+")",this.tgrp=null},closePath:function(){var t=this.current,e=t.path.getAttributeNS(null,"d");e+="Z",t.path.setAttributeNS(null,"d",e)},setLeading:function(t){this.current.leading=-t},setTextRise:function(t){this.current.textRise=t},setHScale:function(t){this.current.textHScale=t/100},setGState:function(t){for(var e=0,n=t.length;e<n;e++){var r=t[e],i=r[0],a=r[1];switch(i){case"LW":this.setLineWidth(a);break;case"LC":this.setLineCap(a);break;case"LJ":this.setLineJoin(a);break;case"ML":this.setMiterLimit(a);break;case"D":this.setDash(a[0],a[1]);break;case"Font":this.setFont(a);break;default:u("Unimplemented graphic state "+i)}}},fill:function(){var t=this.current;t.element.setAttributeNS(null,"fill",t.fillColor)},stroke:function(){var t=this.current;t.element.setAttributeNS(null,"stroke",t.strokeColor),t.element.setAttributeNS(null,"fill","none")},eoFill:function(){var t=this.current;t.element.setAttributeNS(null,"fill",t.fillColor),t.element.setAttributeNS(null,"fill-rule","evenodd")},fillStroke:function(){this.stroke(),this.fill()},eoFillStroke:function(){this.current.element.setAttributeNS(null,"fill-rule","evenodd"),this.fillStroke()},closeStroke:function(){this.closePath(),this.stroke()},closeFillStroke:function(){this.closePath(),this.fillStroke()},paintSolidColorImageMask:function(){var t=this.current,e=document.createElementNS(s,"svg:rect");e.setAttributeNS(null,"x","0"),e.setAttributeNS(null,"y","0"),e.setAttributeNS(null,"width","1px"),e.setAttributeNS(null,"height","1px"),e.setAttributeNS(null,"fill",t.fillColor),this._ensureTransformGroup().appendChild(e)},paintJpegXObject:function(t,n,r){var i=this.objs.get(t),a=document.createElementNS(s,"svg:image");a.setAttributeNS(m,"xlink:href",i.src),a.setAttributeNS(null,"width",i.width+"px"),a.setAttributeNS(null,"height",i.height+"px"),a.setAttributeNS(null,"x","0"),a.setAttributeNS(null,"y",e(-r)),a.setAttributeNS(null,"transform","scale("+e(1/n)+" "+e(-1/r)+")"),this._ensureTransformGroup().appendChild(a)},paintImageXObject:function(t){var e=this.objs.get(t);if(!e)return void u("Dependent image isn't ready yet");this.paintInlineImageXObject(e)},paintInlineImageXObject:function(t,n){var r=t.width,i=t.height,a=p(t,this.forceDataSchema),o=document.createElementNS(s,"svg:rect");o.setAttributeNS(null,"x","0"),o.setAttributeNS(null,"y","0"),o.setAttributeNS(null,"width",e(r)),o.setAttributeNS(null,"height",e(i)),this.current.element=o,this.clip("nonzero");var c=document.createElementNS(s,"svg:image");c.setAttributeNS(m,"xlink:href",a),c.setAttributeNS(null,"x","0"),c.setAttributeNS(null,"y",e(-i)),c.setAttributeNS(null,"width",e(r)+"px"),c.setAttributeNS(null,"height",e(i)+"px"),c.setAttributeNS(null,"transform","scale("+e(1/r)+" "+e(-1/i)+")"),n?n.appendChild(c):this._ensureTransformGroup().appendChild(c)},paintImageMaskXObject:function(t){var n=this.current,r=t.width,i=t.height,a=n.fillColor;n.maskId="mask"+y++;var o=document.createElementNS(s,"svg:mask");o.setAttributeNS(null,"id",n.maskId);var c=document.createElementNS(s,"svg:rect");c.setAttributeNS(null,"x","0"),c.setAttributeNS(null,"y","0"),c.setAttributeNS(null,"width",e(r)),c.setAttributeNS(null,"height",e(i)),c.setAttributeNS(null,"fill",a),c.setAttributeNS(null,"mask","url(#"+n.maskId+")"),this.defs.appendChild(o),this._ensureTransformGroup().appendChild(c),this.paintInlineImageXObject(t,o)},paintFormXObjectBegin:function(t,n){if(h(t)&&6===t.length&&this.transform(t[0],t[1],t[2],t[3],t[4],t[5]),h(n)&&4===n.length){var r=n[2]-n[0],i=n[3]-n[1],a=document.createElementNS(s,"svg:rect");a.setAttributeNS(null,"x",n[0]),a.setAttributeNS(null,"y",n[1]),a.setAttributeNS(null,"width",e(r)),a.setAttributeNS(null,"height",e(i)),this.current.element=a,this.clip("nonzero"),this.endPath()}},paintFormXObjectEnd:function(){},_initialize:function(t){var e=document.createElementNS(s,"svg:svg");e.setAttributeNS(null,"version","1.1"),e.setAttributeNS(null,"width",t.width+"px"),e.setAttributeNS(null,"height",t.height+"px"),e.setAttributeNS(null,"preserveAspectRatio","none"),e.setAttributeNS(null,"viewBox","0 0 "+t.width+" "+t.height);var r=document.createElementNS(s,"svg:defs");e.appendChild(r),this.defs=r;var i=document.createElementNS(s,"svg:g");return i.setAttributeNS(null,"transform",n(t.transform)),e.appendChild(i),this.svg=i,e},_ensureClipGroup:function(){if(!this.current.clipGroup){var t=document.createElementNS(s,"svg:g");t.setAttributeNS(null,"clip-path",this.current.activeClipUrl),this.svg.appendChild(t),this.current.clipGroup=t}return this.current.clipGroup},_ensureTransformGroup:function(){return this.tgrp||(this.tgrp=document.createElementNS(s,"svg:g"),this.tgrp.setAttributeNS(null,"transform",n(this.transformMatrix)),this.current.activeClipUrl?this._ensureClipGroup().appendChild(this.tgrp):this.svg.appendChild(this.tgrp)),this.tgrp}},r}();e.SVGGraphics=m},function(t,e,n){"use strict";var r=n(0),i=n(1),a=r.Util,s=r.createPromiseCapability,o=i.CustomStyle,c=i.getDefaultSetting,l=function(){function t(t){return!f.test(t)}function e(e,n,r){var i=document.createElement("div"),s={style:null,angle:0,canvasWidth:0,isWhitespace:!1,originalTransform:null,paddingBottom:0,paddingLeft:0,paddingRight:0,paddingTop:0,scale:1};if(e._textDivs.push(i),t(n.str))return s.isWhitespace=!0,void e._textDivProperties.set(i,s);var o=a.transform(e._viewport.transform,n.transform),l=Math.atan2(o[1],o[0]),h=r[n.fontName];h.vertical&&(l+=Math.PI/2);var u=Math.sqrt(o[2]*o[2]+o[3]*o[3]),d=u;h.ascent?d=h.ascent*d:h.descent&&(d=(1+h.descent)*d);var f,g;if(0===l?(f=o[4],g=o[5]-d):(f=o[4]+d*Math.sin(l),g=o[5]-d*Math.cos(l)),p[1]=f,p[3]=g,p[5]=u,p[7]=h.fontFamily,s.style=p.join(""),i.setAttribute("style",s.style),i.textContent=n.str,c("pdfBug")&&(i.dataset.fontName=n.fontName),0!==l&&(s.angle=l*(180/Math.PI)),n.str.length>1&&(h.vertical?s.canvasWidth=n.height*e._viewport.scale:s.canvasWidth=n.width*e._viewport.scale),e._textDivProperties.set(i,s),e._enhanceTextSelection){var m=1,A=0;0!==l&&(m=Math.cos(l),A=Math.sin(l));var v,b,y=(h.vertical?n.height:n.width)*e._viewport.scale,x=u;0!==l?(v=[m,A,-A,m,f,g],b=a.getAxialAlignedBoundingBox([0,0,y,x],v)):b=[f,g,f+y,g+x],e._bounds.push({left:b[0],top:b[1],right:b[2],bottom:b[3],div:i,size:[y,x],m:v})}}function n(t){if(!t._canceled){var e=t._container,n=t._textDivs,r=t._capability,i=n.length;if(i>d)return t._renderingDone=!0,void r.resolve();var a=document.createElement("canvas");a.mozOpaque=!0;for(var s,c,l=a.getContext("2d",{alpha:!1}),h=0;h<i;h++){var u=n[h],f=t._textDivProperties.get(u);if(!f.isWhitespace){var p=u.style.fontSize,g=u.style.fontFamily;p===s&&g===c||(l.font=p+" "+g,s=p,c=g);var m=l.measureText(u.textContent).width;e.appendChild(u);var A="";0!==f.canvasWidth&&m>0&&(f.scale=f.canvasWidth/m,A="scaleX("+f.scale+")"),0!==f.angle&&(A="rotate("+f.angle+"deg) "+A),""!==A&&(f.originalTransform=A,o.setProp("transform",u,A)),t._textDivProperties.set(u,f)}}t._renderingDone=!0,r.resolve()}}function r(t){for(var e=t._bounds,n=t._viewport,r=i(n.width,n.height,e),s=0;s<r.length;s++){var o=e[s].div,c=t._textDivProperties.get(o);if(0!==c.angle){var l=r[s],h=e[s],u=h.m,d=u[0],f=u[1],p=[[0,0],[0,h.size[1]],[h.size[0],0],h.size],g=new Float64Array(64);p.forEach(function(t,e){var n=a.applyTransform(t,u);g[e+0]=d&&(l.left-n[0])/d,g[e+4]=f&&(l.top-n[1])/f,g[e+8]=d&&(l.right-n[0])/d,g[e+12]=f&&(l.bottom-n[1])/f,g[e+16]=f&&(l.left-n[0])/-f,g[e+20]=d&&(l.top-n[1])/d,g[e+24]=f&&(l.right-n[0])/-f,g[e+28]=d&&(l.bottom-n[1])/d,g[e+32]=d&&(l.left-n[0])/-d,g[e+36]=f&&(l.top-n[1])/-f,g[e+40]=d&&(l.right-n[0])/-d,g[e+44]=f&&(l.bottom-n[1])/-f,g[e+48]=f&&(l.left-n[0])/f,g[e+52]=d&&(l.top-n[1])/-d,g[e+56]=f&&(l.right-n[0])/f,g[e+60]=d&&(l.bottom-n[1])/-d});var m=function(t,e,n){for(var r=0,i=0;i<n;i++){var a=t[e++];a>0&&(r=r?Math.min(a,r):a)}return r},A=1+Math.min(Math.abs(d),Math.abs(f));c.paddingLeft=m(g,32,16)/A,c.paddingTop=m(g,48,16)/A,c.paddingRight=m(g,0,16)/A,c.paddingBottom=m(g,16,16)/A,t._textDivProperties.set(o,c)}else c.paddingLeft=e[s].left-r[s].left,c.paddingTop=e[s].top-r[s].top,c.paddingRight=r[s].right-e[s].right,c.paddingBottom=r[s].bottom-e[s].bottom,t._textDivProperties.set(o,c)}}function i(t,e,n){var r=n.map(function(t,e){return{x1:t.left,y1:t.top,x2:t.right,y2:t.bottom,index:e,x1New:void 0,x2New:void 0}});l(t,r);var i=new Array(n.length);return r.forEach(function(t){var e=t.index;i[e]={left:t.x1New,top:0,right:t.x2New,bottom:0}}),n.map(function(e,n){var a=i[n],s=r[n];s.x1=e.top,s.y1=t-a.right,s.x2=e.bottom,s.y2=t-a.left,s.index=n,s.x1New=void 0,s.x2New=void 0}),l(e,r),r.forEach(function(t){var e=t.index;i[e].top=t.x1New,i[e].bottom=t.x2New}),i}function l(t,e){e.sort(function(t,e){return t.x1-e.x1||t.index-e.index});var n={x1:-1/0,y1:-1/0,x2:0,y2:1/0,index:-1,x1New:0,x2New:0},r=[{start:-1/0,end:1/0,boundary:n}];e.forEach(function(t){for(var e=0;e<r.length&&r[e].end<=t.y1;)e++;for(var n=r.length-1;n>=0&&r[n].start>=t.y2;)n--;var i,a,s,o,c=-1/0;for(s=e;s<=n;s++){i=r[s],a=i.boundary;var l;l=a.x2>t.x1?a.index>t.index?a.x1New:t.x1:void 0===a.x2New?(a.x2+t.x1)/2:a.x2New,l>c&&(c=l)}for(t.x1New=c,s=e;s<=n;s++)i=r[s],a=i.boundary,void 0===a.x2New?a.x2>t.x1?a.index>t.index&&(a.x2New=a.x2):a.x2New=c:a.x2New>c&&(a.x2New=Math.max(c,a.x2));var h=[],u=null;for(s=e;s<=n;s++){i=r[s],a=i.boundary;var d=a.x2>t.x2?a:t;u===d?h[h.length-1].end=i.end:(h.push({start:i.start,end:i.end,boundary:d}),u=d)}for(r[e].start<t.y1&&(h[0].start=t.y1,h.unshift({start:r[e].start,end:t.y1,boundary:r[e].boundary})),t.y2<r[n].end&&(h[h.length-1].end=t.y2,h.push({start:t.y2,end:r[n].end,boundary:r[n].boundary})),s=e;s<=n;s++)if(i=r[s],a=i.boundary,void 0===a.x2New){var f=!1;for(o=e-1;!f&&o>=0&&r[o].start>=a.y1;o--)f=r[o].boundary===a;for(o=n+1;!f&&o<r.length&&r[o].end<=a.y2;o++)f=r[o].boundary===a;for(o=0;!f&&o<h.length;o++)f=h[o].boundary===a;f||(a.x2New=c)}Array.prototype.splice.apply(r,[e,n-e+1].concat(h))}),r.forEach(function(e){var n=e.boundary;void 0===n.x2New&&(n.x2New=Math.max(t,n.x2))})}function h(t,e,n,r,i){this._textContent=t,this._container=e,this._viewport=n,this._textDivs=r||[],this._textDivProperties=new WeakMap,this._renderingDone=!1,this._canceled=!1,this._capability=s(),this._renderTimer=null,this._bounds=[],this._enhanceTextSelection=!!i}function u(t){var e=new h(t.textContent,t.container,t.viewport,t.textDivs,t.enhanceTextSelection);return e._render(t.timeout),e}var d=1e5,f=/\S/,p=["left: ",0,"px; top: ",0,"px; font-size: ",0,"px; font-family: ","",";"];return h.prototype={get promise(){return this._capability.promise},cancel:function(){this._canceled=!0,null!==this._renderTimer&&(clearTimeout(this._renderTimer),this._renderTimer=null),this._capability.reject("canceled")},_render:function(t){for(var r=this._textContent.items,i=this._textContent.styles,a=0,s=r.length;a<s;a++)e(this,r[a],i);if(t){var o=this;this._renderTimer=setTimeout(function(){n(o),o._renderTimer=null},t)}else n(this)},expandTextDivs:function(t){if(this._enhanceTextSelection&&this._renderingDone){null!==this._bounds&&(r(this),this._bounds=null);for(var e=0,n=this._textDivs.length;e<n;e++){var i=this._textDivs[e],a=this._textDivProperties.get(i);if(!a.isWhitespace)if(t){var s="",c="";1!==a.scale&&(s="scaleX("+a.scale+")"),0!==a.angle&&(s="rotate("+a.angle+"deg) "+s),0!==a.paddingLeft&&(c+=" padding-left: "+a.paddingLeft/a.scale+"px;",s+=" translateX("+-a.paddingLeft/a.scale+"px)"),0!==a.paddingTop&&(c+=" padding-top: "+a.paddingTop+"px;",s+=" translateY("+-a.paddingTop+"px)"),0!==a.paddingRight&&(c+=" padding-right: "+a.paddingRight/a.scale+"px;"),0!==a.paddingBottom&&(c+=" padding-bottom: "+a.paddingBottom+"px;"),""!==c&&i.setAttribute("style",a.style+c),""!==s&&o.setProp("transform",i,s)}else i.style.padding=0,o.setProp("transform",i,a.originalTransform||"")}}}},u}();e.renderTextLayer=l},function(t,e,n){"use strict";var r;r=function(){return this}();try{r=r||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(r=window)}t.exports=r},function(t,e,n){"use strict";function r(t){return t.replace(/>\\376\\377([^<]+)/g,function(t,e){for(var n=e.replace(/\\([0-3])([0-7])([0-7])/g,function(t,e,n,r){return String.fromCharCode(64*e+8*n+1*r)}),r="",i=0;i<n.length;i+=2){var a=256*n.charCodeAt(i)+n.charCodeAt(i+1);r+=a>=32&&a<127&&60!==a&&62!==a&&38!==a?String.fromCharCode(a):"&#x"+(65536+a).toString(16).substring(1)+";"}return">"+r})}function i(t){if("string"==typeof t){t=r(t);t=(new DOMParser).parseFromString(t,"application/xml")}else t instanceof Document||s("Metadata: Invalid metadata object");this.metaDocument=t,this.metadata=Object.create(null),this.parse()}var a=n(0),s=a.error;i.prototype={parse:function(){var t=this.metaDocument,e=t.documentElement;if("rdf:rdf"!==e.nodeName.toLowerCase())for(e=e.firstChild;e&&"rdf:rdf"!==e.nodeName.toLowerCase();)e=e.nextSibling;var n=e?e.nodeName.toLowerCase():null;if(e&&"rdf:rdf"===n&&e.hasChildNodes()){var r,i,a,s,o,c,l,h=e.childNodes;for(s=0,c=h.length;s<c;s++)if(r=h[s],"rdf:description"===r.nodeName.toLowerCase())for(o=0,l=r.childNodes.length;o<l;o++)"#text"!==r.childNodes[o].nodeName.toLowerCase()&&(i=r.childNodes[o],a=i.nodeName.toLowerCase(),this.metadata[a]=i.textContent.trim())}},get:function(t){return this.metadata[t]||null},has:function(t){return void 0!==this.metadata[t]}},e.Metadata=i},function(t,e,n){"use strict";var r=n(0),i=n(1),a=r.shadow,s=i.getDefaultSetting,o=function(){function t(t,e,n){var r=t.createShader(n);if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){var i=t.getShaderInfoLog(r);throw new Error("Error during shader compilation: "+i)}return r}function e(e,n){return t(e,n,e.VERTEX_SHADER)}function n(e,n){return t(e,n,e.FRAGMENT_SHADER)}function r(t,e){for(var n=t.createProgram(),r=0,i=e.length;r<i;++r)t.attachShader(n,e[r]);if(t.linkProgram(n),!t.getProgramParameter(n,t.LINK_STATUS)){var a=t.getProgramInfoLog(n);throw new Error("Error during program linking: "+a)}return n}function i(t,e,n){t.activeTexture(n);var r=t.createTexture();return t.bindTexture(t.TEXTURE_2D,r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}function o(){f||(p=document.createElement("canvas"),f=p.getContext("webgl",{premultipliedalpha:!1}))}function c(){var t,i;o(),t=p,p=null,i=f,f=null;var a=e(i,g),s=n(i,m),c=r(i,[a,s]);i.useProgram(c);var l={};l.gl=i,l.canvas=t,l.resolutionLocation=i.getUniformLocation(c,"u_resolution"),l.positionLocation=i.getAttribLocation(c,"a_position"),l.backdropLocation=i.getUniformLocation(c,"u_backdrop"),l.subtypeLocation=i.getUniformLocation(c,"u_subtype");var h=i.getAttribLocation(c,"a_texCoord"),u=i.getUniformLocation(c,"u_image"),d=i.getUniformLocation(c,"u_mask"),v=i.createBuffer();i.bindBuffer(i.ARRAY_BUFFER,v),i.bufferData(i.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),i.STATIC_DRAW),i.enableVertexAttribArray(h),i.vertexAttribPointer(h,2,i.FLOAT,!1,0,0),i.uniform1i(u,0),i.uniform1i(d,1),A=l}function l(t,e,n){var r=t.width,a=t.height;A||c();var s=A,o=s.canvas,l=s.gl;o.width=r,o.height=a,l.viewport(0,0,l.drawingBufferWidth,l.drawingBufferHeight),l.uniform2f(s.resolutionLocation,r,a),n.backdrop?l.uniform4f(s.resolutionLocation,n.backdrop[0],n.backdrop[1],n.backdrop[2],1):l.uniform4f(s.resolutionLocation,0,0,0,0),l.uniform1i(s.subtypeLocation,"Luminosity"===n.subtype?1:0);var h=i(l,t,l.TEXTURE0),u=i(l,e,l.TEXTURE1),d=l.createBuffer();return l.bindBuffer(l.ARRAY_BUFFER,d),l.bufferData(l.ARRAY_BUFFER,new Float32Array([0,0,r,0,0,a,0,a,r,0,r,a]),l.STATIC_DRAW),l.enableVertexAttribArray(s.positionLocation),l.vertexAttribPointer(s.positionLocation,2,l.FLOAT,!1,0,0),l.clearColor(0,0,0,0),l.enable(l.BLEND),l.blendFunc(l.ONE,l.ONE_MINUS_SRC_ALPHA),l.clear(l.COLOR_BUFFER_BIT),l.drawArrays(l.TRIANGLES,0,6),l.flush(),l.deleteTexture(h),l.deleteTexture(u),l.deleteBuffer(d),o}function h(){var t,i;o(),t=p,p=null,i=f,f=null;var a=e(i,v),s=n(i,b),c=r(i,[a,s]);i.useProgram(c);var l={};l.gl=i,l.canvas=t,l.resolutionLocation=i.getUniformLocation(c,"u_resolution"),l.scaleLocation=i.getUniformLocation(c,"u_scale"),l.offsetLocation=i.getUniformLocation(c,"u_offset"),l.positionLocation=i.getAttribLocation(c,"a_position"),l.colorLocation=i.getAttribLocation(c,"a_color"),y=l}function u(t,e,n,r,i){y||h();var a=y,s=a.canvas,o=a.gl;s.width=t,s.height=e,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.uniform2f(a.resolutionLocation,t,e);var c,l,u,d=0;for(c=0,l=r.length;c<l;c++)switch(r[c].type){case"lattice":u=r[c].coords.length/r[c].verticesPerRow|0,d+=(u-1)*(r[c].verticesPerRow-1)*6;break;case"triangles":d+=r[c].coords.length}var f=new Float32Array(2*d),p=new Uint8Array(3*d),g=i.coords,m=i.colors,A=0,v=0;for(c=0,l=r.length;c<l;c++){var b=r[c],x=b.coords,S=b.colors;switch(b.type){case"lattice":var w=b.verticesPerRow;u=x.length/w|0;for(var k=1;k<u;k++)for(var C=k*w+1,_=1;_<w;_++,C++)f[A]=g[x[C-w-1]],f[A+1]=g[x[C-w-1]+1],f[A+2]=g[x[C-w]],f[A+3]=g[x[C-w]+1],f[A+4]=g[x[C-1]],f[A+5]=g[x[C-1]+1],p[v]=m[S[C-w-1]],p[v+1]=m[S[C-w-1]+1],p[v+2]=m[S[C-w-1]+2],p[v+3]=m[S[C-w]],p[v+4]=m[S[C-w]+1],p[v+5]=m[S[C-w]+2],p[v+6]=m[S[C-1]],p[v+7]=m[S[C-1]+1],p[v+8]=m[S[C-1]+2],f[A+6]=f[A+2],f[A+7]=f[A+3],f[A+8]=f[A+4],f[A+9]=f[A+5],f[A+10]=g[x[C]],f[A+11]=g[x[C]+1],p[v+9]=p[v+3],p[v+10]=p[v+4],p[v+11]=p[v+5],p[v+12]=p[v+6],p[v+13]=p[v+7],p[v+14]=p[v+8],p[v+15]=m[S[C]],p[v+16]=m[S[C]+1],p[v+17]=m[S[C]+2],A+=12,v+=18;break;case"triangles":for(var T=0,P=x.length;T<P;T++)f[A]=g[x[T]],f[A+1]=g[x[T]+1],p[v]=m[S[T]],p[v+1]=m[S[T]+1],p[v+2]=m[S[T]+2],A+=2,v+=3}}n?o.clearColor(n[0]/255,n[1]/255,n[2]/255,1):o.clearColor(0,0,0,0),o.clear(o.COLOR_BUFFER_BIT);var L=o.createBuffer();o.bindBuffer(o.ARRAY_BUFFER,L),o.bufferData(o.ARRAY_BUFFER,f,o.STATIC_DRAW),o.enableVertexAttribArray(a.positionLocation),o.vertexAttribPointer(a.positionLocation,2,o.FLOAT,!1,0,0);var E=o.createBuffer();return o.bindBuffer(o.ARRAY_BUFFER,E),o.bufferData(o.ARRAY_BUFFER,p,o.STATIC_DRAW),o.enableVertexAttribArray(a.colorLocation),o.vertexAttribPointer(a.colorLocation,3,o.UNSIGNED_BYTE,!1,0,0),o.uniform2f(a.scaleLocation,i.scaleX,i.scaleY),o.uniform2f(a.offsetLocation,i.offsetX,i.offsetY),o.drawArrays(o.TRIANGLES,0,d),o.flush(),o.deleteBuffer(L),o.deleteBuffer(E),s}function d(){A&&A.canvas&&(A.canvas.width=0,A.canvas.height=0),y&&y.canvas&&(y.canvas.width=0,y.canvas.height=0),A=null,y=null} var f,p,g=" attribute vec2 a_position; attribute vec2 a_texCoord; uniform vec2 u_resolution; varying vec2 v_texCoord; void main() { vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); v_texCoord = a_texCoord; } ",m=" precision mediump float; uniform vec4 u_backdrop; uniform int u_subtype; uniform sampler2D u_image; uniform sampler2D u_mask; varying vec2 v_texCoord; void main() { vec4 imageColor = texture2D(u_image, v_texCoord); vec4 maskColor = texture2D(u_mask, v_texCoord); if (u_backdrop.a > 0.0) { maskColor.rgb = maskColor.rgb * maskColor.a + u_backdrop.rgb * (1.0 - maskColor.a); } float lum; if (u_subtype == 0) { lum = maskColor.a; } else { lum = maskColor.r * 0.3 + maskColor.g * 0.59 + maskColor.b * 0.11; } imageColor.a *= lum; imageColor.rgb *= imageColor.a; gl_FragColor = imageColor; } ",A=null,v=" attribute vec2 a_position; attribute vec3 a_color; uniform vec2 u_resolution; uniform vec2 u_scale; uniform vec2 u_offset; varying vec4 v_color; void main() { vec2 position = (a_position + u_offset) * u_scale; vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); v_color = vec4(a_color / 255.0, 1.0); } ",b=" precision mediump float; varying vec4 v_color; void main() { gl_FragColor = v_color; } ",y=null;return{get isEnabled(){if(s("disableWebGL"))return!1;var t=!1;try{o(),t=!!f}catch(t){}return a(this,"isEnabled",t)},composeSMask:l,drawFigures:u,clear:d}}();e.WebGLUtils=o},function(t,e,n){"use strict";var r=n(0),i=n(1),a=n(3),s=n(2),o=n(5),c=n(7),l=n(4),h=r.globalScope,u=r.deprecated,d=r.warn,f=i.LinkTarget,p=i.DEFAULT_LINK_REL,g="undefined"==typeof window;h.PDFJS||(h.PDFJS={});var m=h.PDFJS;m.version="1.8.199",m.build="74b31ab1",m.pdfBug=!1,void 0!==m.verbosity&&r.setVerbosityLevel(m.verbosity),delete m.verbosity,Object.defineProperty(m,"verbosity",{get:function(){return r.getVerbosityLevel()},set:function(t){r.setVerbosityLevel(t)},enumerable:!0,configurable:!0}),m.VERBOSITY_LEVELS=r.VERBOSITY_LEVELS,m.OPS=r.OPS,m.UNSUPPORTED_FEATURES=r.UNSUPPORTED_FEATURES,m.isValidUrl=i.isValidUrl,m.shadow=r.shadow,m.createBlob=r.createBlob,m.createObjectURL=function(t,e){return r.createObjectURL(t,e,m.disableCreateObjectURL)},Object.defineProperty(m,"isLittleEndian",{configurable:!0,get:function(){var t=r.isLittleEndian();return r.shadow(m,"isLittleEndian",t)}}),m.removeNullCharacters=r.removeNullCharacters,m.PasswordResponses=r.PasswordResponses,m.PasswordException=r.PasswordException,m.UnknownErrorException=r.UnknownErrorException,m.InvalidPDFException=r.InvalidPDFException,m.MissingPDFException=r.MissingPDFException,m.UnexpectedResponseException=r.UnexpectedResponseException,m.Util=r.Util,m.PageViewport=r.PageViewport,m.createPromiseCapability=r.createPromiseCapability,m.maxImageSize=void 0===m.maxImageSize?-1:m.maxImageSize,m.cMapUrl=void 0===m.cMapUrl?null:m.cMapUrl,m.cMapPacked=void 0!==m.cMapPacked&&m.cMapPacked,m.disableFontFace=void 0!==m.disableFontFace&&m.disableFontFace,m.imageResourcesPath=void 0===m.imageResourcesPath?"":m.imageResourcesPath,m.disableWorker=void 0!==m.disableWorker&&m.disableWorker,m.workerSrc=void 0===m.workerSrc?null:m.workerSrc,m.workerPort=void 0===m.workerPort?null:m.workerPort,m.disableRange=void 0!==m.disableRange&&m.disableRange,m.disableStream=void 0!==m.disableStream&&m.disableStream,m.disableAutoFetch=void 0!==m.disableAutoFetch&&m.disableAutoFetch,m.pdfBug=void 0!==m.pdfBug&&m.pdfBug,m.postMessageTransfers=void 0===m.postMessageTransfers||m.postMessageTransfers,m.disableCreateObjectURL=void 0!==m.disableCreateObjectURL&&m.disableCreateObjectURL,m.disableWebGL=void 0===m.disableWebGL||m.disableWebGL,m.externalLinkTarget=void 0===m.externalLinkTarget?f.NONE:m.externalLinkTarget,m.externalLinkRel=void 0===m.externalLinkRel?p:m.externalLinkRel,m.isEvalSupported=void 0===m.isEvalSupported||m.isEvalSupported,m.pdfjsNext=void 0!==m.pdfjsNext&&m.pdfjsNext;var A=m.openExternalLinksInNewWindow;delete m.openExternalLinksInNewWindow,Object.defineProperty(m,"openExternalLinksInNewWindow",{get:function(){return m.externalLinkTarget===f.BLANK},set:function(t){if(t&&u('PDFJS.openExternalLinksInNewWindow, please use "PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.'),m.externalLinkTarget!==f.NONE)return void d("PDFJS.externalLinkTarget is already initialized");m.externalLinkTarget=t?f.BLANK:f.NONE},enumerable:!0,configurable:!0}),A&&(m.openExternalLinksInNewWindow=A),m.getDocument=a.getDocument,m.PDFDataRangeTransport=a.PDFDataRangeTransport,m.PDFWorker=a.PDFWorker,Object.defineProperty(m,"hasCanvasTypedArrays",{configurable:!0,get:function(){var t=i.hasCanvasTypedArrays();return r.shadow(m,"hasCanvasTypedArrays",t)}}),m.CustomStyle=i.CustomStyle,m.LinkTarget=f,m.addLinkAttributes=i.addLinkAttributes,m.getFilenameFromUrl=i.getFilenameFromUrl,m.isExternalLinkTargetSet=i.isExternalLinkTargetSet,m.AnnotationLayer=s.AnnotationLayer,m.renderTextLayer=o.renderTextLayer,m.Metadata=c.Metadata,m.SVGGraphics=l.SVGGraphics,m.UnsupportedManager=a._UnsupportedManager,e.globalScope=h,e.isWorker=g,e.PDFJS=h.PDFJS},function(t,e,n){"use strict";function r(t){t.mozCurrentTransform||(t._originalSave=t.save,t._originalRestore=t.restore,t._originalRotate=t.rotate,t._originalScale=t.scale,t._originalTranslate=t.translate,t._originalTransform=t.transform,t._originalSetTransform=t.setTransform,t._transformMatrix=t._transformMatrix||[1,0,0,1,0,0],t._transformStack=[],Object.defineProperty(t,"mozCurrentTransform",{get:function(){return this._transformMatrix}}),Object.defineProperty(t,"mozCurrentTransformInverse",{get:function(){var t=this._transformMatrix,e=t[0],n=t[1],r=t[2],i=t[3],a=t[4],s=t[5],o=e*i-n*r,c=n*r-e*i;return[i/o,n/c,r/c,e/o,(i*a-r*s)/c,(n*a-e*s)/o]}}),t.save=function(){var t=this._transformMatrix;this._transformStack.push(t),this._transformMatrix=t.slice(0,6),this._originalSave()},t.restore=function(){var t=this._transformStack.pop();t&&(this._transformMatrix=t,this._originalRestore())},t.translate=function(t,e){var n=this._transformMatrix;n[4]=n[0]*t+n[2]*e+n[4],n[5]=n[1]*t+n[3]*e+n[5],this._originalTranslate(t,e)},t.scale=function(t,e){var n=this._transformMatrix;n[0]=n[0]*t,n[1]=n[1]*t,n[2]=n[2]*e,n[3]=n[3]*e,this._originalScale(t,e)},t.transform=function(e,n,r,i,a,s){var o=this._transformMatrix;this._transformMatrix=[o[0]*e+o[2]*n,o[1]*e+o[3]*n,o[0]*r+o[2]*i,o[1]*r+o[3]*i,o[0]*a+o[2]*s+o[4],o[1]*a+o[3]*s+o[5]],t._originalTransform(e,n,r,i,a,s)},t.setTransform=function(e,n,r,i,a,s){this._transformMatrix=[e,n,r,i,a,s],t._originalSetTransform(e,n,r,i,a,s)},t.rotate=function(t){var e=Math.cos(t),n=Math.sin(t),r=this._transformMatrix;this._transformMatrix=[r[0]*e+r[2]*n,r[1]*e+r[3]*n,r[0]*-n+r[2]*e,r[1]*-n+r[3]*e,r[4],r[5]],this._originalRotate(t)})}function i(t){var e,n,r,i,a=t.width,s=t.height,o=a+1,c=new Uint8Array(o*(s+1)),l=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),h=a+7&-8,u=t.data,d=new Uint8Array(h*s),f=0;for(e=0,i=u.length;e<i;e++)for(var p=128,g=u[e];p>0;)d[f++]=g&p?0:255,p>>=1;var m=0;for(f=0,0!==d[f]&&(c[0]=1,++m),n=1;n<a;n++)d[f]!==d[f+1]&&(c[n]=d[f]?2:1,++m),f++;for(0!==d[f]&&(c[n]=2,++m),e=1;e<s;e++){f=e*h,r=e*o,d[f-h]!==d[f]&&(c[r]=d[f]?1:8,++m);var A=(d[f]?4:0)+(d[f-h]?8:0);for(n=1;n<a;n++)A=(A>>2)+(d[f+1]?4:0)+(d[f-h+1]?8:0),l[A]&&(c[r+n]=l[A],++m),f++;if(d[f-h]!==d[f]&&(c[r+n]=d[f]?2:4,++m),m>1e3)return null}for(f=h*(s-1),r=e*o,0!==d[f]&&(c[r]=8,++m),n=1;n<a;n++)d[f]!==d[f+1]&&(c[r+n]=d[f]?4:8,++m),f++;if(0!==d[f]&&(c[r+n]=4,++m),m>1e3)return null;var v=new Int32Array([0,o,-1,0,-o,0,0,0,1]),b=[];for(e=0;m&&e<=s;e++){for(var y=e*o,x=y+a;y<x&&!c[y];)y++;if(y!==x){var S,w=[y%o,e],k=c[y],C=y;do{var _=v[k];do{y+=_}while(!c[y]);S=c[y],5!==S&&10!==S?(k=S,c[y]=0):(k=S&51*k>>4,c[y]&=k>>2|k<<2),w.push(y%o),w.push(y/o|0),--m}while(C!==y);b.push(w),--e}}return function(t){t.save(),t.scale(1/a,-1/s),t.translate(0,-s),t.beginPath();for(var e=0,n=b.length;e<n;e++){var r=b[e];t.moveTo(r[0],r[1]);for(var i=2,o=r.length;i<o;i+=2)t.lineTo(r[i],r[i+1])}t.fill(),t.beginPath(),t.restore()}}var a=n(0),s=n(1),o=n(12),c=n(8),l=a.FONT_IDENTITY_MATRIX,h=a.IDENTITY_MATRIX,u=a.ImageKind,d=a.OPS,f=a.TextRenderingMode,p=a.Uint32ArrayView,g=a.Util,m=a.assert,A=a.info,v=a.isNum,b=a.isArray,y=a.isLittleEndian,x=a.error,S=a.shadow,w=a.warn,k=o.TilingPattern,C=o.getShadingPatternFromIR,_=c.WebGLUtils,T=s.hasCanvasTypedArrays,P=16,L={get value(){return S(L,"value",T())}},E={get value(){return S(E,"value",y())}},R=function(){function t(t){this.canvasFactory=t,this.cache=Object.create(null)}return t.prototype={getCanvas:function(t,e,n,i){var a;return void 0!==this.cache[t]?(a=this.cache[t],this.canvasFactory.reset(a,e,n),a.context.setTransform(1,0,0,1,0,0)):(a=this.canvasFactory.create(e,n),this.cache[t]=a),i&&r(a.context),a},clear:function(){for(var t in this.cache){var e=this.cache[t];this.canvasFactory.destroy(e),delete this.cache[t]}}},t}(),I=function(){function t(t){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=h,this.textMatrixScale=1,this.fontMatrix=l,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=f.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.resumeSMaskCtx=null,this.old=t}return t.prototype={clone:function(){return Object.create(this)},setCurrentPoint:function(t,e){this.x=t,this.y=e}},t}(),F=function(){function t(t,e,n,i,a){this.ctx=t,this.current=new I,this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=e,this.objs=n,this.canvasFactory=i,this.imageLayer=a,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.cachedCanvases=new R(this.canvasFactory),t&&r(t),this.cachedGetSinglePixelWidth=null}function e(t,e){if("undefined"!=typeof ImageData&&e instanceof ImageData)return void t.putImageData(e,0,0);var n,r,i,a,s,o=e.height,c=e.width,l=o%P,h=(o-l)/P,d=0===l?h:h+1,f=t.createImageData(c,P),g=0,m=e.data,A=f.data;if(e.kind===u.GRAYSCALE_1BPP){var v=m.byteLength,b=L.value?new Uint32Array(A.buffer):new p(A),y=b.length,S=c+7>>3,w=4294967295,k=E.value||!L.value?4278190080:255;for(r=0;r<d;r++){for(a=r<h?P:l,n=0,i=0;i<a;i++){for(var C=v-g,_=0,T=C>S?c:8*C-7,R=-8&T,I=0,F=0;_<R;_+=8)F=m[g++],b[n++]=128&F?w:k,b[n++]=64&F?w:k,b[n++]=32&F?w:k,b[n++]=16&F?w:k,b[n++]=8&F?w:k,b[n++]=4&F?w:k,b[n++]=2&F?w:k,b[n++]=1&F?w:k;for(;_<T;_++)0===I&&(F=m[g++],I=128),b[n++]=F&I?w:k,I>>=1}for(;n<y;)b[n++]=0;t.putImageData(f,0,r*P)}}else if(e.kind===u.RGBA_32BPP){for(i=0,s=c*P*4,r=0;r<h;r++)A.set(m.subarray(g,g+s)),g+=s,t.putImageData(f,0,i),i+=P;r<d&&(s=c*l*4,A.set(m.subarray(g,g+s)),t.putImageData(f,0,i))}else if(e.kind===u.RGB_24BPP)for(a=P,s=c*a,r=0;r<d;r++){for(r>=h&&(a=l,s=c*a),n=0,i=s;i--;)A[n++]=m[g++],A[n++]=m[g++],A[n++]=m[g++],A[n++]=255;t.putImageData(f,0,r*P)}else x("bad image kind: "+e.kind)}function n(t,e){for(var n=e.height,r=e.width,i=n%P,a=(n-i)/P,s=0===i?a:a+1,o=t.createImageData(r,P),c=0,l=e.data,h=o.data,u=0;u<s;u++){for(var d=u<a?P:i,f=3,p=0;p<d;p++)for(var g=0,m=0;m<r;m++){if(!g){var A=l[c++];g=128}h[f]=A&g?0:255,f+=4,g>>=1}t.putImageData(o,0,u*P)}}function a(t,e){for(var n=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font"],r=0,i=n.length;r<i;r++){var a=n[r];void 0!==t[a]&&(e[a]=t[a])}void 0!==t.setLineDash&&(e.setLineDash(t.getLineDash()),e.lineDashOffset=t.lineDashOffset)}function s(t,e,n,r){for(var i=t.length,a=3;a<i;a+=4){var s=t[a];if(0===s)t[a-3]=e,t[a-2]=n,t[a-1]=r;else if(s<255){var o=255-s;t[a-3]=t[a-3]*s+e*o>>8,t[a-2]=t[a-2]*s+n*o>>8,t[a-1]=t[a-1]*s+r*o>>8}}}function o(t,e,n){for(var r=t.length,i=3;i<r;i+=4){var a=n?n[t[i]]:t[i];e[i]=e[i]*a*(1/255)|0}}function c(t,e,n){for(var r=t.length,i=3;i<r;i+=4){var a=77*t[i-3]+152*t[i-2]+28*t[i-1];e[i]=n?e[i]*n[a>>8]>>8:e[i]*a>>16}}function y(t,e,n,r,i,a,l){var h,u=!!a,d=u?a[0]:0,f=u?a[1]:0,p=u?a[2]:0;h="Luminosity"===i?c:o;for(var g=Math.min(r,Math.ceil(1048576/n)),m=0;m<r;m+=g){var A=Math.min(g,r-m),v=t.getImageData(0,m,n,A),b=e.getImageData(0,m,n,A);u&&s(v.data,d,f,p),h(v.data,b.data,l),t.putImageData(b,0,m)}}function T(t,e,n){var r=e.canvas,i=e.context;t.setTransform(e.scaleX,0,0,e.scaleY,e.offsetX,e.offsetY);var a=e.backdrop||null;if(!e.transferMap&&_.isEnabled){var s=_.composeSMask(n.canvas,r,{subtype:e.subtype,backdrop:a});return t.setTransform(1,0,0,1,0,0),void t.drawImage(s,e.offsetX,e.offsetY)}y(i,n,r.width,r.height,e.subtype,a,e.transferMap),t.drawImage(r,0,0)}var F=["butt","round","square"],O=["miter","round","bevel"],N={},M={};t.prototype={beginDrawing:function(t,e,n){var r=this.ctx.canvas.width,i=this.ctx.canvas.height;if(this.ctx.save(),this.ctx.fillStyle="rgb(255, 255, 255)",this.ctx.fillRect(0,0,r,i),this.ctx.restore(),n){var a=this.cachedCanvases.getCanvas("transparent",r,i,!0);this.compositeCtx=this.ctx,this.transparentCanvas=a.canvas,this.ctx=a.context,this.ctx.save(),this.ctx.transform.apply(this.ctx,this.compositeCtx.mozCurrentTransform)}this.ctx.save(),t&&this.ctx.transform.apply(this.ctx,t),this.ctx.transform.apply(this.ctx,e.transform),this.baseTransform=this.ctx.mozCurrentTransform.slice(),this.imageLayer&&this.imageLayer.beginLayout()},executeOperatorList:function(t,e,n,r){var i=t.argsArray,a=t.fnArray,s=e||0,o=i.length;if(o===s)return s;for(var c,l=o-s>10&&"function"==typeof n,h=l?Date.now()+15:0,u=0,f=this.commonObjs,p=this.objs;;){if(void 0!==r&&s===r.nextBreakPoint)return r.breakIt(s,n),s;if((c=a[s])!==d.dependency)this[c].apply(this,i[s]);else for(var g=i[s],m=0,A=g.length;m<A;m++){var v=g[m],b="g"===v[0]&&"_"===v[1],y=b?f:p;if(!y.isResolved(v))return y.get(v,n),s}if(++s===o)return s;if(l&&++u>10){if(Date.now()>h)return n(),s;u=0}}},endDrawing:function(){null!==this.current.activeSMask&&this.endSMaskGroup(),this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null),this.cachedCanvases.clear(),_.clear(),this.imageLayer&&this.imageLayer.endLayout()},setLineWidth:function(t){this.current.lineWidth=t,this.ctx.lineWidth=t},setLineCap:function(t){this.ctx.lineCap=F[t]},setLineJoin:function(t){this.ctx.lineJoin=O[t]},setMiterLimit:function(t){this.ctx.miterLimit=t},setDash:function(t,e){var n=this.ctx;void 0!==n.setLineDash&&(n.setLineDash(t),n.lineDashOffset=e)},setRenderingIntent:function(t){},setFlatness:function(t){},setGState:function(t){for(var e=0,n=t.length;e<n;e++){var r=t[e],i=r[0],a=r[1];switch(i){case"LW":this.setLineWidth(a);break;case"LC":this.setLineCap(a);break;case"LJ":this.setLineJoin(a);break;case"ML":this.setMiterLimit(a);break;case"D":this.setDash(a[0],a[1]);break;case"RI":this.setRenderingIntent(a);break;case"FL":this.setFlatness(a);break;case"Font":this.setFont(a[0],a[1]);break;case"CA":this.current.strokeAlpha=r[1];break;case"ca":this.current.fillAlpha=r[1],this.ctx.globalAlpha=r[1];break;case"BM":this.ctx.globalCompositeOperation=a;break;case"SMask":this.current.activeSMask&&(this.stateStack.length>0&&this.stateStack[this.stateStack.length-1].activeSMask===this.current.activeSMask?this.suspendSMaskGroup():this.endSMaskGroup()),this.current.activeSMask=a?this.tempSMask:null,this.current.activeSMask&&this.beginSMaskGroup(),this.tempSMask=null}}},beginSMaskGroup:function(){var t=this.current.activeSMask,e=t.canvas.width,n=t.canvas.height,r="smaskGroupAt"+this.groupLevel,i=this.cachedCanvases.getCanvas(r,e,n,!0),s=this.ctx,o=s.mozCurrentTransform;this.ctx.save();var c=i.context;c.scale(1/t.scaleX,1/t.scaleY),c.translate(-t.offsetX,-t.offsetY),c.transform.apply(c,o),t.startTransformInverse=c.mozCurrentTransformInverse,a(s,c),this.ctx=c,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(s),this.groupLevel++},suspendSMaskGroup:function(){var t=this.ctx;this.groupLevel--,this.ctx=this.groupStack.pop(),T(this.ctx,this.current.activeSMask,t),this.ctx.restore(),this.ctx.save(),a(t,this.ctx),this.current.resumeSMaskCtx=t;var e=g.transform(this.current.activeSMask.startTransformInverse,t.mozCurrentTransform);this.ctx.transform.apply(this.ctx,e),t.save(),t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,t.canvas.width,t.canvas.height),t.restore()},resumeSMaskGroup:function(){var t=this.current.resumeSMaskCtx,e=this.ctx;this.ctx=t,this.groupStack.push(e),this.groupLevel++},endSMaskGroup:function(){var t=this.ctx;this.groupLevel--,this.ctx=this.groupStack.pop(),T(this.ctx,this.current.activeSMask,t),this.ctx.restore(),a(t,this.ctx);var e=g.transform(this.current.activeSMask.startTransformInverse,t.mozCurrentTransform);this.ctx.transform.apply(this.ctx,e)},save:function(){this.ctx.save();var t=this.current;this.stateStack.push(t),this.current=t.clone(),this.current.resumeSMaskCtx=null},restore:function(){this.current.resumeSMaskCtx&&this.resumeSMaskGroup(),null===this.current.activeSMask||0!==this.stateStack.length&&this.stateStack[this.stateStack.length-1].activeSMask===this.current.activeSMask||this.endSMaskGroup(),0!==this.stateStack.length&&(this.current=this.stateStack.pop(),this.ctx.restore(),this.pendingClip=null,this.cachedGetSinglePixelWidth=null)},transform:function(t,e,n,r,i,a){this.ctx.transform(t,e,n,r,i,a),this.cachedGetSinglePixelWidth=null},constructPath:function(t,e){for(var n=this.ctx,r=this.current,i=r.x,a=r.y,s=0,o=0,c=t.length;s<c;s++)switch(0|t[s]){case d.rectangle:i=e[o++],a=e[o++];var l=e[o++],h=e[o++];0===l&&(l=this.getSinglePixelWidth()),0===h&&(h=this.getSinglePixelWidth());var u=i+l,f=a+h;this.ctx.moveTo(i,a),this.ctx.lineTo(u,a),this.ctx.lineTo(u,f),this.ctx.lineTo(i,f),this.ctx.lineTo(i,a),this.ctx.closePath();break;case d.moveTo:i=e[o++],a=e[o++],n.moveTo(i,a);break;case d.lineTo:i=e[o++],a=e[o++],n.lineTo(i,a);break;case d.curveTo:i=e[o+4],a=e[o+5],n.bezierCurveTo(e[o],e[o+1],e[o+2],e[o+3],i,a),o+=6;break;case d.curveTo2:n.bezierCurveTo(i,a,e[o],e[o+1],e[o+2],e[o+3]),i=e[o+2],a=e[o+3],o+=4;break;case d.curveTo3:i=e[o+2],a=e[o+3],n.bezierCurveTo(e[o],e[o+1],i,a,i,a),o+=4;break;case d.closePath:n.closePath()}r.setCurrentPoint(i,a)},closePath:function(){this.ctx.closePath()},stroke:function(t){t=void 0===t||t;var e=this.ctx,n=this.current.strokeColor;e.lineWidth=Math.max(.65*this.getSinglePixelWidth(),this.current.lineWidth),e.globalAlpha=this.current.strokeAlpha,n&&n.hasOwnProperty("type")&&"Pattern"===n.type?(e.save(),e.strokeStyle=n.getPattern(e,this),e.stroke(),e.restore()):e.stroke(),t&&this.consumePath(),e.globalAlpha=this.current.fillAlpha},closeStroke:function(){this.closePath(),this.stroke()},fill:function(t){t=void 0===t||t;var e=this.ctx,n=this.current.fillColor,r=this.current.patternFill,i=!1;r&&(e.save(),this.baseTransform&&e.setTransform.apply(e,this.baseTransform),e.fillStyle=n.getPattern(e,this),i=!0),this.pendingEOFill?(e.fill("evenodd"),this.pendingEOFill=!1):e.fill(),i&&e.restore(),t&&this.consumePath()},eoFill:function(){this.pendingEOFill=!0,this.fill()},fillStroke:function(){this.fill(!1),this.stroke(!1),this.consumePath()},eoFillStroke:function(){this.pendingEOFill=!0,this.fillStroke()},closeFillStroke:function(){this.closePath(),this.fillStroke()},closeEOFillStroke:function(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()},endPath:function(){this.consumePath()},clip:function(){this.pendingClip=N},eoClip:function(){this.pendingClip=M},beginText:function(){this.current.textMatrix=h,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0},endText:function(){var t=this.pendingTextPaths,e=this.ctx;if(void 0===t)return void e.beginPath();e.save(),e.beginPath();for(var n=0;n<t.length;n++){var r=t[n];e.setTransform.apply(e,r.transform),e.translate(r.x,r.y),r.addToPath(e,r.fontSize)}e.restore(),e.clip(),e.beginPath(),delete this.pendingTextPaths},setCharSpacing:function(t){this.current.charSpacing=t},setWordSpacing:function(t){this.current.wordSpacing=t},setHScale:function(t){this.current.textHScale=t/100},setLeading:function(t){this.current.leading=-t},setFont:function(t,e){var n=this.commonObjs.get(t),r=this.current;if(n||x("Can't find font for "+t),r.fontMatrix=n.fontMatrix?n.fontMatrix:l,0!==r.fontMatrix[0]&&0!==r.fontMatrix[3]||w("Invalid font matrix for font "+t),e<0?(e=-e,r.fontDirection=-1):r.fontDirection=1,this.current.font=n,this.current.fontSize=e,!n.isType3Font){var i=n.loadedName||"sans-serif",a=n.black?"900":n.bold?"bold":"normal",s=n.italic?"italic":"normal",o='"'+i+'", '+n.fallbackName,c=e<16?16:e>100?100:e;this.current.fontSizeScale=e/c;var h=s+" "+a+" "+c+"px "+o;this.ctx.font=h}},setTextRenderingMode:function(t){this.current.textRenderingMode=t},setTextRise:function(t){this.current.textRise=t},moveText:function(t,e){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=e},setLeadingMoveText:function(t,e){this.setLeading(-e),this.moveText(t,e)},setTextMatrix:function(t,e,n,r,i,a){this.current.textMatrix=[t,e,n,r,i,a],this.current.textMatrixScale=Math.sqrt(t*t+e*e),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0},nextLine:function(){this.moveText(0,this.current.leading)},paintChar:function(t,e,n){var r,i=this.ctx,a=this.current,s=a.font,o=a.textRenderingMode,c=a.fontSize/a.fontSizeScale,l=o&f.FILL_STROKE_MASK,h=!!(o&f.ADD_TO_PATH_FLAG);if((s.disableFontFace||h)&&(r=s.getPathGenerator(this.commonObjs,t)),s.disableFontFace?(i.save(),i.translate(e,n),i.beginPath(),r(i,c),l!==f.FILL&&l!==f.FILL_STROKE||i.fill(),l!==f.STROKE&&l!==f.FILL_STROKE||i.stroke(),i.restore()):(l!==f.FILL&&l!==f.FILL_STROKE||i.fillText(t,e,n),l!==f.STROKE&&l!==f.FILL_STROKE||i.strokeText(t,e,n)),h){(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:i.mozCurrentTransform,x:e,y:n,fontSize:c,addToPath:r})}},get isFontSubpixelAAEnabled(){var t=this.canvasFactory.create(10,10).context;t.scale(1.5,1),t.fillText("I",0,10);for(var e=t.getImageData(0,0,10,10).data,n=!1,r=3;r<e.length;r+=4)if(e[r]>0&&e[r]<255){n=!0;break}return S(this,"isFontSubpixelAAEnabled",n)},showText:function(t){var e=this.current,n=e.font;if(n.isType3Font)return this.showType3Text(t);var r=e.fontSize;if(0!==r){var i=this.ctx,a=e.fontSizeScale,s=e.charSpacing,o=e.wordSpacing,c=e.fontDirection,l=e.textHScale*c,h=t.length,u=n.vertical,d=u?1:-1,p=n.defaultVMetrics,g=r*e.fontMatrix[0],m=e.textRenderingMode===f.FILL&&!n.disableFontFace;i.save(),i.transform.apply(i,e.textMatrix),i.translate(e.x,e.y+e.textRise),e.patternFill&&(i.fillStyle=e.fillColor.getPattern(i,this)),c>0?i.scale(l,-1):i.scale(l,1);var A=e.lineWidth,b=e.textMatrixScale;if(0===b||0===A){var y=e.textRenderingMode&f.FILL_STROKE_MASK;y!==f.STROKE&&y!==f.FILL_STROKE||(this.cachedGetSinglePixelWidth=null,A=.65*this.getSinglePixelWidth())}else A/=b;1!==a&&(i.scale(a,a),A/=a),i.lineWidth=A;var x,S=0;for(x=0;x<h;++x){var w=t[x];if(v(w))S+=d*w*r/1e3;else{var k,C,_,T,P=!1,L=(w.isSpace?o:0)+s,E=w.fontChar,R=w.accent,I=w.width;if(u){var F,O,N;F=w.vmetric||p,O=w.vmetric?F[1]:.5*I,O=-O*g,N=F[2]*g,I=F?-F[0]:I,k=O/a,C=(S+N)/a}else k=S/a,C=0;if(n.remeasure&&I>0){var M=1e3*i.measureText(E).width/r*a;if(I<M&&this.isFontSubpixelAAEnabled){var D=I/M;P=!0,i.save(),i.scale(D,1),k/=D}else I!==M&&(k+=(I-M)/2e3*r/a)}(w.isInFont||n.missingFile)&&(m&&!R?i.fillText(E,k,C):(this.paintChar(E,k,C),R&&(_=k+R.offset.x/a,T=C-R.offset.y/a,this.paintChar(R.fontChar,_,T))));S+=I*g+L*c,P&&i.restore()}}u?e.y-=S*l:e.x+=S*l,i.restore()}},showType3Text:function(t){var e,n,r,i,a=this.ctx,s=this.current,o=s.font,c=s.fontSize,h=s.fontDirection,u=o.vertical?1:-1,d=s.charSpacing,p=s.wordSpacing,m=s.textHScale*h,A=s.fontMatrix||l,b=t.length,y=s.textRenderingMode===f.INVISIBLE;if(!y&&0!==c){for(this.cachedGetSinglePixelWidth=null,a.save(),a.transform.apply(a,s.textMatrix),a.translate(s.x,s.y),a.scale(m,h),e=0;e<b;++e)if(n=t[e],v(n))i=u*n*c/1e3,this.ctx.translate(i,0),s.x+=i*m;else{var x=(n.isSpace?p:0)+d,S=o.charProcOperatorList[n.operatorListId];if(S){this.processingType3=n,this.save(),a.scale(c,c),a.transform.apply(a,A),this.executeOperatorList(S),this.restore();var k=g.applyTransform([n.width,0],A);r=k[0]*c+x,a.translate(r,0),s.x+=r*m}else w('Type3 character "'+n.operatorListId+'" is not available')}a.restore(),this.processingType3=null}},setCharWidth:function(t,e){},setCharWidthAndBounds:function(t,e,n,r,i,a){this.ctx.rect(n,r,i-n,a-r),this.clip(),this.endPath()},getColorN_Pattern:function(e){var n;if("TilingPattern"===e[0]){var r=e[1],i=this.baseTransform||this.ctx.mozCurrentTransform.slice(),a=this,s={createCanvasGraphics:function(e){return new t(e,a.commonObjs,a.objs,a.canvasFactory)}};n=new k(e,r,this.ctx,s,i)}else n=C(e);return n},setStrokeColorN:function(){this.current.strokeColor=this.getColorN_Pattern(arguments)},setFillColorN:function(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0},setStrokeRGBColor:function(t,e,n){var r=g.makeCssRgb(t,e,n);this.ctx.strokeStyle=r,this.current.strokeColor=r},setFillRGBColor:function(t,e,n){var r=g.makeCssRgb(t,e,n);this.ctx.fillStyle=r,this.current.fillColor=r,this.current.patternFill=!1},shadingFill:function(t){var e=this.ctx;this.save();var n=C(t);e.fillStyle=n.getPattern(e,this,!0);var r=e.mozCurrentTransformInverse;if(r){var i=e.canvas,a=i.width,s=i.height,o=g.applyTransform([0,0],r),c=g.applyTransform([0,s],r),l=g.applyTransform([a,0],r),h=g.applyTransform([a,s],r),u=Math.min(o[0],c[0],l[0],h[0]),d=Math.min(o[1],c[1],l[1],h[1]),f=Math.max(o[0],c[0],l[0],h[0]),p=Math.max(o[1],c[1],l[1],h[1]);this.ctx.fillRect(u,d,f-u,p-d)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.restore()},beginInlineImage:function(){x("Should not call beginInlineImage")},beginImageData:function(){x("Should not call beginImageData")},paintFormXObjectBegin:function(t,e){if(this.save(),this.baseTransformStack.push(this.baseTransform),b(t)&&6===t.length&&this.transform.apply(this,t),this.baseTransform=this.ctx.mozCurrentTransform,b(e)&&4===e.length){var n=e[2]-e[0],r=e[3]-e[1];this.ctx.rect(e[0],e[1],n,r),this.clip(),this.endPath()}},paintFormXObjectEnd:function(){this.restore(),this.baseTransform=this.baseTransformStack.pop()},beginGroup:function(t){this.save();var e=this.ctx;t.isolated||A("TODO: Support non-isolated groups."),t.knockout&&w("Knockout groups not supported.");var n=e.mozCurrentTransform;t.matrix&&e.transform.apply(e,t.matrix),m(t.bbox,"Bounding box is required.");var r=g.getAxialAlignedBoundingBox(t.bbox,e.mozCurrentTransform),i=[0,0,e.canvas.width,e.canvas.height];r=g.intersect(r,i)||[0,0,0,0];var s=Math.floor(r[0]),o=Math.floor(r[1]),c=Math.max(Math.ceil(r[2])-s,1),l=Math.max(Math.ceil(r[3])-o,1),h=1,u=1;c>4096&&(h=c/4096,c=4096),l>4096&&(u=l/4096,l=4096);var d="groupAt"+this.groupLevel;t.smask&&(d+="_smask_"+this.smaskCounter++%2);var f=this.cachedCanvases.getCanvas(d,c,l,!0),p=f.context;p.scale(1/h,1/u),p.translate(-s,-o),p.transform.apply(p,n),t.smask?this.smaskStack.push({canvas:f.canvas,context:p,offsetX:s,offsetY:o,scaleX:h,scaleY:u,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null}):(e.setTransform(1,0,0,1,0,0),e.translate(s,o),e.scale(h,u)),a(e,p),this.ctx=p,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(e),this.groupLevel++,this.current.activeSMask=null},endGroup:function(t){this.groupLevel--;var e=this.ctx;this.ctx=this.groupStack.pop(),void 0!==this.ctx.imageSmoothingEnabled?this.ctx.imageSmoothingEnabled=!1:this.ctx.mozImageSmoothingEnabled=!1,t.smask?this.tempSMask=this.smaskStack.pop():this.ctx.drawImage(e.canvas,0,0),this.restore()},beginAnnotations:function(){this.save(),this.current=new I,this.baseTransform&&this.ctx.setTransform.apply(this.ctx,this.baseTransform)},endAnnotations:function(){this.restore()},beginAnnotation:function(t,e,n){if(this.save(),b(t)&&4===t.length){var r=t[2]-t[0],i=t[3]-t[1];this.ctx.rect(t[0],t[1],r,i),this.clip(),this.endPath()}this.transform.apply(this,e),this.transform.apply(this,n)},endAnnotation:function(){this.restore()},paintJpegXObject:function(t,e,n){var r=this.objs.get(t);if(!r)return void w("Dependent image isn't ready yet");this.save();var i=this.ctx;if(i.scale(1/e,-1/n),i.drawImage(r,0,0,r.width,r.height,0,-n,e,n),this.imageLayer){var a=i.mozCurrentTransformInverse,s=this.getCanvasPosition(0,0);this.imageLayer.appendImage({objId:t,left:s[0],top:s[1],width:e/a[0],height:n/a[3]})}this.restore()},paintImageMaskXObject:function(t){var e=this.ctx,r=t.width,a=t.height,s=this.current.fillColor,o=this.current.patternFill,c=this.processingType3;if(c&&void 0===c.compiled&&(c.compiled=r<=1e3&&a<=1e3?i({data:t.data,width:r,height:a}):null),c&&c.compiled)return void c.compiled(e);var l=this.cachedCanvases.getCanvas("maskCanvas",r,a),h=l.context;h.save(),n(h,t),h.globalCompositeOperation="source-in",h.fillStyle=o?s.getPattern(h,this):s,h.fillRect(0,0,r,a),h.restore(),this.paintInlineImageXObject(l.canvas)},paintImageMaskXObjectRepeat:function(t,e,r,i){ var a=t.width,s=t.height,o=this.current.fillColor,c=this.current.patternFill,l=this.cachedCanvases.getCanvas("maskCanvas",a,s),h=l.context;h.save(),n(h,t),h.globalCompositeOperation="source-in",h.fillStyle=c?o.getPattern(h,this):o,h.fillRect(0,0,a,s),h.restore();for(var u=this.ctx,d=0,f=i.length;d<f;d+=2)u.save(),u.transform(e,0,0,r,i[d],i[d+1]),u.scale(1,-1),u.drawImage(l.canvas,0,0,a,s,0,-1,1,1),u.restore()},paintImageMaskXObjectGroup:function(t){for(var e=this.ctx,r=this.current.fillColor,i=this.current.patternFill,a=0,s=t.length;a<s;a++){var o=t[a],c=o.width,l=o.height,h=this.cachedCanvases.getCanvas("maskCanvas",c,l),u=h.context;u.save(),n(u,o),u.globalCompositeOperation="source-in",u.fillStyle=i?r.getPattern(u,this):r,u.fillRect(0,0,c,l),u.restore(),e.save(),e.transform.apply(e,o.transform),e.scale(1,-1),e.drawImage(h.canvas,0,0,c,l,0,-1,1,1),e.restore()}},paintImageXObject:function(t){var e=this.objs.get(t);if(!e)return void w("Dependent image isn't ready yet");this.paintInlineImageXObject(e)},paintImageXObjectRepeat:function(t,e,n,r){var i=this.objs.get(t);if(!i)return void w("Dependent image isn't ready yet");for(var a=i.width,s=i.height,o=[],c=0,l=r.length;c<l;c+=2)o.push({transform:[e,0,0,n,r[c],r[c+1]],x:0,y:0,w:a,h:s});this.paintInlineImageXObjectGroup(i,o)},paintInlineImageXObject:function(t){var n=t.width,r=t.height,i=this.ctx;this.save(),i.scale(1/n,-1/r);var a,s,o=i.mozCurrentTransformInverse,c=o[0],l=o[1],h=Math.max(Math.sqrt(c*c+l*l),1),u=o[2],d=o[3],f=Math.max(Math.sqrt(u*u+d*d),1);if(t instanceof HTMLElement||!t.data)a=t;else{s=this.cachedCanvases.getCanvas("inlineImage",n,r);var p=s.context;e(p,t),a=s.canvas}for(var g=n,m=r,A="prescale1";h>2&&g>1||f>2&&m>1;){var v=g,b=m;h>2&&g>1&&(v=Math.ceil(g/2),h/=g/v),f>2&&m>1&&(b=Math.ceil(m/2),f/=m/b),s=this.cachedCanvases.getCanvas(A,v,b),p=s.context,p.clearRect(0,0,v,b),p.drawImage(a,0,0,g,m,0,0,v,b),a=s.canvas,g=v,m=b,A="prescale1"===A?"prescale2":"prescale1"}if(i.drawImage(a,0,0,g,m,0,-r,n,r),this.imageLayer){var y=this.getCanvasPosition(0,-r);this.imageLayer.appendImage({imgData:t,left:y[0],top:y[1],width:n/o[0],height:r/o[3]})}this.restore()},paintInlineImageXObjectGroup:function(t,n){var r=this.ctx,i=t.width,a=t.height,s=this.cachedCanvases.getCanvas("inlineImage",i,a);e(s.context,t);for(var o=0,c=n.length;o<c;o++){var l=n[o];if(r.save(),r.transform.apply(r,l.transform),r.scale(1,-1),r.drawImage(s.canvas,l.x,l.y,l.w,l.h,0,-1,1,1),this.imageLayer){var h=this.getCanvasPosition(l.x,l.y);this.imageLayer.appendImage({imgData:t,left:h[0],top:h[1],width:i,height:a})}r.restore()}},paintSolidColorImageMask:function(){this.ctx.fillRect(0,0,1,1)},paintXObject:function(){w("Unsupported 'paintXObject' command.")},markPoint:function(t){},markPointProps:function(t,e){},beginMarkedContent:function(t){},beginMarkedContentProps:function(t,e){},endMarkedContent:function(){},beginCompat:function(){},endCompat:function(){},consumePath:function(){var t=this.ctx;this.pendingClip&&(this.pendingClip===M?t.clip("evenodd"):t.clip(),this.pendingClip=null),t.beginPath()},getSinglePixelWidth:function(t){if(null===this.cachedGetSinglePixelWidth){this.ctx.save();var e=this.ctx.mozCurrentTransformInverse;this.ctx.restore(),this.cachedGetSinglePixelWidth=Math.sqrt(Math.max(e[0]*e[0]+e[1]*e[1],e[2]*e[2]+e[3]*e[3]))}return this.cachedGetSinglePixelWidth},getCanvasPosition:function(t,e){var n=this.ctx.mozCurrentTransform;return[n[0]*t+n[2]*e+n[4],n[1]*t+n[3]*e+n[5]]}};for(var D in d)t.prototype[d[D]]=t.prototype[D];return t}();e.CanvasGraphics=F},function(t,e,n){"use strict";function r(t){this.docId=t,this.styleElement=null,this.nativeFontFaces=[],this.loadTestFontId=0,this.loadingContext={requests:[],nextRequestId:0}}var i=n(0),a=i.assert,s=i.bytesToString,o=i.string32,c=i.shadow,l=i.warn;r.prototype={insertRule:function(t){var e=this.styleElement;e||(e=this.styleElement=document.createElement("style"),e.id="PDFJS_FONT_STYLE_TAG_"+this.docId,document.documentElement.getElementsByTagName("head")[0].appendChild(e));var n=e.sheet;n.insertRule(t,n.cssRules.length)},clear:function(){this.styleElement&&(this.styleElement.remove(),this.styleElement=null),this.nativeFontFaces.forEach(function(t){document.fonts.delete(t)}),this.nativeFontFaces.length=0}};var h=function(){return atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==")};Object.defineProperty(r.prototype,"loadTestFont",{get:function(){return c(this,"loadTestFont",h())},configurable:!0}),r.prototype.addNativeFontFace=function(t){this.nativeFontFaces.push(t),document.fonts.add(t)},r.prototype.bind=function(t,e){for(var n=[],i=[],a=[],s=r.isFontLoadingAPISupported&&!r.isSyncFontLoadingSupported,o=0,c=t.length;o<c;o++){var h=t[o];if(!h.attached&&!1!==h.loading)if(h.attached=!0,s){var u=h.createNativeFontFace();u&&(this.addNativeFontFace(u),a.push(function(t){return t.loaded.catch(function(e){l('Failed to load font "'+t.family+'": '+e)})}(u)))}else{var d=h.createFontFaceRule();d&&(this.insertRule(d),n.push(d),i.push(h))}}var f=this.queueLoadingCallback(e);s?Promise.all(a).then(function(){f.complete()}):n.length>0&&!r.isSyncFontLoadingSupported?this.prepareFontLoadEvent(n,i,f):f.complete()},r.prototype.queueLoadingCallback=function(t){function e(){for(a(!i.end,"completeRequest() cannot be called twice"),i.end=Date.now();n.requests.length>0&&n.requests[0].end;){var t=n.requests.shift();setTimeout(t.callback,0)}}var n=this.loadingContext,r="pdfjs-font-loading-"+n.nextRequestId++,i={id:r,complete:e,callback:t,started:Date.now()};return n.requests.push(i),i},r.prototype.prepareFontLoadEvent=function(t,e,n){function r(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function i(t,e,n,r){return t.substr(0,e)+r+t.substr(e+n)}function a(t,e){return++d>30?(l("Load test font never loaded."),void e()):(u.font="30px "+t,u.fillText(".",0,20),u.getImageData(0,0,1,1).data[3]>0?void e():void setTimeout(a.bind(null,t,e)))}var s,c,h=document.createElement("canvas");h.width=1,h.height=1;var u=h.getContext("2d"),d=0,f="lt"+Date.now()+this.loadTestFontId++,p=this.loadTestFont;p=i(p,976,f.length,f);var g=r(p,16);for(s=0,c=f.length-3;s<c;s+=4)g=g-1482184792+r(f,s)|0;s<f.length&&(g=g-1482184792+r(f+"XXX",s)|0),p=i(p,16,4,o(g));var m="url(data:font/opentype;base64,"+btoa(p)+");",A='@font-face { font-family:"'+f+'";src:'+m+"}";this.insertRule(A);var v=[];for(s=0,c=e.length;s<c;s++)v.push(e[s].loadedName);v.push(f);var b=document.createElement("div");for(b.setAttribute("style","visibility: hidden;width: 10px; height: 10px;position: absolute; top: 0px; left: 0px;"),s=0,c=v.length;s<c;++s){var y=document.createElement("span");y.textContent="Hi",y.style.fontFamily=v[s],b.appendChild(y)}document.body.appendChild(b),a(f,function(){document.body.removeChild(b),n.complete()})},r.isFontLoadingAPISupported="undefined"!=typeof document&&!!document.fonts;var u=function(){if("undefined"==typeof navigator)return!0;var t=!1,e=/Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);return e&&e[1]>=14&&(t=!0),t};Object.defineProperty(r,"isSyncFontLoadingSupported",{get:function(){return c(r,"isSyncFontLoadingSupported",u())},enumerable:!0,configurable:!0});var d={get value(){return c(this,"value",i.isEvalSupported())}},f=function(){function t(t,e){this.compiledGlyphs=Object.create(null);for(var n in t)this[n]=t[n];this.options=e}return t.prototype={createNativeFontFace:function(){if(!this.data)return null;if(this.options.disableFontFace)return this.disableFontFace=!0,null;var t=new FontFace(this.loadedName,this.data,{});return this.options.fontRegistry&&this.options.fontRegistry.registerFont(this),t},createFontFaceRule:function(){if(!this.data)return null;if(this.options.disableFontFace)return this.disableFontFace=!0,null;var t=s(new Uint8Array(this.data)),e=this.loadedName,n="url(data:"+this.mimetype+";base64,"+btoa(t)+");",r='@font-face { font-family:"'+e+'";src:'+n+"}";return this.options.fontRegistry&&this.options.fontRegistry.registerFont(this,n),r},getPathGenerator:function(t,e){if(!(e in this.compiledGlyphs)){var n,r,i,a=t.get(this.loadedName+"_path_"+e);if(this.options.isEvalSupported&&d.value){var s,o="";for(r=0,i=a.length;r<i;r++)n=a[r],s=void 0!==n.args?n.args.join(","):"",o+="c."+n.cmd+"("+s+");\n";this.compiledGlyphs[e]=new Function("c","size",o)}else this.compiledGlyphs[e]=function(t,e){for(r=0,i=a.length;r<i;r++)n=a[r],"scale"===n.cmd&&(n.args=[e,-e]),t[n.cmd].apply(t,n.args)}}return this.compiledGlyphs[e]}},t}();e.FontFaceObject=f,e.FontLoader=r},function(t,e,n){"use strict";function r(t){var e=u[t[0]];return e||l("Unknown IR type: "+t[0]),e.fromIR(t)}var i=n(0),a=n(8),s=i.Util,o=i.info,c=i.isArray,l=i.error,h=a.WebGLUtils,u={};u.RadialAxial={fromIR:function(t){var e=t[1],n=t[2],r=t[3],i=t[4],a=t[5],s=t[6];return{type:"Pattern",getPattern:function(t){var o;"axial"===e?o=t.createLinearGradient(r[0],r[1],i[0],i[1]):"radial"===e&&(o=t.createRadialGradient(r[0],r[1],a,i[0],i[1],s));for(var c=0,l=n.length;c<l;++c){var h=n[c];o.addColorStop(h[0],h[1])}return o}}}};var d=function(){function t(t,e,n,r,i,a,s,o){var c,l=e.coords,h=e.colors,u=t.data,d=4*t.width;l[n+1]>l[r+1]&&(c=n,n=r,r=c,c=a,a=s,s=c),l[r+1]>l[i+1]&&(c=r,r=i,i=c,c=s,s=o,o=c),l[n+1]>l[r+1]&&(c=n,n=r,r=c,c=a,a=s,s=c);var f=(l[n]+e.offsetX)*e.scaleX,p=(l[n+1]+e.offsetY)*e.scaleY,g=(l[r]+e.offsetX)*e.scaleX,m=(l[r+1]+e.offsetY)*e.scaleY,A=(l[i]+e.offsetX)*e.scaleX,v=(l[i+1]+e.offsetY)*e.scaleY;if(!(p>=v))for(var b,y,x,S,w,k,C,_,T,P=h[a],L=h[a+1],E=h[a+2],R=h[s],I=h[s+1],F=h[s+2],O=h[o],N=h[o+1],M=h[o+2],D=Math.round(p),j=Math.round(v),U=D;U<=j;U++){U<m?(T=U<p?0:p===m?1:(p-U)/(p-m),b=f-(f-g)*T,y=P-(P-R)*T,x=L-(L-I)*T,S=E-(E-F)*T):(T=U>v?1:m===v?0:(m-U)/(m-v),b=g-(g-A)*T,y=R-(R-O)*T,x=I-(I-N)*T,S=F-(F-M)*T),T=U<p?0:U>v?1:(p-U)/(p-v),w=f-(f-A)*T,k=P-(P-O)*T,C=L-(L-N)*T,_=E-(E-M)*T;for(var B=Math.round(Math.min(b,w)),W=Math.round(Math.max(b,w)),G=d*U+4*B,X=B;X<=W;X++)T=(b-X)/(b-w),T=T<0?0:T>1?1:T,u[G++]=y-(y-k)*T|0,u[G++]=x-(x-C)*T|0,u[G++]=S-(S-_)*T|0,u[G++]=255}}function e(e,n,r){var i,a,s=n.coords,o=n.colors;switch(n.type){case"lattice":var c=n.verticesPerRow,h=Math.floor(s.length/c)-1,u=c-1;for(i=0;i<h;i++)for(var d=i*c,f=0;f<u;f++,d++)t(e,r,s[d],s[d+1],s[d+c],o[d],o[d+1],o[d+c]),t(e,r,s[d+c+1],s[d+1],s[d+c],o[d+c+1],o[d+1],o[d+c]);break;case"triangles":for(i=0,a=s.length;i<a;i+=3)t(e,r,s[i],s[i+1],s[i+2],o[i],o[i+1],o[i+2]);break;default:l("illigal figure")}}function n(t,n,r,i,a,s,o){var c,l,u,d,f=Math.floor(t[0]),p=Math.floor(t[1]),g=Math.ceil(t[2])-f,m=Math.ceil(t[3])-p,A=Math.min(Math.ceil(Math.abs(g*n[0]*1.1)),3e3),v=Math.min(Math.ceil(Math.abs(m*n[1]*1.1)),3e3),b=g/A,y=m/v,x={coords:r,colors:i,offsetX:-f,offsetY:-p,scaleX:1/b,scaleY:1/y},S=A+4,w=v+4;if(h.isEnabled)c=h.drawFigures(A,v,s,a,x),l=o.getCanvas("mesh",S,w,!1),l.context.drawImage(c,2,2),c=l.canvas;else{l=o.getCanvas("mesh",S,w,!1);var k=l.context,C=k.createImageData(A,v);if(s){var _=C.data;for(u=0,d=_.length;u<d;u+=4)_[u]=s[0],_[u+1]=s[1],_[u+2]=s[2],_[u+3]=255}for(u=0;u<a.length;u++)e(C,a[u],x);k.putImageData(C,2,2),c=l.canvas}return{canvas:c,offsetX:f-2*b,offsetY:p-2*y,scaleX:b,scaleY:y}}return n}();u.Mesh={fromIR:function(t){var e=t[2],n=t[3],r=t[4],i=t[5],a=t[6],o=t[8];return{type:"Pattern",getPattern:function(t,c,l){var h;if(l)h=s.singularValueDecompose2dScale(t.mozCurrentTransform);else if(h=s.singularValueDecompose2dScale(c.baseTransform),a){var u=s.singularValueDecompose2dScale(a);h=[h[0]*u[0],h[1]*u[1]]}var f=d(i,h,e,n,r,l?null:o,c.cachedCanvases);return l||(t.setTransform.apply(t,c.baseTransform),a&&t.transform.apply(t,a)),t.translate(f.offsetX,f.offsetY),t.scale(f.scaleX,f.scaleY),t.createPattern(f.canvas,"no-repeat")}}}},u.Dummy={fromIR:function(){return{type:"Pattern",getPattern:function(){return"hotpink"}}}};var f=function(){function t(t,e,n,r,i){this.operatorList=t[2],this.matrix=t[3]||[1,0,0,1,0,0],this.bbox=s.normalizeRect(t[4]),this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.color=e,this.canvasGraphicsFactory=r,this.baseTransform=i,this.type="Pattern",this.ctx=n}var e={COLORED:1,UNCOLORED:2};return t.prototype={createPatternCanvas:function(t){var e=this.operatorList,n=this.bbox,r=this.xstep,i=this.ystep,a=this.paintType,c=this.tilingType,l=this.color,h=this.canvasGraphicsFactory;o("TilingType: "+c);var u=n[0],d=n[1],f=n[2],p=n[3],g=[u,d],m=[u+r,d+i],A=m[0]-g[0],v=m[1]-g[1],b=s.singularValueDecompose2dScale(this.matrix),y=s.singularValueDecompose2dScale(this.baseTransform),x=[b[0]*y[0],b[1]*y[1]];A=Math.min(Math.ceil(Math.abs(A*x[0])),3e3),v=Math.min(Math.ceil(Math.abs(v*x[1])),3e3);var S=t.cachedCanvases.getCanvas("pattern",A,v,!0),w=S.context,k=h.createCanvasGraphics(w);k.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(w,a,l),this.setScale(A,v,r,i),this.transformToScale(k);var C=[1,0,0,1,-g[0],-g[1]];return k.transform.apply(k,C),this.clipBbox(k,n,u,d,f,p),k.executeOperatorList(e),S.canvas},setScale:function(t,e,n,r){this.scale=[t/n,e/r]},transformToScale:function(t){var e=this.scale,n=[e[0],0,0,e[1],0,0];t.transform.apply(t,n)},scaleToContext:function(){var t=this.scale;this.ctx.scale(1/t[0],1/t[1])},clipBbox:function(t,e,n,r,i,a){if(c(e)&&4===e.length){var s=i-n,o=a-r;t.ctx.rect(n,r,s,o),t.clip(),t.endPath()}},setFillAndStrokeStyleToContext:function(t,n,r){switch(n){case e.COLORED:var i=this.ctx;t.fillStyle=i.fillStyle,t.strokeStyle=i.strokeStyle;break;case e.UNCOLORED:var a=s.makeCssRgb(r[0],r[1],r[2]);t.fillStyle=a,t.strokeStyle=a;break;default:l("Unsupported paint type: "+n)}},getPattern:function(t,e){var n=this.createPatternCanvas(e);return t=this.ctx,t.setTransform.apply(t,this.baseTransform),t.transform.apply(t,this.matrix),this.scaleToContext(),t.createPattern(n,"repeat")}},t}();e.getShadingPatternFromIR=r,e.TilingPattern=f},function(t,e,n){"use strict";var r=n(0),i=n(9),a=n(3),s=n(5),o=n(2),c=n(1),l=n(4);e.PDFJS=i.PDFJS,e.build=a.build,e.version=a.version,e.getDocument=a.getDocument,e.PDFDataRangeTransport=a.PDFDataRangeTransport,e.PDFWorker=a.PDFWorker,e.renderTextLayer=s.renderTextLayer,e.AnnotationLayer=o.AnnotationLayer,e.CustomStyle=c.CustomStyle,e.createPromiseCapability=r.createPromiseCapability,e.PasswordResponses=r.PasswordResponses,e.InvalidPDFException=r.InvalidPDFException,e.MissingPDFException=r.MissingPDFException,e.SVGGraphics=l.SVGGraphics,e.UnexpectedResponseException=r.UnexpectedResponseException,e.OPS=r.OPS,e.UNSUPPORTED_FEATURES=r.UNSUPPORTED_FEATURES,e.isValidUrl=c.isValidUrl,e.createValidAbsoluteUrl=r.createValidAbsoluteUrl,e.createObjectURL=r.createObjectURL,e.removeNullCharacters=r.removeNullCharacters,e.shadow=r.shadow,e.createBlob=r.createBlob,e.RenderingCancelledException=c.RenderingCancelledException,e.getFilenameFromUrl=c.getFilenameFromUrl,e.addLinkAttributes=c.addLinkAttributes},function(t,e,n){"use strict";(function(t){if("undefined"==typeof PDFJS||!PDFJS.compatibilityChecked){var e="undefined"!=typeof window?window:void 0!==t?t:"undefined"!=typeof self?self:void 0,n="undefined"!=typeof navigator&&navigator.userAgent||"",r=/Android/.test(n),i=/Android\s[0-2][^\d]/.test(n),a=/Android\s[0-4][^\d]/.test(n),s=n.indexOf("Chrom")>=0,o=/Chrome\/(39|40)\./.test(n),c=n.indexOf("CriOS")>=0,l=n.indexOf("Trident")>=0,h=/\b(iPad|iPhone|iPod)(?=;)/.test(n),u=n.indexOf("Opera")>=0,d=/Safari\//.test(n)&&!/(Chrome\/|Android\s)/.test(n),f="object"==typeof window&&"object"==typeof document;"undefined"==typeof PDFJS&&(e.PDFJS={}),PDFJS.compatibilityChecked=!0,function(){function t(t,e){return new r(this.slice(t,e))}function n(t,e){arguments.length<2&&(e=0);for(var n=0,r=t.length;n<r;++n,++e)this[e]=255&t[n]}function r(e){var r,i,a;if("number"==typeof e)for(r=[],i=0;i<e;++i)r[i]=0;else if("slice"in e)r=e.slice(0);else for(r=[],i=0,a=e.length;i<a;++i)r[i]=e[i];return r.subarray=t,r.buffer=r,r.byteLength=r.length,r.set=n,"object"==typeof e&&e.buffer&&(r.buffer=e.buffer),r}if("undefined"!=typeof Uint8Array)return void 0===Uint8Array.prototype.subarray&&(Uint8Array.prototype.subarray=function(t,e){return new Uint8Array(this.slice(t,e))},Float32Array.prototype.subarray=function(t,e){return new Float32Array(this.slice(t,e))}),void("undefined"==typeof Float64Array&&(e.Float64Array=Float32Array));e.Uint8Array=r,e.Int8Array=r,e.Uint32Array=r,e.Int32Array=r,e.Uint16Array=r,e.Float32Array=r,e.Float64Array=r}(),function(){e.URL||(e.URL=e.webkitURL)}(),function(){if(void 0!==Object.defineProperty){var t=!0;try{f&&Object.defineProperty(new Image,"id",{value:"test"});var e=function(){};e.prototype={get id(){}},Object.defineProperty(new e,"id",{value:"",configurable:!0,enumerable:!0,writable:!1})}catch(e){t=!1}if(t)return}Object.defineProperty=function(t,e,n){delete t[e],"get"in n&&t.__defineGetter__(e,n.get),"set"in n&&t.__defineSetter__(e,n.set),"value"in n&&(t.__defineSetter__(e,function(t){return this.__defineGetter__(e,function(){return t}),t}),t[e]=n.value)}}(),function(){if("undefined"!=typeof XMLHttpRequest){var t=XMLHttpRequest.prototype,e=new XMLHttpRequest;if("overrideMimeType"in e||Object.defineProperty(t,"overrideMimeType",{value:function(t){}}),!("responseType"in e)){if(Object.defineProperty(t,"responseType",{get:function(){return this._responseType||"text"},set:function(t){"text"!==t&&"arraybuffer"!==t||(this._responseType=t,"arraybuffer"===t&&"function"==typeof this.overrideMimeType&&this.overrideMimeType("text/plain; charset=x-user-defined"))}}),"undefined"!=typeof VBArray)return void Object.defineProperty(t,"response",{get:function(){return"arraybuffer"===this.responseType?new Uint8Array(new VBArray(this.responseBody).toArray()):this.responseText}});Object.defineProperty(t,"response",{get:function(){if("arraybuffer"!==this.responseType)return this.responseText;var t,e=this.responseText,n=e.length,r=new Uint8Array(n);for(t=0;t<n;++t)r[t]=255&e.charCodeAt(t);return r.buffer}})}}}(),function(){if(!("btoa"in e)){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";e.btoa=function(e){var n,r,i="";for(n=0,r=e.length;n<r;n+=3){var a=255&e.charCodeAt(n),s=255&e.charCodeAt(n+1),o=255&e.charCodeAt(n+2),c=a>>2,l=(3&a)<<4|s>>4,h=n+1<r?(15&s)<<2|o>>6:64,u=n+2<r?63&o:64;i+=t.charAt(c)+t.charAt(l)+t.charAt(h)+t.charAt(u)}return i}}}(),function(){if(!("atob"in e)){e.atob=function(t){if(t=t.replace(/=+$/,""),t.length%4==1)throw new Error("bad atob input");for(var e,n,r=0,i=0,a="";n=t.charAt(i++);~n&&(e=r%4?64*e+n:n,r++%4)?a+=String.fromCharCode(255&e>>(-2*r&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return a}}}(),function(){void 0===Function.prototype.bind&&(Function.prototype.bind=function(t){var e=this,n=Array.prototype.slice.call(arguments,1);return function(){var r=n.concat(Array.prototype.slice.call(arguments));return e.apply(t,r)}})}(),function(){if(f){"dataset"in document.createElement("div")||Object.defineProperty(HTMLElement.prototype,"dataset",{get:function(){if(this._dataset)return this._dataset;for(var t={},e=0,n=this.attributes.length;e<n;e++){var r=this.attributes[e];if("data-"===r.name.substring(0,5)){t[r.name.substring(5).replace(/\-([a-z])/g,function(t,e){return e.toUpperCase()})]=r.value}}return Object.defineProperty(this,"_dataset",{value:t,writable:!1,enumerable:!1}),t},enumerable:!0})}}(),function(){function t(t,e,n,r){var i=t.className||"",a=i.split(/\s+/g);""===a[0]&&a.shift();var s=a.indexOf(e);return s<0&&n&&a.push(e),s>=0&&r&&a.splice(s,1),t.className=a.join(" "),s>=0}if(f){if(!("classList"in document.createElement("div"))){var e={add:function(e){t(this.element,e,!0,!1)},contains:function(e){return t(this.element,e,!1,!1)},remove:function(e){t(this.element,e,!1,!0)},toggle:function(e){t(this.element,e,!0,!0)}};Object.defineProperty(HTMLElement.prototype,"classList",{get:function(){if(this._classList)return this._classList;var t=Object.create(e,{element:{value:this,writable:!1,enumerable:!0}});return Object.defineProperty(this,"_classList",{value:t,writable:!1,enumerable:!1}),t},enumerable:!0})}}}(),function(){if(!("undefined"==typeof importScripts||"console"in e)){var t={},n={log:function(){var t=Array.prototype.slice.call(arguments);e.postMessage({targetName:"main",action:"console_log",data:t})},error:function(){var t=Array.prototype.slice.call(arguments);e.postMessage({targetName:"main",action:"console_error",data:t})},time:function(e){t[e]=Date.now()},timeEnd:function(e){var n=t[e];if(!n)throw new Error("Unknown timer name "+e);this.log("Timer:",e,Date.now()-n)}};e.console=n}}(),function(){if(f)"console"in window?"bind"in console.log||(console.log=function(t){return function(e){return t(e)}}(console.log),console.error=function(t){return function(e){return t(e)}}(console.error),console.warn=function(t){return function(e){return t(e)}}(console.warn)):window.console={log:function(){},error:function(){},warn:function(){}}}(),function(){function t(t){e(t.target)&&t.stopPropagation()}function e(t){return t.disabled||t.parentNode&&e(t.parentNode)}u&&document.addEventListener("click",t,!0)}(),function(){(l||c)&&(PDFJS.disableCreateObjectURL=!0)}(),function(){"undefined"!=typeof navigator&&("language"in navigator||(PDFJS.locale=navigator.userLanguage||"en-US"))}(),function(){(d||i||o||h)&&(PDFJS.disableRange=!0,PDFJS.disableStream=!0)}(),function(){f&&(history.pushState&&!i||(PDFJS.disableHistory=!0))}(),function(){if(f)if(window.CanvasPixelArray)"function"!=typeof window.CanvasPixelArray.prototype.set&&(window.CanvasPixelArray.prototype.set=function(t){for(var e=0,n=this.length;e<n;e++)this[e]=t[e]});else{var t,e=!1;if(s?(t=n.match(/Chrom(e|ium)\/([0-9]+)\./),e=t&&parseInt(t[2])<21):r?e=a:d&&(t=n.match(/Version\/([0-9]+)\.([0-9]+)\.([0-9]+) Safari\//),e=t&&parseInt(t[1])<6),e){var i=window.CanvasRenderingContext2D.prototype,o=i.createImageData;i.createImageData=function(t,e){var n=o.call(this,t,e);return n.data.set=function(t){for(var e=0,n=this.length;e<n;e++)this[e]=t[e]},n},i=null}}}(),function(){function t(){window.requestAnimationFrame=function(t){return window.setTimeout(t,20)},window.cancelAnimationFrame=function(t){window.clearTimeout(t)}}if(f)h?t():"requestAnimationFrame"in window||(window.requestAnimationFrame=window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame,window.requestAnimationFrame||t())}(),function(){(h||r)&&(PDFJS.maxCanvasPixels=5242880)}(),function(){f&&l&&window.parent!==window&&(PDFJS.disableFullscreen=!0)}(),function(){f&&("currentScript"in document||Object.defineProperty(document,"currentScript",{get:function(){var t=document.getElementsByTagName("script");return t[t.length-1]},enumerable:!0,configurable:!0}))}(),function(){if(f){var t=document.createElement("input");try{t.type="number"}catch(r){var e=t.constructor.prototype,n=Object.getOwnPropertyDescriptor(e,"type");Object.defineProperty(e,"type",{get:function(){return n.get.call(this)},set:function(t){n.set.call(this,"number"===t?"text":t)},enumerable:!0,configurable:!0})}}}(),function(){if(f&&document.attachEvent){var t=document.constructor.prototype,e=Object.getOwnPropertyDescriptor(t,"readyState");Object.defineProperty(t,"readyState",{get:function(){var t=e.get.call(this);return"interactive"===t?"loading":t},set:function(t){e.set.call(this,t)},enumerable:!0,configurable:!0})}}(),function(){f&&void 0===Element.prototype.remove&&(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)})}(),function(){if(e.Promise)return"function"!=typeof e.Promise.all&&(e.Promise.all=function(t){var n,r,i=0,a=[],s=new e.Promise(function(t,e){n=t,r=e});return t.forEach(function(t,e){i++,t.then(function(t){a[e]=t,0===--i&&n(a)},r)}),0===i&&n(a),s}),"function"!=typeof e.Promise.resolve&&(e.Promise.resolve=function(t){return new e.Promise(function(e){e(t)})}),"function"!=typeof e.Promise.reject&&(e.Promise.reject=function(t){return new e.Promise(function(e,n){n(t)})}),void("function"!=typeof e.Promise.prototype.catch&&(e.Promise.prototype.catch=function(t){return e.Promise.prototype.then(void 0,t)}));var t=2,n={handlers:[],running:!1,unhandledRejections:[],pendingRejectionCheck:!1,scheduleHandlers:function(t){0!==t._status&&(this.handlers=this.handlers.concat(t._handlers),t._handlers=[],this.running||(this.running=!0,setTimeout(this.runHandlers.bind(this),0)))},runHandlers:function(){for(var e=Date.now()+1;this.handlers.length>0;){var n=this.handlers.shift(),r=n.thisPromise._status,i=n.thisPromise._value;try{1===r?"function"==typeof n.onResolve&&(i=n.onResolve(i)):"function"==typeof n.onReject&&(i=n.onReject(i),r=1,n.thisPromise._unhandledRejection&&this.removeUnhandeledRejection(n.thisPromise))}catch(e){r=t,i=e}if(n.nextPromise._updateStatus(r,i),Date.now()>=e)break}if(this.handlers.length>0)return void setTimeout(this.runHandlers.bind(this),0);this.running=!1},addUnhandledRejection:function(t){this.unhandledRejections.push({promise:t,time:Date.now()}),this.scheduleRejectionCheck()},removeUnhandeledRejection:function(t){t._unhandledRejection=!1;for(var e=0;e<this.unhandledRejections.length;e++)this.unhandledRejections[e].promise===t&&(this.unhandledRejections.splice(e),e--)},scheduleRejectionCheck:function(){this.pendingRejectionCheck||(this.pendingRejectionCheck=!0,setTimeout(function(){this.pendingRejectionCheck=!1;for(var t=Date.now(),e=0;e<this.unhandledRejections.length;e++)if(t-this.unhandledRejections[e].time>500){var n=this.unhandledRejections[e].promise._value,r="Unhandled rejection: "+n;n.stack&&(r+="\n"+n.stack);try{throw new Error(r)}catch(t){console.warn(r)}this.unhandledRejections.splice(e),e--}this.unhandledRejections.length&&this.scheduleRejectionCheck()}.bind(this),500))}},r=function(t){this._status=0,this._handlers=[];try{t.call(this,this._resolve.bind(this),this._reject.bind(this))}catch(t){this._reject(t)}};r.all=function(e){function n(e){s._status!==t&&(c=[],a(e))}var i,a,s=new r(function(t,e){i=t,a=e}),o=e.length,c=[];if(0===o)return i(c),s;for(var l=0,h=e.length;l<h;++l){var u=e[l],d=function(e){return function(n){s._status!==t&&(c[e]=n,0===--o&&i(c))}}(l);r.isPromise(u)?u.then(d,n):d(u)}return s},r.isPromise=function(t){return t&&"function"==typeof t.then},r.resolve=function(t){return new r(function(e){e(t)})},r.reject=function(t){return new r(function(e,n){n(t)})},r.prototype={_status:null,_value:null,_handlers:null,_unhandledRejection:null,_updateStatus:function(e,i){if(1!==this._status&&this._status!==t){if(1===e&&r.isPromise(i))return void i.then(this._updateStatus.bind(this,1),this._updateStatus.bind(this,t));this._status=e,this._value=i,e===t&&0===this._handlers.length&&(this._unhandledRejection=!0,n.addUnhandledRejection(this)),n.scheduleHandlers(this)}},_resolve:function(t){this._updateStatus(1,t)},_reject:function(e){this._updateStatus(t,e)},then:function(t,e){var i=new r(function(t,e){this.resolve=t,this.reject=e});return this._handlers.push({thisPromise:this,onResolve:t,onReject:e,nextPromise:i}),n.scheduleHandlers(this),i},catch:function(t){return this.then(void 0,t)}},e.Promise=r}(),function(){function t(){this.id="$weakmap"+n++}if(!e.WeakMap){var n=0;t.prototype={has:function(t){return!!Object.getOwnPropertyDescriptor(t,this.id)},get:function(t,e){return this.has(t)?t[this.id]:e},set:function(t,e){Object.defineProperty(t,this.id,{value:e,enumerable:!1,configurable:!0})},delete:function(t){delete t[this.id]}},e.WeakMap=t}}(),function(){function t(t){return void 0!==u[t]}function n(){o.call(this),this._isInvalid=!0}function r(t){return""===t&&n.call(this),t.toLowerCase()}function i(t){var e=t.charCodeAt(0);return e>32&&e<127&&-1===[34,35,60,62,63,96].indexOf(e)?t:encodeURIComponent(t)}function a(t){var e=t.charCodeAt(0);return e>32&&e<127&&-1===[34,35,60,62,96].indexOf(e)?t:encodeURIComponent(t)}function s(e,s,o){function c(t){b.push(t)}var l=s||"scheme start",h=0,m="",A=!1,v=!1,b=[];t:for(;(e[h-1]!==f||0===h)&&!this._isInvalid;){var y=e[h];switch(l){case"scheme start":if(!y||!p.test(y)){if(s){c("Invalid scheme.");break t}m="",l="no scheme";continue}m+=y.toLowerCase(),l="scheme";break;case"scheme":if(y&&g.test(y))m+=y.toLowerCase();else{if(":"!==y){if(s){if(y===f)break t;c("Code point not allowed in scheme: "+y);break t}m="",h=0,l="no scheme";continue}if(this._scheme=m,m="",s)break t;t(this._scheme)&&(this._isRelative=!0),l="file"===this._scheme?"relative":this._isRelative&&o&&o._scheme===this._scheme?"relative or authority":this._isRelative?"authority first slash":"scheme data"}break;case"scheme data":"?"===y?(this._query="?",l="query"):"#"===y?(this._fragment="#",l="fragment"):y!==f&&"\t"!==y&&"\n"!==y&&"\r"!==y&&(this._schemeData+=i(y));break;case"no scheme":if(o&&t(o._scheme)){l="relative";continue}c("Missing scheme."),n.call(this);break;case"relative or authority":if("/"!==y||"/"!==e[h+1]){c("Expected /, got: "+y),l="relative";continue}l="authority ignore slashes";break;case"relative":if(this._isRelative=!0,"file"!==this._scheme&&(this._scheme=o._scheme),y===f){this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query=o._query,this._username=o._username,this._password=o._password;break t}if("/"===y||"\\"===y)"\\"===y&&c("\\ is an invalid code point."),l="relative slash";else if("?"===y)this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query="?",this._username=o._username,this._password=o._password,l="query";else{if("#"!==y){var x=e[h+1],S=e[h+2];("file"!==this._scheme||!p.test(y)||":"!==x&&"|"!==x||S!==f&&"/"!==S&&"\\"!==S&&"?"!==S&&"#"!==S)&&(this._host=o._host,this._port=o._port,this._username=o._username,this._password=o._password,this._path=o._path.slice(),this._path.pop()),l="relative path";continue}this._host=o._host,this._port=o._port,this._path=o._path.slice(),this._query=o._query,this._fragment="#",this._username=o._username,this._password=o._password,l="fragment"}break;case"relative slash":if("/"!==y&&"\\"!==y){"file"!==this._scheme&&(this._host=o._host,this._port=o._port,this._username=o._username,this._password=o._password),l="relative path";continue}"\\"===y&&c("\\ is an invalid code point."),l="file"===this._scheme?"file host":"authority ignore slashes";break;case"authority first slash":if("/"!==y){c("Expected '/', got: "+y),l="authority ignore slashes";continue}l="authority second slash";break;case"authority second slash":if(l="authority ignore slashes","/"!==y){c("Expected '/', got: "+y);continue}break;case"authority ignore slashes":if("/"!==y&&"\\"!==y){l="authority";continue}c("Expected authority, got: "+y);break;case"authority":if("@"===y){A&&(c("@ already seen."),m+="%40"),A=!0;for(var w=0;w<m.length;w++){var k=m[w] ;if("\t"!==k&&"\n"!==k&&"\r"!==k)if(":"!==k||null!==this._password){var C=i(k);null!==this._password?this._password+=C:this._username+=C}else this._password="";else c("Invalid whitespace in authority.")}m=""}else{if(y===f||"/"===y||"\\"===y||"?"===y||"#"===y){h-=m.length,m="",l="host";continue}m+=y}break;case"file host":if(y===f||"/"===y||"\\"===y||"?"===y||"#"===y){2!==m.length||!p.test(m[0])||":"!==m[1]&&"|"!==m[1]?0===m.length?l="relative path start":(this._host=r.call(this,m),m="",l="relative path start"):l="relative path";continue}"\t"===y||"\n"===y||"\r"===y?c("Invalid whitespace in file host."):m+=y;break;case"host":case"hostname":if(":"!==y||v){if(y===f||"/"===y||"\\"===y||"?"===y||"#"===y){if(this._host=r.call(this,m),m="",l="relative path start",s)break t;continue}"\t"!==y&&"\n"!==y&&"\r"!==y?("["===y?v=!0:"]"===y&&(v=!1),m+=y):c("Invalid code point in host/hostname: "+y)}else if(this._host=r.call(this,m),m="",l="port","hostname"===s)break t;break;case"port":if(/[0-9]/.test(y))m+=y;else{if(y===f||"/"===y||"\\"===y||"?"===y||"#"===y||s){if(""!==m){var _=parseInt(m,10);_!==u[this._scheme]&&(this._port=_+""),m=""}if(s)break t;l="relative path start";continue}"\t"===y||"\n"===y||"\r"===y?c("Invalid code point in port: "+y):n.call(this)}break;case"relative path start":if("\\"===y&&c("'\\' not allowed in path."),l="relative path","/"!==y&&"\\"!==y)continue;break;case"relative path":if(y!==f&&"/"!==y&&"\\"!==y&&(s||"?"!==y&&"#"!==y))"\t"!==y&&"\n"!==y&&"\r"!==y&&(m+=i(y));else{"\\"===y&&c("\\ not allowed in relative path.");var T;(T=d[m.toLowerCase()])&&(m=T),".."===m?(this._path.pop(),"/"!==y&&"\\"!==y&&this._path.push("")):"."===m&&"/"!==y&&"\\"!==y?this._path.push(""):"."!==m&&("file"===this._scheme&&0===this._path.length&&2===m.length&&p.test(m[0])&&"|"===m[1]&&(m=m[0]+":"),this._path.push(m)),m="","?"===y?(this._query="?",l="query"):"#"===y&&(this._fragment="#",l="fragment")}break;case"query":s||"#"!==y?y!==f&&"\t"!==y&&"\n"!==y&&"\r"!==y&&(this._query+=a(y)):(this._fragment="#",l="fragment");break;case"fragment":y!==f&&"\t"!==y&&"\n"!==y&&"\r"!==y&&(this._fragment+=y)}h++}}function o(){this._scheme="",this._schemeData="",this._username="",this._password=null,this._host="",this._port="",this._path=[],this._query="",this._fragment="",this._isInvalid=!1,this._isRelative=!1}function c(t,e){void 0===e||e instanceof c||(e=new c(String(e))),this._url=t,o.call(this);var n=t.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g,"");s.call(this,n,null,e)}var l=!1;try{if("function"==typeof URL&&"object"==typeof URL.prototype&&"origin"in URL.prototype){var h=new URL("b","http://a");h.pathname="c%20d",l="http://a/c%20d"===h.href}}catch(t){}if(!l){var u=Object.create(null);u.ftp=21,u.file=0,u.gopher=70,u.http=80,u.https=443,u.ws=80,u.wss=443;var d=Object.create(null);d["%2e"]=".",d[".%2e"]="..",d["%2e."]="..",d["%2e%2e"]="..";var f,p=/[a-zA-Z]/,g=/[a-zA-Z0-9\+\-\.]/;c.prototype={toString:function(){return this.href},get href(){if(this._isInvalid)return this._url;var t="";return""===this._username&&null===this._password||(t=this._username+(null!==this._password?":"+this._password:"")+"@"),this.protocol+(this._isRelative?"//"+t+this.host:"")+this.pathname+this._query+this._fragment},set href(t){o.call(this),s.call(this,t)},get protocol(){return this._scheme+":"},set protocol(t){this._isInvalid||s.call(this,t+":","scheme start")},get host(){return this._isInvalid?"":this._port?this._host+":"+this._port:this._host},set host(t){!this._isInvalid&&this._isRelative&&s.call(this,t,"host")},get hostname(){return this._host},set hostname(t){!this._isInvalid&&this._isRelative&&s.call(this,t,"hostname")},get port(){return this._port},set port(t){!this._isInvalid&&this._isRelative&&s.call(this,t,"port")},get pathname(){return this._isInvalid?"":this._isRelative?"/"+this._path.join("/"):this._schemeData},set pathname(t){!this._isInvalid&&this._isRelative&&(this._path=[],s.call(this,t,"relative path start"))},get search(){return this._isInvalid||!this._query||"?"===this._query?"":this._query},set search(t){!this._isInvalid&&this._isRelative&&(this._query="?","?"===t[0]&&(t=t.slice(1)),s.call(this,t,"query"))},get hash(){return this._isInvalid||!this._fragment||"#"===this._fragment?"":this._fragment},set hash(t){this._isInvalid||(this._fragment="#","#"===t[0]&&(t=t.slice(1)),s.call(this,t,"fragment"))},get origin(){var t;if(this._isInvalid||!this._scheme)return"";switch(this._scheme){case"data":case"file":case"javascript":case"mailto":return"null"}return t=this.host,t?this._scheme+"://"+t:""}};var m=e.URL;m&&(c.createObjectURL=function(t){return m.createObjectURL.apply(m,arguments)},c.revokeObjectURL=function(t){m.revokeObjectURL(t)}),e.URL=c}}()}}).call(e,n(6))}])});
import { fakeXhr } from 'nise'; import xhrRequest, { getError, getBody } from '../xhrRequest'; let mockXhr = null; let currentRequest = null; const API_URL = '/api/upload'; const option = { data: { name: 'gio', age: '21', hobbies: ['eat', 'sleep'] }, file: 'file', filename: 'filename.png', withCredentials: true, action: API_URL, method: 'POST', onProgress: () => {}, onSuccess: () => {}, onError: () => {}, }; describe('xhrRequest', () => { beforeEach(() => { mockXhr = fakeXhr.useFakeXMLHttpRequest(); mockXhr.onCreate = (request) => (currentRequest = request); }); afterEach(() => { mockXhr.restore(); currentRequest = null; }); test('upload request success', (done) => { expect.assertions(2); option.onSuccess = (response) => { expect(response).toEqual({ message: 'upload success', success: true }); expect(currentRequest.requestBody.getAll('hobbies[]')).toEqual(['eat', 'sleep']); done(); }; xhrRequest(option); currentRequest.respond( 200, { 'Content-Type': 'application/json' }, JSON.stringify({ message: 'upload success', success: true }) ); }); test('use real file', (done) => { expect.assertions(1); const mockFile = new File(['foo'], 'foo.png', { type: 'image/png', }); option.file = mockFile; option.onSuccess = (_response) => { expect(currentRequest.requestBody.getAll(option.filename)[0].name).toEqual(option.file.name); done(); }; xhrRequest(option); currentRequest.respond( 200, { 'Content-Type': 'application/json' }, JSON.stringify({ message: 'upload success', success: true }) ); }); test('should trigger onError 1', (done) => { expect.assertions(2); option.onError = (progressEvent, response) => { expect(progressEvent.type).toEqual('error'); expect(response).toEqual({}); done(); }; xhrRequest(option); currentRequest.error(); }); test('should trigger onError 2', (done) => { expect.assertions(2); option.onError = (error, response) => { expect(error.toString()).toContain(`cannot POST ${API_URL} 404`); expect(response).toEqual({ success: false, status: 404 }); done(); }; xhrRequest(option); currentRequest.respond(404, {}, JSON.stringify({ success: false, status: 404 })); }); test('should trigger abort', () => { option.headers = { foo: null, form: 'form', }; const { abort } = xhrRequest(option); expect(() => abort()).not.toThrowError(); }); }); describe('other', () => { test('getError function', () => { const msg = `cannot POST ${API_URL} 0`; const err = new Error(msg); err.status = 0; err.method = 'POST'; err.url = API_URL; const xhr = new XMLHttpRequest(); expect(getError(option, xhr)).toEqual(err); }); test('getBody function without text', () => { const xhr = new XMLHttpRequest(); getBody(xhr); }); test('getBody function with text', () => { const xhr = new XMLHttpRequest(); Object.defineProperty(xhr, 'responseText', { value: '{"name": "gio"}', writable: true, }); expect(getBody(xhr)).toEqual({ name: 'gio' }); }); test('getBody function with text catch err', () => { const xhr = new XMLHttpRequest(); Object.defineProperty(xhr, 'responseText', { value: 'hh', writable: true, }); expect(getBody(xhr)).toBe('hh'); }); });
/** * Created by phpNT on 24.09.2015. */
import getPokemonType from './get-pokemon-type' describe('src/utils/get-pokemon-type', () => { it('function getPokemonType - SHOULD return a pokemon type if found', () => { expect(getPokemonType('normal')).toEqual({ name: 'normal', namePtBr: 'Normal', iconUrl: 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/aa/Pok%C3%A9mon_Normal_Type_Icon.svg/120px-Pok%C3%A9mon_Normal_Type_Icon.svg.png', }) }) it('function getPokemonType - SHOULD return a empty object if no type is found', () => { expect(getPokemonType('empty-type')).toEqual({}) }) })
var objectAssign = require('object-assign'); var fieldTestObjectsPath = require('keystone-nightwatch-e2e').fieldTestObjectsPath; var path = require('path'); var TextFieldTestObject = require(path.resolve(fieldTestObjectsPath, 'TextFieldTestObject')); var EmailFieldTestObject = require(path.resolve(fieldTestObjectsPath, 'EmailFieldTestObject')); module.exports = function EmailModelTestConfig (config) { return { name: new TextFieldTestObject(objectAssign({}, config, {fieldName: 'name'})), fieldA: new EmailFieldTestObject(objectAssign({}, config, {fieldName: 'fieldA'})), fieldB: new EmailFieldTestObject(objectAssign({}, config, {fieldName: 'fieldB'})), }; };
/** * Copyright 2013-2019 the original author or authors from the JHipster project. * * This file is part of the JHipster project, see https://www.jhipster.tech/ * for more information. * * 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. */ const chalk = require('chalk'); const shelljs = require('shelljs'); const prompts = require('./prompts'); const writeFiles = require('./files').writeFiles; const BaseDockerGenerator = require('../generator-base-docker'); const { loadFromYoRc, checkImages, generateJwtSecret, configureImageNames, setAppsFolderPaths } = require('../docker-base'); const { setupKubernetesConstants } = require('../kubernetes-base'); const statistics = require('../statistics'); module.exports = class extends BaseDockerGenerator { get initializing() { return { sayHello() { this.log(chalk.white(`${chalk.bold('⭕')} [*BETA*] Welcome to the JHipster OpenShift Generator ${chalk.bold('⭕')}`)); this.log( chalk.white( `Files will be generated in folder: ${chalk.yellow( this.destinationRoot() )} or in the root directory path that you select in the subsequent step` ) ); }, ...super.initializing, checkOpenShift() { if (this.skipChecks) return; const done = this.async(); shelljs.exec('oc version', { silent: true }, (code, stdout, stderr) => { if (stderr) { this.log( `${chalk.yellow.bold('WARNING!')} oc 1.3 or later is not installed on your computer.\n` + 'Make sure you have OpenShift Origin / OpenShift Container Platform and CLI installed. Read' + ' https://github.com/openshift/origin/\n' ); } done(); }); }, loadConfig() { loadFromYoRc.call(this); this.openshiftNamespace = this.config.get('openshiftNamespace'); this.storageType = this.config.get('storageType'); this.registryReplicas = this.config.get('registryReplicas'); }, setupKubernetesConstants }; } get prompting() { return { askForApplicationType: prompts.askForApplicationType, askForPath: prompts.askForPath, askForApps: prompts.askForApps, askForMonitoring: prompts.askForMonitoring, askForServiceDiscovery: prompts.askForServiceDiscovery, askForAdminPassword: prompts.askForAdminPassword, askForOpenShiftNamespace: prompts.askForOpenShiftNamespace, askForStorageType: prompts.askForStorageType, askForDockerRepositoryName: prompts.askForDockerRepositoryName, askForDockerPushCommand: prompts.askForDockerPushCommand }; } get configuring() { return { insight() { statistics.sendSubGenEvent('generator', 'openshift'); }, checkImages, generateJwtSecret, configureImageNames, setAppsFolderPaths, // place holder for future changes (may be prompt or something else) setRegistryReplicas() { this.registryReplicas = 2; }, setPostPromptProp() { this.appConfigs.some(element => { if (element.messageBroker === 'kafka') { this.useKafka = true; return true; } return false; }); }, saveConfig() { this.config.set({ appsFolders: this.appsFolders, directoryPath: this.directoryPath, clusteredDbApps: this.clusteredDbApps, serviceDiscoveryType: this.serviceDiscoveryType, monitoring: this.monitoring, jwtSecretKey: this.jwtSecretKey, dockerRepositoryName: this.dockerRepositoryName, dockerPushCommand: this.dockerPushCommand, openshiftNamespace: this.openshiftNamespace, storageType: this.storageType, registryReplicas: this.registryReplicas }); } }; } get writing() { return writeFiles(); } end() { if (this.warning) { this.log(`\n${chalk.yellow.bold('WARNING!')} OpenShift configuration generated, but no Jib cache found`); this.log('If you forgot to generate the Docker image for this application, please run:'); this.log(this.warningMessage); } else { this.log(`\n${chalk.bold.green('OpenShift configuration successfully generated!')}`); } this.log( `${chalk.yellow.bold( 'WARNING!' )} You will need to push your image to a registry. If you have not done so, use the following commands to tag and push the images:` ); for (let i = 0; i < this.appsFolders.length; i++) { const originalImageName = this.appConfigs[i].baseName.toLowerCase(); const targetImageName = this.appConfigs[i].targetImageName; if (originalImageName !== targetImageName) { this.log(` ${chalk.cyan(`docker image tag ${originalImageName} ${targetImageName}`)}`); } this.log(` ${chalk.cyan(`${this.dockerPushCommand} ${targetImageName}`)}`); } this.log('\nYou can deploy all your apps by running: '); this.log(` ${chalk.cyan(`${this.directoryPath}ocp/ocp-apply.sh`)}`); this.log('OR'); this.log(` ${chalk.cyan(`oc process -f ${this.directoryPath}ocp/registry/scc-config.yml | oc apply -f -`)}`); if (this.monitoring === 'elk') { this.log(` ${chalk.cyan(`oc process -f ${this.directoryPath}ocp/monitoring/jhipster-monitoring.yml | oc apply -f -`)}`); } if (this.monitoring === 'prometheus') { this.log(` ${chalk.cyan(`oc process -f ${this.directoryPath}ocp/monitoring/jhipster-metrics.yml | oc apply -f -`)}`); } if (this.useKafka === true) { this.log(` ${chalk.cyan(`oc process -f ${this.directoryPath}ocp/messagebroker/kafka.yml | oc apply -f -`)}`); } for (let i = 0, regIndex = 0; i < this.appsFolders.length; i++) { const app = this.appConfigs[i]; const appName = app.baseName.toLowerCase(); if (app.searchEngine === 'elasticsearch') { this.log( ` ${chalk.cyan(`oc process -f ${this.directoryPath}ocp/${appName}/${appName}-elasticsearch.yml | oc apply -f -`)}` ); } if (app.serviceDiscoveryType !== false && regIndex++ === 0) { this.log(` ${chalk.cyan(`oc process -f ${this.directoryPath}ocp/registry/application-configmap.yml | oc apply -f -`)}`); if (app.serviceDiscoveryType === 'eureka') { this.log(` ${chalk.cyan(`oc process -f ${this.directoryPath}ocp/registry/jhipster-registry.yml | oc apply -f -`)}`); } else { this.log(` ${chalk.cyan(`oc process -f ${this.directoryPath}ocp/registry/consul.yml | oc apply -f -`)}`); } } if (app.prodDatabaseType !== 'no') { this.log( ` ${chalk.cyan( `oc process -f ${this.directoryPath}ocp/${appName}/${appName}-${app.prodDatabaseType}.yml | oc apply -f -` )}` ); } this.log(` ${chalk.cyan(`oc process -f ${this.directoryPath}ocp/${appName}/${appName}-deployment.yml | oc apply -f -`)}`); } if (this.gatewayNb + this.monolithicNb >= 1) { this.log("\nUse these commands to find your application's IP addresses:"); for (let i = 0; i < this.appsFolders.length; i++) { if (this.appConfigs[i].applicationType === 'gateway' || this.appConfigs[i].applicationType === 'monolith') { this.log(` ${chalk.cyan(`oc get svc ${this.appConfigs[i].baseName}`)}`); } } this.log(); } } };
import React from 'react'; import momentJalaali from 'moment-jalaali'; import DatePicker from '../../../src/components/DatePicker'; class component extends React.Component { constructor(props) { super(props); this.state = { value: momentJalaali() }; } render() { return ( <DatePicker placeholder="e.g. 1993/11/12 12:03 PM" value={this.state.value} onChange={value => this.setState({ value })} /> ); } } const title = 'Placeholder'; const code = `class component extends React.Component { constructor(props) { super(props); this.state = {value: momentJalaali()}; } render() { return <DatePicker placeholder="e.g. 1993/11/12 12:03 PM" value={this.state.value} onChange={value => this.setState({ value })} /> } } `; const Default = { component, title, code }; export default Default;
const function807 = function (t, e, i) { "use strict"; var n = this && this.__extends || function () { var t = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (t, e) { t.__proto__ = e } || function (t, e) { for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i]) }; return function (e, i) { function n() { this.constructor = e } t(e, i), e.prototype = null === i ? Object.create(i) : (n.prototype = i.prototype, new n) } }(); Object.defineProperty(e, "__esModule", { value: !0 }); var o = i(5), r = i(19), s = i(8), a = i(40), _ = i(12), u = i(6), l = i(3), c = i(338), h = i(1), p = function (t) { function e(e, i) { var n = t.call(this, e) || this; return n._mainView = i, n._telopBG = new PIXI.Sprite, n._telopLineTop = new PIXI.Sprite, n._telopLineBottom = new PIXI.Sprite, n._telopText = new PIXI.Sprite, n._particles = new d, n } return n(e, t), e.prototype._03_link = function () { this._04_showTelop() }, e.prototype._04_showTelop = function () { var t = this; this._telopBG.texture = l.REMODEL_ANIMATION.getTexture(2), this._telopBG.alpha = .35, this._telopBG.anchor.set(.5), this._telopBG.position.set(o.default.width / 2, o.default.height / 2), this._telopBG.scale.y = 0, this.addChild(this._telopBG); var e = l.REMODEL_ANIMATION.getTexture(3); this._telopLineTop.texture = e, this._telopLineTop.anchor.set(.5), this._telopLineTop.position.set(o.default.width / 2, o.default.height / 2), this.addChild(this._telopLineTop), this._telopLineBottom.texture = e, this._telopLineBottom.anchor.set(.5), this._telopLineBottom.position.set(o.default.width / 2, o.default.height / 2), this.addChild(this._telopLineBottom); var i, n = new r.TweenTask; i = createjs.Tween.get(this._telopBG.scale).to({ y: 1 }, 300), n.addTween(i), i = createjs.Tween.get(this._telopLineTop).to({ y: o.default.height / 2 - 155 }, 300), n.addTween(i), i = createjs.Tween.get(this._telopLineBottom).to({ y: o.default.height / 2 + 155 }, 300), n.addTween(i), n.start(function () { t._telopText.texture = l.REMODEL_ANIMATION.getTexture(9), t._telopText.x = o.default.width, t._telopText.y = Math.round(o.default.height / 2 - t._telopText.height / 2), t.addChild(t._telopText), createjs.Tween.get(t._telopText).to({ x: 178 }, 400).call(function () { u.SE.play("226"), t.addChild(t._particles), t._particles.play() }).to({ x: 63 }, 1700).call(function () { t._05_waitClick() }) }) }, e.prototype._05_waitClick = function () { var t = this, e = new a.GearBtnHome; e.initialize(), e.activate(), e.position.set(1140, 660), this.addChild(e); var i = new s.AreaBox(0); i.buttonMode = !0, this.addChild(i), i.once(h.EventType.CLICK, function () { t.removeChild(i), t._06_whiteInOut(e) }) }, e.prototype._06_whiteInOut = function (t) { var e = this; this._white.alpha = 0, this.addChild(this._white), createjs.Tween.get(this._white).to({ alpha: 1 }, 500).call(function () { e.removeChild(e._background), e.removeChild(e._ship), e.removeChild(e._telopBG), e.removeChild(e._telopLineTop), e.removeChild(e._telopLineBottom), e.removeChild(e._telopText), e.removeChild(e._particles), e.removeChild(t), t.dispose(), e._mainView.visible = !0 }).to({ alpha: 0 }, 500).call(function () { e.removeChild(e._white), null != e._cb_onComplete && e._cb_onComplete() }) }, e.prototype.dispose = function () { this.removeChildren(), t.prototype.dispose.call(this), this._telopBG = null, this._telopLineTop = null, this._telopLineBottom = null, this._telopText = null, this._particles.dispose(), this._particles = null }, e }(c.PowerUpAnimation); e.PowerUpAnimationSuccess = p; var d = function (t) { function e() { var e = t.call(this) || this; e._particles = []; for (var i = [[-459, -59], [-392, -74], [-332, 51], [-237, -89], [-158, 66], [-96, -54], [-8, 60], [39, -65], [141, -35], [239, 63], [308, -54], [420, 45]], n = l.REMODEL_ANIMATION.getTexture(8), o = 0; o < 12; o++) { var r = new _.Sprite(n); r.anchor.set(.5), r.scale.set(0), r.x = i[o][0] + 600, r.y = i[o][1] + 360, e.addChild(r), e._particles.push(r) } return e } return n(e, t), e.prototype.play = function () { this._removeTweens(), this._tweens = []; for (var t = 0; t < this._particles.length; t++) { var e = this._particles[t]; e.scale.set(0); var i = createjs.Tween.get(e).wait(100 * t).to({ scaleX: 1.5, scaleY: 1.5 }, 100).to({ scaleX: 0, scaleY: 0 }, 100); this._tweens.push(i) } }, e.prototype.dispose = function () { this._removeTweens(), this.removeChildren(), this._particles = null }, e.prototype._removeTweens = function () { if (null != this._tweens) { for (var t = 0, e = this._tweens; t < e.length; t++) { e[t].setPaused(!0) } this._tweens = null } }, e }(PIXI.Container) }
import {CSS_PREFIX} from '../const'; import {GrammarRegistry} from '../grammar-registry'; import {LayerLabels} from './decorators/layer-labels'; import {d3_animationInterceptor} from '../utils/d3-decorators'; import {utils} from '../utils/utils'; import {utilsDom} from '../utils/utils-dom'; import {utilsDraw} from '../utils/utils-draw'; import d3 from 'd3'; const d3Data = ((node) => d3.select(node).data()[0]); const Interval = { init(xConfig) { const config = Object.assign({}, xConfig); config.guide = (config.guide || {}); config.guide = utils.defaults( (config.guide), { animationSpeed: 0, avoidScalesOverflow: true, maxHighlightDistance: 32, prettify: true, sortByBarHeight: true, enableColorToBarPosition: !config.stack }); config.guide.size = utils.defaults( (config.guide.size || {}), { enableDistributeEvenly: true }); config.guide.label = utils.defaults( (config.guide.label || {}), { position: (config.flip ? (config.stack ? [ 'r-', 'l+', 'hide-by-label-height-horizontal', 'cut-label-horizontal' ] : [ 'outside-then-inside-horizontal', 'auto:hide-on-label-label-overlap' ] ) : (config.stack ? [ 'rotate-on-size-overflow', 't-', 'b+', 'hide-by-label-height-vertical', 'cut-label-vertical', 'auto:hide-on-label-label-overlap' ] : [ 'rotate-on-size-overflow', 'outside-then-inside-vertical', 'auto:hide-on-label-label-overlap' ] ) ) }); const avoidScalesOverflow = config.guide.avoidScalesOverflow; const enableColorPositioning = config.guide.enableColorToBarPosition; const enableDistributeEvenly = config.guide.size.enableDistributeEvenly; config.transformRules = [ config.flip && GrammarRegistry.get('flip'), config.stack && GrammarRegistry.get('stack'), enableColorPositioning && GrammarRegistry.get('positioningByColor') ] .filter(x => x) .concat(config.transformModel || []); config.adjustRules = [ (enableDistributeEvenly && ((prevModel, args) => { const sizeCfg = utils.defaults( (config.guide.size || {}), { defMinSize: config.guide.prettify ? 3 : 0, defMaxSize: config.guide.prettify ? 40 : Number.MAX_VALUE }); const params = Object.assign( {}, args, { defMin: sizeCfg.defMinSize, defMax: sizeCfg.defMaxSize, minLimit: sizeCfg.minSize, maxLimit: sizeCfg.maxSize }); return GrammarRegistry.get('size_distribute_evenly')(prevModel, params); })), ( avoidScalesOverflow && enableDistributeEvenly && ((prevModel, args) => { const params = Object.assign({}, args, { sizeDirection: 'x' }); return GrammarRegistry.get('avoidScalesOverflow')(prevModel, params); }) ), (config.stack && GrammarRegistry.get('adjustYScale')) ].filter(x => x); return config; }, addInteraction() { const node = this.node(); const createFilter = ((data, falsy) => ((row) => row === data ? true : falsy)); node.on('highlight', (sender, filter) => this.highlight(filter)); node.on('data-hover', ((sender, e) => this.highlight(createFilter(e.data, null)))); node.on('data-click', ((sender, e) => this.highlight(createFilter(e.data, e.data ? false : null)))); }, draw() { const node = this.node(); const config = node.config; const options = config.options; // TODO: hide it somewhere options.container = options.slot(config.uid); const prettify = config.guide.prettify; const baseCssClass = `i-role-element i-role-datum bar ${CSS_PREFIX}bar`; const screenModel = node.screenModel; const d3Attrs = this.buildModel(screenModel, {prettify, minBarH: 1, minBarW: 1, baseCssClass}); const createUpdateFunc = d3_animationInterceptor; const barX = config.flip ? 'y' : 'x'; const barY = config.flip ? 'x' : 'y'; const barH = config.flip ? 'width' : 'height'; const barW = config.flip ? 'height' : 'width'; const fibers = screenModel.toFibers(); const data = fibers .reduce((arr, f) => arr.concat(f), []); const barClass = d3Attrs.class; const updateAttrs = utils.omit(d3Attrs, 'class'); const bars = options.container.selectAll('.bar') .data(data, screenModel.id); bars.exit() .classed('tau-removing', true) .call(createUpdateFunc( config.guide.animationSpeed, null, { [barX]: function () { var d3This = d3.select(this); var x = d3This.attr(barX) - 0; var w = d3This.attr(barW) - 0; return x + w / 2; }, [barY]: function () { return this.getAttribute('data-zero'); }, [barW]: 0, [barH]: 0 }, // ((node) => d3.select(node).remove()) ((node) => { // NOTE: Sometimes nodes are removed after // they re-appear by filter. var el = d3.select(node); if (el.classed('tau-removing')) { el.remove(); } }) )); bars.call(createUpdateFunc( config.guide.animationSpeed, null, updateAttrs )).attr('class', barClass) .attr('data-zero', screenModel[`${barY}0`]); bars.enter() .append('rect') .call(createUpdateFunc( config.guide.animationSpeed, {[barY]: screenModel[`${barY}0`], [barH]: 0}, updateAttrs )).attr('class', barClass) .attr('data-zero', screenModel[`${barY}0`]); node.subscribe(new LayerLabels(screenModel.model, screenModel.model.flip, config.guide.label, options) .draw(fibers)); const sortByWidthThenY = ((a, b) => { var dataA = d3Data(a); var dataB = d3Data(b); if (d3Attrs.width(dataA) === d3Attrs.width(dataB)) { return (d3Attrs.y(dataA) - d3Attrs.y(dataB)); } return (d3Attrs.width(dataB) - d3Attrs.width(dataA)); }); const sortByHeightThenX = ((a, b) => { var dataA = d3Data(a); var dataB = d3Data(b); if (d3Attrs.height(dataA) === d3Attrs.height(dataB)) { return (d3Attrs.x(dataA) - d3Attrs.x(dataB)); } return (d3Attrs.height(dataB) - d3Attrs.height(dataA)); }); this._barsSorter = (config.guide.sortByBarHeight ? (config.flip ? sortByWidthThenY : sortByHeightThenX) : (() => { var ids = data.reduce((obj, d, i) => { obj[screenModel.model.id(d)] = i; return obj; }, {}); return (a, b) => ( ids[screenModel.model.id(d3Data(a))] - ids[screenModel.model.id(d3Data(b))] ); })() ); const elementsOrder = { rect: 0, text: 1 }; this._typeSorter = ((a, b) => elementsOrder[a.tagName] - elementsOrder[b.tagName]); this._sortElements(this._typeSorter, this._barsSorter); node.subscribe(bars); this._boundsInfo = this._getBoundsInfo(bars[0]); }, buildModel(screenModel, {prettify, minBarH, minBarW, baseCssClass}) { const barSize = ((d) => { var w = screenModel.size(d); if (prettify) { w = Math.max(minBarW, w); } return w; }); var model; const value = (d) => d[screenModel.model.scaleY.dim]; if (screenModel.flip) { let barHeight = ((d) => Math.abs(screenModel.x(d) - screenModel.x0(d))); model = { y: ((d) => screenModel.y(d) - barSize(d) * 0.5), x: ((d) => { const x = Math.min(screenModel.x0(d), screenModel.x(d)); if (prettify) { // decorate for better visual look & feel const h = barHeight(d); const dx = value(d); var offset = 0; if (dx === 0) {offset = 0;} if (dx > 0) {offset = (h);} if (dx < 0) {offset = (0 - minBarH);} const isTooSmall = (h < minBarH); return (isTooSmall) ? (x + offset) : (x); } else { return x; } }), height: ((d) => barSize(d)), width: ((d) => { const h = barHeight(d); if (prettify) { // decorate for better visual look & feel return (value(d) === 0) ? h : Math.max(minBarH, h); } return h; }) }; } else { let barHeight = ((d) => Math.abs(screenModel.y(d) - screenModel.y0(d))); model = { x: ((d) => screenModel.x(d) - barSize(d) * 0.5), y: ((d) => { var y = Math.min(screenModel.y0(d), screenModel.y(d)); if (prettify) { // decorate for better visual look & feel const h = barHeight(d); const isTooSmall = (h < minBarH); y = ((isTooSmall && (value(d) > 0)) ? (y - minBarH) : y); } return y; }), width: ((d) => barSize(d)), height: ((d) => { var h = barHeight(d); if (prettify) { // decorate for better visual look & feel h = ((value(d) === 0) ? h : Math.max(minBarH, h)); } return h; }) }; } return Object.assign( model, { class: ((d) => `${baseCssClass} ${screenModel.class(d)}`), fill: ((d) => screenModel.color(d)) }); }, _sortElements(...sorters) { const container = this.node().config.options.container.node(); utilsDom.sortChildren(container, utils.createMultiSorter(...sorters)); }, _getBoundsInfo(bars) { if (bars.length === 0) { return null; } const screenModel = this.node().screenModel; const {flip} = this.node().config; const items = bars .map((node) => { const data = d3.select(node).data()[0]; const x = screenModel.x(data); const x0 = screenModel.x0(data); const y = screenModel.y(data); const y0 = screenModel.y0(data); const w = Math.abs(x - x0); const h = Math.abs(y - y0); const cx = ((x + x0) / 2); const cy = ((y + y0) / 2); const invert = (y > y0); const box = { top: (cy - h / 2), right: (cx + w / 2), bottom: (cy + h / 2), left: (cx - w / 2) }; return {node, data, cx, cy, box, invert}; }); const bounds = items.reduce( (bounds, {box}) => { bounds.left = Math.min(box.left, bounds.left); bounds.right = Math.max(box.right, bounds.right); bounds.top = Math.min(box.top, bounds.top); bounds.bottom = Math.max(box.bottom, bounds.bottom); return bounds; }, { left: Number.MAX_VALUE, right: Number.MIN_VALUE, top: Number.MAX_VALUE, bottom: Number.MIN_VALUE }); const ticks = utils.unique(items.map(flip ? ((item) => item.cy) : ((item) => item.cx))).sort((a, b) => a - b); const groups = ticks.reduce(((obj, value) => (obj[value] = [], obj)), {}); items.forEach((item) => { const tick = ticks.find(flip ? ((value) => item.cy === value) : ((value) => item.cx === value)); groups[tick].push(item); }); const split = (values) => { if (values.length === 1) { return groups[values]; } const midIndex = Math.ceil(values.length / 2); const middle = (values[midIndex - 1] + values[midIndex]) / 2; return { middle, lower: split(values.slice(0, midIndex)), greater: split(values.slice(midIndex)) }; }; const tree = split(ticks); return {bounds, tree}; }, getClosestElement(_cursorX, _cursorY) { if (!this._boundsInfo) { return null; } const {bounds, tree} = this._boundsInfo; const container = this.node().config.options.container; const {flip} = this.node().config; const translate = utilsDraw.getDeepTransformTranslate(container.node()); const cursorX = (_cursorX - translate.x); const cursorY = (_cursorY - translate.y); const {maxHighlightDistance} = this.node().config.guide; if ((cursorX < bounds.left - maxHighlightDistance) || (cursorX > bounds.right + maxHighlightDistance) || (cursorY < bounds.top - maxHighlightDistance) || (cursorY > bounds.bottom + maxHighlightDistance) ) { return null; } const measureCursor = (flip ? cursorY : cursorX); const valueCursor = (flip ? cursorX : cursorY); const isBetween = ((value, start, end) => value >= start && value <= end); const closestElements = (function getClosestElements(el) { if (Array.isArray(el)) { return el; } return getClosestElements(measureCursor > el.middle ? el.greater : el.lower); })(tree) .map((el) => { const elStart = (flip ? el.box.left : el.box.top); const elEnd = (flip ? el.box.right : el.box.bottom); const cursorInside = isBetween(valueCursor, elStart, elEnd); if (!cursorInside && (Math.abs(valueCursor - elStart) > maxHighlightDistance) && (Math.abs(valueCursor - elEnd) > maxHighlightDistance) ) { return null; } const distToValue = Math.abs(valueCursor - ((el.invert !== flip) ? elEnd : elStart)); return Object.assign(el, {distToValue, cursorInside}); }) .filter((el) => el) .sort(((a, b) => { if (a.cursorInside !== b.cursorInside) { return (b.cursorInside - a.cursorInside); } return (Math.abs(a.distToValue) - Math.abs(b.distToValue)); })) .map((el) => { const x = (el.cx); const y = (el.cy); const distance = Math.abs(flip ? (cursorY - y) : (cursorX - x)); const secondaryDistance = Math.abs(flip ? (cursorX - x) : (cursorY - y)); return {node: el.node, data: el.data, distance, secondaryDistance, x, y}; }); return (closestElements[0] || null); }, highlight(filter) { const x = 'graphical-report__highlighted'; const _ = 'graphical-report__dimmed'; const container = this.node().config.options.container; const classed = { [x]: ((d) => filter(d) === true), [_]: ((d) => filter(d) === false) }; container .selectAll('.bar') .classed(classed); container .selectAll('.i-role-label') .classed(classed); this._sortElements( (a, b) => (filter(d3Data(a)) - filter(d3Data(b))), this._typeSorter, this._barsSorter ); } }; export {Interval};
module.exports = ({ changes }) => changes;
/** * @ngdoc module * @name material.components.slider * @description Slider module! */ angular.module('material.components.slider', []) .directive('materialSlider', [ '$window', materialSliderDirective ]); /** * @ngdoc directive * @name materialSlider * @module material.components.slider * @restrict E * * @description * Slider directive! * */ function materialSliderDirective($window) { var MIN_VALUE_CSS = 'material-slider-min'; var ACTIVE_CSS = 'material-active'; function rangeSettings(rangeEle) { return { min: parseInt( rangeEle.min !== "" ? rangeEle.min : 0, 10 ), max: parseInt( rangeEle.max !== "" ? rangeEle.max : 100, 10 ), step: parseInt( rangeEle.step !== "" ? rangeEle.step : 1, 10 ) } } return { restrict: 'E', scope: true, transclude: true, template: '<div class="material-track" ng-transclude></div>', link: link }; // ********************************************************** // Private Methods // ********************************************************** function link(scope, element, attr) { var input = element.find('input'); var ngModelCtrl = angular.element(input).controller('ngModel'); if(!ngModelCtrl || input[0].type !== 'range') return; var rangeEle = input[0]; var trackEle = angular.element( element[0].querySelector('.material-track') ); trackEle.append('<div class="material-fill"><div class="material-thumb"></div></div>'); var fillEle = trackEle[0].querySelector('.material-fill'); if(input.attr('step')) { var settings = rangeSettings(rangeEle); var tickCount = (settings.max - settings.min) / settings.step; var tickMarkersEle = angular.element('<div class="material-tick-markers material-display-flex"></div>'); for(var i=0; i<tickCount; i++) { tickMarkersEle.append('<div class="material-tick material-flex"></div>'); } trackEle.append(tickMarkersEle); } input.on('mousedown touchstart', function(e){ trackEle.addClass(ACTIVE_CSS); }); input.on('mouseup touchend', function(e){ trackEle.removeClass(ACTIVE_CSS); }); function render() { var settings = rangeSettings(rangeEle); var adjustedValue = parseInt(ngModelCtrl.$viewValue, 10) - settings.min; var fillRatio = (adjustedValue / (settings.max - settings.min)); fillEle.style.width = (fillRatio * 100) + '%'; if(fillRatio <= 0) { element.addClass(MIN_VALUE_CSS); } else { element.removeClass(MIN_VALUE_CSS); } } scope.$watch( function () { return ngModelCtrl.$viewValue; }, render ); } }
import React from 'react'; import { Icon } from 'semantic-ui-react'; import { navigation, Table, TableHeaderCell, TableHeader, TableRow, TableRowCell } from 'nr1'; const getAlertColor = alertHighest => { switch (alertHighest) { case 'NOT_ALERTING': { return 'green'; } case 'WARNING': { return 'orange'; } case 'CRITICAL': { return 'red'; } } return 'grey'; }; export default class EntityTable extends React.Component { render() { const { popupData, updateState } = this.props; const { properties } = popupData; let entities = properties.entities || []; const nestedEntites = []; entities.forEach(e => { if (e.relationships) { e.relationships.forEach(r => { if (r.target && r.target.entity) { nestedEntites.push(r.target.entity); } }); } }); entities = [...entities, ...nestedEntites].filter( e => e.entityType !== 'DASHBOARD_ENTITY' ); return ( <Table items={entities || []} onSelect={(evt, { item }) => (item.selected = evt.target.checked)} > <TableHeader> <TableHeaderCell value={({ item }) => item.alertSeverity || 'UNCONFIGURED'} width="fit-content" alignmentType={TableRowCell.ALIGNMENT_TYPE.LEFT} /> <TableHeaderCell // width="10px" value={({ item }) => item.name} alignmentType={TableRowCell.ALIGNMENT_TYPE.LEFT} > Name </TableHeaderCell> <TableHeaderCell value={({ item }) => item.entityType}> Type </TableHeaderCell> </TableHeader> {({ item }) => { const alertColor = getAlertColor(item.alertSeverity); return ( <TableRow onClick={() => { updateState({ hidden: false }); navigation.openStackedEntity(item.guid); }} > <TableRowCell> <Icon color={alertColor} name="circle" /> </TableRowCell> <TableRowCell>{item.name}</TableRowCell> <TableRowCell>{item.entityType}</TableRowCell> </TableRow> ); }} </Table> ); } }
import React from "react"; import { Square } from "./Square"; export class CreateSquares extends React.Component { render() { const change = this.props.shuffle; console.log(change); function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } const theArray = this.props.list; console.log(theArray); const remove = this.props.removeSquare; const clickOn = this.props.onClickSquare; const things = change ? shuffle(theArray) : theArray; const rows = things.map(function(ele, i) { var v = ele.value; // console.log("V" + v); const height = ele.height; const width = ele.width; return ( <Square key={ele.id} id={ele.id} value={v} color={ele.color} textColor={ele.textColor} removeSquare={remove} onClickSquare={clickOn} height={height} width={width} doClick={true} /> ); // return <h1>Hi</h1>; }); // console.log(rows); return rows; } }
//Requires const modulename = 'WebServer:VerifyNuiAuth'; const { customAlphabet } = require('nanoid'); const dict51 = require('nanoid-dictionary/nolookalikes'); const nanoid = customAlphabet(dict51, 20); const { dir, log, logOk, logWarn, logError } = require('../../extras/console')(modulename); //Helper functions const sessDuration = 60 * 60 * 1000; //one hour /** * Verify login * * NOTE: good part of the header validation (including origin) is already in * ctxUtils.js, but here we are way more verbose with the errors, and strict * with our validations. * * FIXME: add better logging * FIXME: will this method be deprecated? * @param {object} ctx */ module.exports = async function VerifyNuiAuth(ctx) { // Check sus IPs if (!GlobalData.loopbackInterfaces.includes(ctx.ip) && !GlobalData.isZapHosting) { if (GlobalData.verbose) { logWarn(`NUI Auth Failed: ctx.ip (${ctx.ip}) not in ${JSON.stringify(GlobalData.loopbackInterfaces)}.`); } return ctx.send({isAdmin: false, reason: 'Invalid Request: source'}); } // Check missing headers if (typeof ctx.request.headers['x-txadmin-token'] !== 'string') { return ctx.send({isAdmin: false, reason: 'Invalid Request: token header'}); } if (typeof ctx.request.headers['x-txadmin-identifiers'] !== 'string') { return ctx.send({isAdmin: false, reason: 'Invalid Request: identifiers header'}); } // Check token value if (ctx.request.headers['x-txadmin-token'] !== globals.webServer.fxWebPipeToken) { if (GlobalData.verbose) { logWarn(`NUI Auth Failed: token received ${ctx.request.headers['x-txadmin-token']} !== expected ${globals.webServer.fxWebPipeToken}.`); } return ctx.send({isAdmin: false, reason: 'Unauthorized: token value'}); } // Check identifier array const identifiers = ctx.request.headers['x-txadmin-identifiers'] .split(',') .map((i) => i.trim().toLowerCase()) .filter((i) => i.length); if (!identifiers.length) { return ctx.send({isAdmin: false, reason: 'Unauthorized: empty identifier array'}); } try { const admin = globals.adminVault.getAdminByIdentifiers(identifiers); if (!admin) { if (GlobalData.verbose) { logWarn(`NUI Auth Failed: no admin found with identifiers ${JSON.stringify(identifiers)}.`); } return ctx.send({isAdmin: false, reason: 'Unauthorized: admin not found'}); } //Setting up session const providerWithPicture = Object.values(admin.providers).find((provider) => provider.data && provider.data.picture); ctx.session.auth = { username: admin.name, picture: (providerWithPicture) ? providerWithPicture.data.picture : undefined, password_hash: admin.password_hash, expires_at: Math.ceil((+new Date + sessDuration) / 1000), isWebInterface: false, //FIXME: Tabarra needs to build security around this value }; //dir(admin); const permissions = admin.master ? ['all_permissions'] : admin.permissions; ctx.send({ isAdmin: true, permissions, expiration: Date.now() + sessDuration, luaToken: nanoid(), }); ctx.utils.logAction(`logged in from ${ctx.ip} via in-game ui`); globals.databus.txStatsData.login.origins.webpipe++; globals.databus.txStatsData.login.methods.nui++; } catch (error) { logWarn(`Failed to authenticate NUI user with error: ${error.message}`); if (GlobalData.verbose) dir(error); return ctx.send({isAdmin: false, reason: 'internal error'}); } };
import React from 'react'; import { render, fireEvent, wait } from '@testing-library/react'; import { MutationComponent, withApolloMockProvider, withNotificationProvider, TESTING_STATE, BUTTON_TEST_ID, repositoryMock, } from 'components/Lambdas/helpers/testing'; import { formatMessage } from 'components/Lambdas/helpers/misc'; import { GQL_MUTATIONS } from 'components/Lambdas/constants'; import { useCreateRepository, prepareCreateLambdaInput, } from '../useCreateRepository'; import { CREATE_REPOSITORY_DATA_MOCK, CREATE_REPOSITORY_ERROR_MOCK, } from '../testMocks'; describe('useCreateRepository', () => { const variables = { name: repositoryMock.name, namespace: repositoryMock.namespace, spec: repositoryMock.spec, }; const mutationInput = { name: repositoryMock.name, namespace: repositoryMock.namespace, spec: repositoryMock.spec, }; it('should see notification with error message if there is an error', async () => { const mockProvider = withApolloMockProvider({ component: ( <MutationComponent hook={useCreateRepository} mutationInput={mutationInput} /> ), mocks: [CREATE_REPOSITORY_ERROR_MOCK(variables)], }); const { getByText, getByTestId } = render( withNotificationProvider({ component: mockProvider, }), ); const message = formatMessage( GQL_MUTATIONS.CREATE_REPOSITORY.ERROR_MESSAGE, { repositoryName: repositoryMock.name, error: `Network error: ${TESTING_STATE.ERROR}`, }, ); const button = getByTestId(BUTTON_TEST_ID); fireEvent.click(button); await wait(() => { expect(getByText(message)).toBeInTheDocument(); }); }); it("should see notification with success message if there isn't an error", async () => { const mockProvider = withApolloMockProvider({ component: ( <MutationComponent hook={useCreateRepository} mutationInput={mutationInput} /> ), mocks: [CREATE_REPOSITORY_DATA_MOCK(variables)], }); const { getByText, getByTestId } = render( withNotificationProvider({ component: mockProvider, }), ); const message = formatMessage( GQL_MUTATIONS.CREATE_REPOSITORY.SUCCESS_MESSAGE, { repositoryName: repositoryMock.name, }, ); const button = getByTestId(BUTTON_TEST_ID); fireEvent.click(button); await wait(() => { expect(getByText(message)).toBeInTheDocument(); }); }); });
import React, { useMemo } from 'react'; import moment from 'moment'; import Page from '../../components/Page'; // import HomeImage from '../../assets/img/background.png'; import CashImage from '../../assets/img/CFN.png'; import Image from 'material-ui-image'; import styled from 'styled-components'; import { Alert } from '@material-ui/lab'; // import { createGlobalStyle } from 'styled-components'; import CountUp from 'react-countup'; import CardIcon from '../../components/CardIcon'; import TokenSymbol from '../../components/TokenSymbol'; import useTombStats from '../../hooks/useTombStats'; import useLpStats from '../../hooks/useLpStats'; import useModal from '../../hooks/useModal'; import useZap from '../../hooks/useZap'; import useBondStats from '../../hooks/useBondStats'; import usetShareStats from '../../hooks/usetShareStats'; import useTotalValueLocked from '../../hooks/useTotalValueLocked'; import useGenesisPoolAllocationTimes from '../../hooks/useGenesisPoolAllocationTimes'; import useMeteorPoolAllocationTimes from '../../hooks/useMeteorPoolAllocationTimes'; import ProgressCountdown from '../Cemetery/ProgressCountdown'; import { tomb as tombTesting, tShare as tShareTesting } from '../../tomb-finance/deployments/deployments.testing.json'; import { tomb as tombProd, tShare as tShareProd } from '../../tomb-finance/deployments/deployments.mainnet.json'; import MetamaskFox from '../../assets/img/metamask-fox.svg'; import TwitterImage from '../../assets/img/twitter.svg'; import DiscordImage from '../../assets/img/discord.svg'; import { Box, Button, Card, CardContent, Grid, Paper } from '@material-ui/core'; import ZapModal from '../Bank/components/ZapModal'; import { makeStyles } from '@material-ui/core/styles'; import useTombFinance from '../../hooks/useTombFinance'; // const BackgroundImage = createGlobalStyle` // body { // background: url(${HomeImage}) no-repeat !important; // background-size: cover !important; // } // `; const useStyles = makeStyles((theme) => ({ button: { [theme.breakpoints.down('415')]: { marginTop: '10px', }, }, })); const StyledLink = styled.a` font-weight: 700; text-decoration: none; `; const Home = () => { const classes = useStyles(); const TVL = useTotalValueLocked(); const tombAvaxLpStats = useLpStats('CFN-AVAX-LP'); const tShareAvaxLpStats = useLpStats('CSHARE-AVAX-LP'); const tombStats = useTombStats(); const tShareStats = usetShareStats(); const tBondStats = useBondStats(); const tombFinance = useTombFinance(); // const { balance } = useBurnedCSHARES(); const balance = 0; const { from, to } = useGenesisPoolAllocationTimes(); const { from: mfrom, to: mto } = useMeteorPoolAllocationTimes(); const isStart = Date.now() >= from.getTime(); const isOver = Date.now() >= to.getTime(); const isMStart = Date.now() >= mfrom.getTime(); const isMOver = Date.now() >= mto.getTime(); let tomb; let tShare; if (!process.env.NODE_ENV || process.env.NODE_ENV === 'production') { tomb = tombTesting; tShare = tShareTesting; } else { tomb = tombProd; tShare = tShareProd; } const buyTombAddress = `https://traderjoexyz.com/trade?outputCurrency=${tomb?.address}#/` const buyTShareAddress = `https://traderjoexyz.com/trade?outputCurrency=${tShare?.address}#/` const tombLPStats = useMemo(() => (tombAvaxLpStats ? tombAvaxLpStats : null), [tombAvaxLpStats]); const tshareLPStats = useMemo(() => (tShareAvaxLpStats ? tShareAvaxLpStats : null), [tShareAvaxLpStats]); const tombPriceInDollars = useMemo( () => (tombStats ? Number(tombStats.priceInDollars).toFixed(2) : null), [tombStats], ); const tombPriceInAVAX = useMemo(() => (tombStats ? Number(tombStats.tokenInAvax).toFixed(4) : null), [tombStats]); const tombCirculatingSupply = useMemo(() => (tombStats ? String(tombStats.circulatingSupply) : null), [tombStats]); const tombTotalSupply = useMemo(() => (tombStats ? String(tombStats.totalSupply) : null), [tombStats]); const tSharePriceInDollars = useMemo( () => (tShareStats ? Number(tShareStats.priceInDollars).toFixed(2) : null), [tShareStats], ); const tSharePriceInAVAX = useMemo( () => (tShareStats ? Number(tShareStats.tokenInAvax).toFixed(4) : null), [tShareStats], ); const tShareCirculatingSupply = useMemo( () => (tShareStats ? String(tShareStats.circulatingSupply) : null), [tShareStats], ); const tShareTotalSupply = useMemo(() => (tShareStats ? String(tShareStats.totalSupply) : null), [tShareStats]); const tBondPriceInDollars = useMemo( () => (tBondStats ? Number(tBondStats.priceInDollars).toFixed(2) : null), [tBondStats], ); const tBondPriceInAVAX = useMemo(() => (tBondStats ? Number(tBondStats.tokenInAvax).toFixed(4) : null), [tBondStats]); const tBondCirculatingSupply = useMemo( () => (tBondStats ? String(tBondStats.circulatingSupply) : null), [tBondStats], ); const tBondTotalSupply = useMemo(() => (tBondStats ? String(tBondStats.totalSupply) : null), [tBondStats]); const tombLpZap = useZap({ depositTokenName: 'CFN-AVAX-LP' }); const tshareLpZap = useZap({ depositTokenName: 'CSHARE-AVAX-LP' }); const [onPresentTombZap, onDissmissTombZap] = useModal( <ZapModal decimals={18} onConfirm={(zappingToken, tokenName, amount) => { if (Number(amount) <= 0 || isNaN(Number(amount))) return; tombLpZap.onZap(zappingToken, tokenName, amount); onDissmissTombZap(); }} tokenName={'CFN-AVAX-LP'} />, ); const [onPresentTshareZap, onDissmissTshareZap] = useModal( <ZapModal decimals={18} onConfirm={(zappingToken, tokenName, amount) => { if (Number(amount) <= 0 || isNaN(Number(amount))) return; tshareLpZap.onZap(zappingToken, tokenName, amount); onDissmissTshareZap(); }} tokenName={'CSHARE-AVAX-LP'} />, ); return ( <Page> {/* <BackgroundImage /> */} <Grid container spacing={3}> {/* Logo */} <Grid container item xs={12} sm={4} justifyContent="center"> {/* <Paper>xs=6 sm=3</Paper> */} <Image color="none" style={{ width: "235px", paddingTop: '0px', height: '235px' }} src={CashImage} /> </Grid> {/* Explanation text */} <Grid item xs={12} sm={8}> <Paper> <Box p={4}> <h2>Welcome to CaffeineFund!</h2> <p>Pegged to the price of 0.1 AVAX via seigniorage.</p> <p> <StyledLink href="/farms" style={{ color: '#05147c' }} >Stake</StyledLink> your CFN-AVAX LP tokens to earn CSHARE seigniorage rewards. </p> <p>To maximize profits, stake your harvested CSHAREs in the <StyledLink href="/boardroom" style={{ color: '#05147c' }} >Boardroom</StyledLink> to earn more CFN!</p> { isMStart && !isMOver ? <a href="/farms" style={{fontSize:"24px", fontWeight:"600"}}>CSHARE Reward Pools are live now!</a> : !isMStart ? <div style={{display:'flex'}}> CSHARE Reward Pools Launch In: <ProgressCountdown base={moment().toDate()} hideBar={true} deadline={mfrom} description="Pool Start" /> </div> : null } <br/> { isStart && !isOver ? <a href="/farms" style={{fontSize:"24px", fontWeight:"600"}}>Genesis Pools are live now!</a> : !isStart ? <div style={{display:'flex'}}> Genesis Pools Launch In: <ProgressCountdown base={moment().toDate()} hideBar={true} deadline={from} description="Pool Start" /> </div> : null } </Box> </Paper> </Grid> <Grid container justifyContent="center"> <Box mt={3} mb={1} style={{ padding: '0 10px' }}> <Alert variant="filled" severity="warning"> Do your own research before investing. Investing is risky and may result in monetary loss. CaffeineFund is beta software and may contain bugs. By using CaffeineFund, you agree that the CaffeineFund team is not responsible for any financial losses from investing in CaffeineFund. </Alert> </Box> </Grid> <Grid item xs={12} sm={12} align="center"> <Button target="_blank" href="https://twitter.com/CaffeineFund" style={{ margin: '0 10px', backgroundColor:'#1da1f2', padding:'8px 15px' }}> <img alt="twitter" src={TwitterImage} className={classes.img} style={{marginRight:'10px'}}/> Twitter </Button> <Button target="_blank" href="https://discord.gg/9BV3bTd646" style={{ margin: '0 10px', background:'#5865f2', padding:'8px 15px' }}> <img alt="discord" src={DiscordImage} className={classes.img} style={{marginRight:'10px', width: '18px'}}/> Discord </Button> </Grid> {/* TVL */} <Grid item xs={12} sm={4}> <Card> <CardContent align="center"> <h2>Total Value Locked</h2> <CountUp style={{ fontSize: '25px' }} end={TVL} separator="," prefix="$" /> </CardContent> </Card> </Grid> {/* Wallet */} <Grid item xs={12} sm={8}> <Card style={{ height: '100%' }}> <CardContent align="center" style={{ marginTop: '2.5%' }}> {/* <h2 style={{ marginBottom: '20px' }}>Wallet Balance</h2> */} {/* <Button color="primary" href="/masonry" variant="contained" style={{ marginRight: '25px' }}> Stake Now </Button> */} {/* <Button href="/cemetery" variant="contained" style={{ marginRight: '25px' }}> Stake Now </Button> */} <Button color="primary" href="/farms" variant="contained" style={{ marginRight: '10px' }}> Farms </Button> <Button color="primary" href="/boardroom" variant="contained" style={{ marginRight: '25px' }}> Stake </Button> <Button target="_blank" href={buyTombAddress} variant="contained" style={{ marginRight: '10px' }} className={classes.button} > Buy CFN </Button> {/* <Button variant="contained" target="_blank" href={buyTShareAddress} className={classes.button}> Buy CSHARE </Button> */} <Button variant="contained" target="_blank" href={buyTShareAddress} style={{ marginRight: '10px' }}> Buy CSHARE </Button> <Button variant="contained" target="_blank" href={`https://dexscreener.com/avalanche/${tomb.address}`} style={{ marginRight: '10px' }}> CFN Chart </Button> <Button variant="contained" target="_blank" href={`https://dexscreener.com/avalanche/${tShare.address}`} style={{ marginRight: '10px' }}> CSHARE Chart </Button> </CardContent> </Card> </Grid> {/* TOMB */} <Grid item xs={12} sm={4}> <Card> <CardContent align="center" style={{ position: 'relative' }}> <h2>CFN</h2> <Button onClick={() => { tombFinance.watchAssetInMetamask('CFN'); }} color="default" variant="outlined" style={{ position: 'absolute', top: '10px', right: '10px' }} > +&nbsp; <img alt="metamask fox" style={{ width: '20px' }} src={MetamaskFox} /> </Button> <Box mt={2}> <CardIcon> <TokenSymbol symbol="TOMB" size={110}/> </CardIcon> </Box> Current Price <Box> <span style={{ fontSize: '30px' }}>{tombPriceInAVAX ? tombPriceInAVAX : '-.----'} AVAX</span> </Box> <Box> <span style={{ fontSize: '18px', alignContent: 'flex-start' }}> ${tombPriceInDollars ? tombPriceInDollars : '-.--'} </span> </Box> <span style={{ fontSize: '14px' }}> Market Cap: ${(tombCirculatingSupply * tombPriceInDollars).toFixed(2)} <br /> Circulating Supply: {tombCirculatingSupply} <br /> Total Supply: {tombTotalSupply} </span> </CardContent> </Card> </Grid> {/* <Grid item xs={12} sm={3}> <Card> <CardContent align="center" style={{ position: 'relative' }}> <h2>CFNp</h2> <Box mt={2}> <CardIcon> <TokenSymbol symbol="TOMB" /> </CardIcon> </Box> Current Price <Box> <span style={{ fontSize: '30px' }}>{tombPriceInAVAX ? tombPriceInAVAX : '-.----'} AVAX</span> </Box> <Box> <span style={{ fontSize: '18px', alignContent: 'flex-start' }}> ${tombPriceInDollars ? tombPriceInDollars : '-.--'} </span> </Box> <span style={{ fontSize: '14px' }}> Market Cap: ${(tombCirculatingSupply * tombPriceInDollars).toFixed(2)} <br /> Circulating Supply: {tombCirculatingSupply} <br /> Total Supply: {tombTotalSupply-140000} </span> </CardContent> </Card> </Grid> */} {/* TSHARE */} <Grid item xs={12} sm={4}> <Card> <CardContent align="center" style={{ position: 'relative' }}> <h2>CSHARE</h2> <Button onClick={() => { tombFinance.watchAssetInMetamask('CSHARE'); }} color="default" variant="outlined" style={{ position: 'absolute', top: '10px', right: '10px' }} > +&nbsp; <img alt="metamask fox" style={{ width: '20px' }} src={MetamaskFox} /> </Button> <Box mt={2}> <CardIcon> <TokenSymbol symbol="TSHARE" size={110}/> </CardIcon> </Box> Current Price <Box> <span style={{ fontSize: '30px' }}>{tSharePriceInAVAX ? tSharePriceInAVAX : '-.----'} AVAX</span> </Box> <Box> <span style={{ fontSize: '18px' }}>${tSharePriceInDollars ? tSharePriceInDollars : '-.--'}</span> </Box> <span style={{ fontSize: '14px' }}> Market Cap: ${(tShareCirculatingSupply * tSharePriceInDollars).toFixed(2)} <br /> Circulating Supply: {tShareCirculatingSupply-balance} <br /> Total Supply: {tShareTotalSupply-balance} </span> </CardContent> </Card> </Grid> {/* TBOND */} <Grid item xs={12} sm={4}> <Card> <CardContent align="center" style={{ position: 'relative' }}> <h2>CBOND</h2> <Button onClick={() => { tombFinance.watchAssetInMetamask('CBOND'); }} color="default" variant="outlined" style={{ position: 'absolute', top: '10px', right: '10px' }} > +&nbsp; <img alt="metamask fox" style={{ width: '20px' }} src={MetamaskFox} /> </Button> <Box mt={2}> <CardIcon> <TokenSymbol symbol="TBOND" size={110}/> </CardIcon> </Box> Current Price <Box> <span style={{ fontSize: '30px' }}>{tBondPriceInAVAX ? tBondPriceInAVAX : '-.----'} AVAX</span> </Box> <Box> <span style={{ fontSize: '18px' }}>${tBondPriceInDollars ? tBondPriceInDollars : '-.--'}</span> </Box> {/* <span style={{ fontSize: '14px' }}> Market Cap: $-.-- <br /> Circulating Supply: ------ <br /> Total Supply: ------ </span> */} <span style={{ fontSize: '12px' }}> Market Cap: ${(tBondCirculatingSupply * tBondPriceInDollars).toFixed(2)} <br /> Circulating Supply: {tBondCirculatingSupply} <br /> Total Supply: {tBondTotalSupply} </span> </CardContent> </Card> </Grid> <Grid item xs={12} sm={6}> <Card> <CardContent align="center"> <h2>CFN-WAVAX Joe LP</h2> <Button onClick={() => { tombFinance.watchAssetInMetamask('CFN-WAVAX'); }} color="default" variant="outlined" style={{ position: 'absolute', top: '10px', right: '10px' }} > +&nbsp; <img alt="metamask fox" style={{ width: '20px' }} src={MetamaskFox} /> </Button> <Box mt={2}> <CardIcon> <TokenSymbol symbol="CFN-AVAX-LP" size={120}/> </CardIcon> </Box> <Box mt={2}> <Button color="primary" disabled={false} onClick={onPresentTombZap} variant="contained"> Zap In! </Button> </Box> <Box mt={2}> <span style={{ fontSize: '26px' }}> {tombLPStats?.tokenAmount ? tombLPStats?.tokenAmount : '-.--'} CFN /{' '} {tombLPStats?.avaxAmount ? tombLPStats?.avaxAmount : '-.--'} AVAX </span> </Box> <Box style={{ fontSize: '18px' }}>${tombLPStats?.priceOfOne ? tombLPStats.priceOfOne : '-.--'}</Box> <span style={{ fontSize: '14px' }}> Liquidity: ${tombLPStats?.totalLiquidity ? tombLPStats.totalLiquidity : '-.--'} <br /> Total supply: {tombLPStats?.totalSupply ? tombLPStats.totalSupply : '-.--'} </span> </CardContent> </Card> </Grid> <Grid item xs={12} sm={6}> <Card> <CardContent align="center"> <h2>CSHARE-WAVAX Joe LP</h2> <Button onClick={() => { tombFinance.watchAssetInMetamask('CSHARE-WAVAX'); }} color="default" variant="outlined" style={{ position: 'absolute', top: '10px', right: '10px' }} > +&nbsp; <img alt="metamask fox" style={{ width: '20px' }} src={MetamaskFox} /> </Button> <Box mt={2}> <CardIcon> <TokenSymbol symbol="CSHARE-AVAX-LP" size={120}/> </CardIcon> </Box> <Box mt={2}> <Button color="primary" onClick={onPresentTshareZap} variant="contained"> Zap In! </Button> </Box> <Box mt={2}> <span style={{ fontSize: '26px' }}> {tshareLPStats?.tokenAmount ? tshareLPStats?.tokenAmount : '-.--'} CSHARE /{' '} {tshareLPStats?.avaxAmount ? tshareLPStats?.avaxAmount : '-.--'} AVAX </span> </Box> <Box style={{ fontSize: '18px' }}>${tshareLPStats?.priceOfOne ? tshareLPStats.priceOfOne : '-.--'}</Box> <span style={{ fontSize: '14px' }}> Liquidity: ${tshareLPStats?.totalLiquidity ? tshareLPStats.totalLiquidity : '-.--'} <br /> Total supply: {tshareLPStats?.totalSupply ? tshareLPStats.totalSupply : '-.--'} </span> </CardContent> </Card> </Grid> </Grid> </Page> ); }; export default Home;
let context = require.context( ".", true, /_(?:test)\.js$/ ); context.keys().forEach( context );
#!/usr/bin/env node var result = [{ "filepath": process.argv[2], "highlights": [ { "startLine": 2, "startCol": 0, "endLine": 2, "endCol": 8, "textType": "keyword" } ], "cpdTokens": [ { "startLine": 2, "startCol": 0, "endLine": 2, "endCol": 3, "image": "foo" }, { "startLine": 2, "startCol": 10, "endLine": 2, "endCol": 13, "image": "bar" } ], "ncloc":[55, 77, 99], "commentLines":[24, 42], "nosonarLines":[24], "executableLines": [5, 7], "statements":100, "functions":10, "classes":1 }]; process.stdin.on('data', function () { // needed for 'end' to be sent }); process.stdin.on('end', function () { process.stdout.write(JSON.stringify(result)); });
const themeName = 'theme_name'; // var gulp = require('gulp'); var plumber = require('gulp-plumber'); /* var rename = require('gulp-rename'); */ var sass = require('gulp-sass'); /* var csslint = require('gulp-csslint'); */ var autoPrefixer = require('gulp-autoprefixer'); //if node version is lower than v.0.1.2 require('es6-promise').polyfill(); /* var cssComb = require('gulp-csscomb'); */ var cmq = require('gulp-merge-media-queries'); /* var cleanCss = require('gulp-clean-css'); var uglify = require('gulp-uglify'); var concat = require('gulp-concat'); */ var merge = require('merge-stream'); //webpack var webpack = require('webpack'); var webpackStream = require('webpack-stream'); var webpackConfig = require('./webpack.config.js'); var sourcemaps = require('gulp-sourcemaps'); const paths = { //input scss: { root:`./wp-content/themes/${themeName}/assets/css/*/*.scss`, main:`./wp-content/themes/${themeName}/assets/css/style.scss`, pages:`./wp-content/themes/${themeName}/assets/css/pages/*.scss`, }, //output css:{ main:`./wp-content/themes/${themeName}/assets/css`, pages:`./wp-content/themes/${themeName}/assets/css/pages` }, js:{ rootDir:`./wp-content/themes/${themeName}/assets/js`, index:`./wp-content/themes/${themeName}/assets/js/index.js`, } } gulp.task('sass',function(done){ // main.scss var main = gulp.src([paths.scss.main]) .pipe(sourcemaps.init()) .pipe(plumber({ handleError: function (err) { console.log(err); this.emit('end'); } })) .pipe(sass()) .pipe(autoPrefixer()) //.pipe(cssComb()) .pipe(cmq({log:true})) //.pipe(csslint()) //.pipe(csslint.formatter()) .pipe(sourcemaps.write("./")) .pipe(gulp.dest(paths.css.main)) /* .pipe(rename({ suffix: '.min' })) */ //minify //.pipe(cleanCss()) //.pipe(gulp.dest(`wp-content/themes/${themeName}/assets/css/*.min.css`)) //pages scss compile var pages = gulp.src([paths.scss.pages]) .pipe(sourcemaps.init()) .pipe(plumber({ handleError: function (err) { console.log(err); this.emit('end'); } })) .pipe(sass()) .pipe(autoPrefixer()) //.pipe(cssComb()) .pipe(cmq({log:true})) //.pipe(csslint()) //.pipe(csslint.formatter()) .pipe(sourcemaps.write("./")) .pipe(gulp.dest(paths.css.pages)) /* .pipe(rename({ suffix: '.min' })) */ //minify //.pipe(cleanCss()) //.pipe(gulp.dest(`wp-content/themes/${themeName}/assets/css/*.min.css`)) merge(main, pages); done(); }); gulp.task("webpack", function(done){ webpackStream(webpackConfig, webpack) .pipe(gulp.dest( paths.js.rootDir )); done(); }); /* gulp.task('js',function(){ gulp.src([`wp-content/themes/${themeName}/assets/js/*.js`]) .pipe(plumber({ handleError: function (err) { console.log(err); this.emit('end'); } })) .pipe(concat('main.js')) .pipe(gulp.dest(`wp-content/themes/${themeName}/assets/js`)) .pipe(rename({ suffix: '.min' })) .pipe(uglify()) .pipe(gulp.dest(`wp-content/themes/${themeName}/assets/js`)) }); */ //gulp.task('html',function(){ // gulp.src(['html/**/*.html']) // .pipe(plumber({ // handleError: function (err) { // console.log(err); // this.emit('end'); // } // })) // .pipe(gulp.dest('./')) //}); gulp.task('watch:sass',function(done){ //gulp.watch(`wp-content//themes/${themeName}/assets/js/*/*.js`,['js']); gulp.watch(`wp-content/themes/${themeName}/assets/css/*.scss`, gulp.task('sass')); gulp.watch(`wp-content/themes/${themeName}/assets/css/*/*.scss`, gulp.task('sass')); //gulp.watch('html/**/*.html',['html']); done(); }); gulp.task('watch:webpack', function(done){ gulp.watch(`wp-content/themes/${themeName}/assets/js/*.js`, gulp.task('webpack')); gulp.watch(`wp-content/themes/${themeName}/assets/js/*/*.js`, gulp.task('webpack')); //gulp.watch('html/**/*.html',['html']); done(); }) gulp.task('watch',function(done){ //gulp.watch(`wp-content/themes/${themeName}/assets/js/*/*.js`,['js']); gulp.watch(`wp-content/themes/${themeName}/assets/css/*.scss`, gulp.task('sass')); gulp.watch(`wp-content/themes/${themeName}/assets/css/*/*.scss`, gulp.task('sass')); gulp.watch(`wp-content/themes/${themeName}/assets/js/*.js`, gulp.task('webpack')); gulp.watch(`wp-content/themes/${themeName}/assets/js/*/*.js`, gulp.task('webpack')); done(); })
import Vue from '../../utils/vue'; import { mergeData } from 'vue-functional-data-merge'; export var props = { id: { type: String // default: null }, inline: { type: Boolean, default: false }, novalidate: { type: Boolean, default: false }, validated: { type: Boolean, default: false } }; // @vue/component export var BForm = /*#__PURE__*/Vue.extend({ name: 'BForm', functional: true, props: props, render: function render(h, _ref) { var props = _ref.props, data = _ref.data, children = _ref.children; return h('form', mergeData(data, { class: { 'form-inline': props.inline, 'was-validated': props.validated }, attrs: { id: props.id, novalidate: props.novalidate } }), children); } });
$(document).ready(function(){ setNavbar(); setTimeline(); $('#nav-button').on('click touchstart', function () { if($('.navbar-collapse').hasClass('in')){ $('#span-top').css('animation', 'rotate2 0.2s ease-in forwards'); $('#span-bottom').css('animation', 'rotateBack2 0.2s ease-in forwards'); $('#span-top').removeClass('span-top-rotated'); $('#span-bottom').removeClass('span-bottom-rotated'); } else { $('#span-top').addClass('span-top-rotated'); $('#span-bottom').addClass('span-bottom-rotated'); $('#span-top').css('animation', 'rotate 0.2s ease-in forwards'); $('#span-bottom').css('animation', 'rotateBack 0.2s ease-in forwards'); } }); $(window).resize(function(){ setNavbar(); setTimeline(); }); window.addEventListener( "scroll", function( event ) { setNavbar(); }); /*$(window).scroll(function(){ setNavbar(); });*/ $('a[href*=#]').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var $target = $(this.hash); $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']'); if ($target.length) { var targetOffset = $target.offset().top; $('html,body') .animate({scrollTop: targetOffset}, 1000); return false; } } }); function setNavbar(){ var distanceBar = $('#navbar').offset().top; var distanceQual = $('#qualifications').offset().top; var distanceSkills = $('#skills').offset().top; var distancePort = $('#portfolio').offset().top; var distanceContact = $('#contact').offset().top; var windowScroll = $(window).scrollTop(); if(windowScroll+50 > distanceContact){ $('.navbar-pos').addClass('.nav-fixed'); $('.navbar-pos').css('top', '0'); $('#home-div').removeClass('bg-image'); $('#contactlink').addClass('link-active'); $('#homelink').removeClass('link-active'); $('#aboutlink').removeClass('link-active'); $('#quallink').removeClass('link-active'); $('#skilllink').removeClass('link-active'); $('#portlink').removeClass('link-active'); } else if (windowScroll+50> distancePort){ $('.navbar-pos').css('position', 'fixed'); $('.navbar-pos').css('top', '0'); $('#home-div').removeClass('bg-image'); $('#portlink').addClass('link-active'); $('#homelink').removeClass('link-active'); $('#aboutlink').removeClass('link-active'); $('#quallink').removeClass('link-active'); $('#skilllink').removeClass('link-active'); $('#contactlink').removeClass('link-active'); } else if (windowScroll+50 > distanceSkills){ $('.navbar-pos').css('position', 'fixed'); $('.navbar-pos').css('top', '0'); $('#home-div').removeClass('bg-image'); $('#skilllink').addClass('link-active'); $('#homelink').removeClass('link-active'); $('#aboutlink').removeClass('link-active'); $('#quallink').removeClass('link-active'); $('#portlink').removeClass('link-active'); $('#contactlink').removeClass('link-active'); addCircles(); } else if (windowScroll+50 > distanceQual){ $('.navbar-pos').css('position', 'fixed'); $('.navbar-pos').css('top', '0'); $('#home-div').removeClass('bg-image'); $('#quallink').addClass('link-active'); $('#homelink').removeClass('link-active'); $('#aboutlink').removeClass('link-active'); $('#portlink').removeClass('link-active'); $('#skilllink').removeClass('link-active'); $('#contactlink').removeClass('link-active'); } else if (windowScroll > distanceBar){ $('.navbar-pos').css('position', 'fixed'); $('.navbar-pos').css('top', '0'); $('#home-div').removeClass('bg-image'); $('#aboutlink').addClass('link-active'); $('#homelink').removeClass('link-active'); $('#quallink').removeClass('link-active'); $('#skilllink').removeClass('link-active'); $('#portlink').removeClass('link-active'); $('#contactlink').removeClass('link-active'); } else { $('.navbar-pos').css('position', 'absolute'); $('.navbar-pos').css('top', ''); $('#home-div').addClass('bg-image'); $('#homelink').addClass('link-active'); $('#aboutlink').removeClass('link-active'); $('#quallink').removeClass('link-active'); $('#skilllink').removeClass('link-active'); $('#portlink').removeClass('link-active'); $('#contactlink').removeClass('link-active'); } }; function addCircles(){ $('.20per .spinner').css('animation', 'rota20 2s linear forwards'); $('.20per .filler').css('animation', 'fill20 2s steps(1, end) forwards'); $('.20per .mask').css('animation', 'mask20 2s steps(1, end) forwards'); $('.40per .spinner').css('animation', 'rota40 2s linear forwards'); $('.40per .filler').css('animation', 'fill40 2s steps(1, end) forwards'); $('.40per .mask').css('animation', 'mask40 2s steps(1, end) forwards'); $('.60per .spinner').css('animation', 'rota60 2s linear forwards'); $('.60per .filler').css('animation', 'fill60 2s steps(1, end) forwards'); $('.60per .mask').css('animation', 'mask60 2s steps(1, end) forwards'); $('.80per .spinner').css('animation', 'rota80 2s linear forwards'); $('.80per .filler').css('animation', 'fill80 2s steps(1, end) forwards'); $('.80per .mask').css('animation', 'mask80 2s steps(1, end) forwards'); $('.100per .spinner').css('animation', 'rota100 2s linear forwards'); $('.100per .filler').css('animation', 'fill100 2s steps(1, end) forwards'); $('.100per .mask').css('animation', 'mask100 2s steps(1, end) forwards'); }; function removeCircles(){ $('.20per .spinner').css('animation', ''); $('.20per .filler').css('animation', ''); $('.20per .mask').css('animation', ''); $('.40per .spinner').css('animation', ''); $('.40per .filler').css('animation', ''); $('.40per .mask').css('animation', ''); $('.60per .spinner').css('animation', ''); $('.60per .filler').css('animation', ''); $('.60per .mask').css('animation', ''); $('.80per .spinner').css('animation', ''); $('.80per .filler').css('animation', ''); $('.80per .mask').css('animation', ''); $('.100per .spinner').css('animation', ''); $('.100per .filler').css('animation', ''); $('.100per .mask').css('animation', ''); }; function setTimeline(){ //document.getElementById('timeline-original').disabled = true; //document.getElementById('timeline-modified').disabled = false; $('#timeline-airbus').addClass('timeline-inverted'); $('#timeline-astrium').addClass('timeline-inverted'); $('#timeline-exchange').addClass('timeline-inverted'); var windowWidth = $('.timeline').width(); if (windowWidth > 1400){ $('.timeline-panel').css('width', 94+"%"); } else if (windowWidth > 1000) { $('.timeline-panel').css('width', 92+"%"); } else if (windowWidth > 800) { $('.timeline-panel').css('width', 92+"%"); } else if (windowWidth > 600) { $('.timeline-panel').css('width', 88+"%"); } else if (windowWidth > 400) { $('.timeline-panel').css('width', 84+"%"); } else if (windowWidth > 350) { $('.timeline-panel').css('width', 80+"%"); } else if (windowWidth > 300){ $('.timeline-panel').css('width', 76+"%"); } else { $('.timeline-panel').css('width', 74+"%"); } }; });
export default async function fetchLocations({ url, parser }) { const response = await fetch(url); const data = await response.json(); return parser(data); }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var html_1 = require("@connectv/html"); var transport_1 = require("@connectv/sdh/transport"); var jss_theme_1 = require("@connectv/jss-theme"); var renderer; function getRenderer() { if (!renderer) { if (!window.theme) { throw new Error('Theme not specified!'); } renderer = new html_1.Renderer().plug(jss_theme_1.theme(window.theme)); } return renderer; } exports.getRenderer = getRenderer; exports.getRenderer$ = transport_1.funcTransport(getRenderer); //# sourceMappingURL=renderer.js.map
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import createVue from '@/createVue' import Cookies from 'js-cookie' // Check if token exist here const token = Cookies.get('api_token') let vue if (!token) { if (process.env.NODE_ENV !== 'production') { Cookies.set('api_token', prompt(), {expires: 1 / (24)}) window.location.href = '' } else { Cookies.set('api_token', prompt(), {expires: 1 / (24)}) window.location.href = '' // Replace else section with this if it is not deploy through heroku // window.location.href = '/login' } } else { vue = createVue() } export default vue
import React, { Component } from 'react'; class GetInvolved extends Component { render() { return ( <section className="GetInvolved section" id="get-involved"> <div className="container"> <h3 className="title has-text-centered">Get Involved</h3> <div className="buttons"> <a href="https://startupdetroit.herokuapp.com/" className="button is-link" target="_blank" rel="noopener noreferrer" > Join our Slack community </a> <a href="https://docs.google.com/forms/d/e/1FAIpQLScoj2AXf9EuPJitkVV1Ju7G8NNWAIbPx-3rMBxCX-Q1LJcYdQ/viewform" className="button is-link" target="_blank" rel="noopener noreferrer" > Join our email list </a> <a href="https://www.startupdigest.com/digests/detroit/" className="button is-link" target="_blank" rel="noopener noreferrer" > Startup Digest Calendar </a> </div> </div> </section> ); } } export default GetInvolved;
/*jshint expr: true*/ describe('NodeProximityHandler', function() { var body = document.body, container; beforeEach(function() { container = document.createElement('div'); body.appendChild(container); }); afterEach(function() { body.removeChild(container); }); describe('addHandler', function() { var loader, nodeProximityHandler; beforeEach(function() { loader = { load: sinon.spy() }; nodeProximityHandler = new NodeProximityHandler(loader); container.style.height = '1000px'; container.style.width = '1000px'; container.innerHTML = '<div id="theDiv" style="position: absolute; top: 200px; left: 200px; width: 100px; height: 100px"></div>'; }); it('should create a tripwire around a node', function() { nodeProximityHandler.addTrigger({ el: container.querySelector('#theDiv'), src: 'some/src', distance: '100' }); var tripwire = container.querySelector('.nmouse-tripwire'), rect = tripwire.getBoundingClientRect(); expect(tripwire).to.exist; expect(rect.top).to.equal(100); expect(rect.bottom).to.equal(400); expect(rect.left).to.equal(100); expect(rect.right).to.equal(400); }); it('should call the loader when mousing over the tripwire', function() { nodeProximityHandler.addTrigger({ el: container.querySelector('#theDiv'), src: 'some/src', distance: '100' }); var tripwire = container.querySelector('.nmouse-tripwire'); tripwire.dispatchEvent(new CustomEvent('mouseover', {})); expect(loader.load) .to.have.been.calledOnce .to.have.been.calledWith('some/src'); }); it('should remove the tripwire after triggering', function() { nodeProximityHandler.addTrigger({ el: container.querySelector('#theDiv'), src: 'some/src', distance: '100' }); var tripwire = container.querySelector('.nmouse-tripwire'); tripwire.dispatchEvent(new CustomEvent('mouseover', {})); tripwire = container.querySelector('.nmouse-tripwire'); expect(tripwire).to.not.exist; }); }); });
'use strict'; /* eslint-disable class-methods-use-this */ const sockjs = require('sockjs'); const BaseServer = require('./BaseServer'); // Workaround for sockjs@~0.3.19 // sockjs will remove Origin header, however Origin header is required for checking host. // See https://github.com/webpack/webpack-dev-server/issues/1604 for more information { const SockjsSession = require('sockjs/lib/transport').Session; const decorateConnection = SockjsSession.prototype.decorateConnection; // eslint-disable-next-line func-names SockjsSession.prototype.decorateConnection = function (req) { decorateConnection.call(this, req); const connection = this.connection; if ( connection.headers && !('origin' in connection.headers) && 'origin' in req.headers ) { connection.headers.origin = req.headers.origin; } }; } module.exports = class SockJSServer extends BaseServer { // options has: error (function), debug (function), server (http/s server), path (string) constructor(server) { super(server); this.socket = sockjs.createServer({ // Use provided up-to-date sockjs-client sockjs_url: '/__webpack_dev_server__/sockjs.bundle.js', // Default logger is very annoy. Limit useless logs. log: (severity, line) => { if (severity === 'error') { this.server.logger.error(line); } else if (severity === 'info') { this.server.logger.log(line); } else { this.server.logger.debug(line); } }, }); this.socket.installHandlers(this.server.server, { prefix: this.server.options.client.path, }); } send(connection, message) { // prevent cases where the server is trying to send data while connection is closing if (connection.readyState !== 1) { return; } connection.write(message); } close(connection) { connection.close(); } // f should be passed the resulting connection and the connection headers onConnection(f) { this.socket.on('connection', (connection) => { f(connection, connection ? connection.headers : null); }); } onConnectionClose(connection, f) { connection.on('close', f); } };
const {tokenizeIter, tokenizeBufferIter, tokenize, tokenizeBuffer} = require('./tokenize') // const {parse, parseTokens, parseBuffer, parseFile} = require('./parse') const {parse, parseTokens, parseBuffer} = require('./parse') const {stringify} = require('./stringify') const helper = require('./helper') Object.assign(exports, { tokenizeIter, tokenizeBufferIter, tokenize, tokenizeBuffer, parse, parseTokens, parseBuffer, // parseFile, stringify }, helper)
let UserOrders = (function () { let ui = {}; let table; function bindUi() { this._ui = { dataTable: $('#userOrdersDataTable'), }; return _ui; } function bindEvents() { ui.dataTable.on('click', 'tbody tr', edit); } function onLoad() { initializeDatatable(); } function initializeDatatable(){ table = ui.dataTable.DataTable( { "ajax": window.url, "columns": [ { "data": "order_id" }, { "data": "ordered_list" }, { "data": "order_contact" }, { "data": "full_address" }, { "data": "order_date" } ], 'order' : [[4, 'desc']] } ); } function edit(){ let data = table.row(this).data(); window.location.href = `${baseURL}res/order/invoice/${data.id}`; } function init() { ui = bindUi(); bindEvents(); onLoad(); } return { init: init, _ui: ui, }; })(); $(document).ready(function () { UserOrders.init(); });
import React from "react"; import styled from "styled-components"; import theme from "../../styles/theme"; const { fontSizes } = theme; const SuggestionWrapper = styled.form` display: grid; align-items: center; justify-items: center; grid-template-rows: 1fr; grid-row-gap: 10px; margin: 10px 0; @media screen and (min-width: 768px) { .submit { font-size: ${fontSizes.bodyMedium}; } } @media screen and (min-width: 1024px) { grid-template-columns: 2fr 1fr; grid-column-gap: 10px; } `; const Suggestion = () => { return ( <SuggestionWrapper name="book-suggestion" method="post" data-netlify="true" data-netlify-honeypot="bot-field" > <input type="hidden" name="bot-field" /> <input type="hidden" name="form-name" value="book-suggestion" /> <input type="text" name="book" placeholder="Suggest a book..."></input> <button type="submit" className="submit"> Submit </button> </SuggestionWrapper> ); }; export default Suggestion;
import React from 'react' import { MemoryRouter } from 'react-router-dom' import { shallow } from 'enzyme' import Breadcrumb from './Breadcrumb' describe('Breadcrumb', () => { it('renders correctly the component', () => { const wrapper = shallow( <MemoryRouter initialEntries={['/']} initialIndex={0}> <Breadcrumb /> </MemoryRouter>, ) expect(wrapper.html()).toMatchSnapshot() }) })
var class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic = [ [ "$actualWork", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#abbc1a7281e2381786ae5ece50e0ee3ad", null ], [ "$cost", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#a663dee21a373f0f68e99db5403724e9e", null ], [ "$costBase", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#aa0ec3fc849f8eea87dcddf1beb0b220e", null ], [ "$endDate", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#a398d961fce9d555095d8e8251c060465", null ], [ "$estimatedWork", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#a5ad2ab3b3db4c5691a6fa01fe559a1ed", null ], [ "$estimatedWorkBaseline", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#af634ff04aa49992ef0341a36800bbfd0", null ], [ "$grossProfit", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#ae4f99f33e2a4f5f19412602b0925adc7", null ], [ "$grossProfitBase", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#a018e257c63f9be1e4d4d5a69ac542330", null ], [ "$internalId", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#a5c30554bb7bd3dbca941628ca393757d", null ], [ "$price", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#a264091074b1a8f4ed0abefd278831f6f", null ], [ "$priceBase", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#a16283267a6df7d1fe482c1acb599ada0", null ], [ "$resource", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#abd4c7b8b084214b8d2533ba07fce6b83", null ], [ "$resourceName", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#adc0aed0ec6bf7959e25cdf7dae66b419", null ], [ "$serviceItem", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#ac581421fa8bda6926afb86a1ce8a4355", null ], [ "$serviceItemDesc", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#a5d0d37fe59fe0b2c56da1dbcd93d7296", null ], [ "$startDate", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#a288a4b22573d5731fe3f52c55263c5f3", null ], [ "$unitCost", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#acd0972b9043c6756bd94572ee70f016d", null ], [ "$unitCostBase", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#acf2b1fe0bd2c1472e4ea6ea64522d02a", null ], [ "$unitPrice", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#a3556a0f24bc1be9c7d5503cf1f1e3e89", null ], [ "$unitPriceBase", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#ab026e2d70fb034544e91fa2e08523737", null ], [ "$units", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#abab3f33128592840c23918fe3999185a", null ], [ "$workCalendar", "class_net_suite_1_1_classes_1_1_project_task_assignment_search_row_basic.html#a21d54f964dad5a3c0c9d136cd5b2bf30", null ] ];
module.exports = { semi: false, singleQuote: true, printWidth: 100, tabWidth: 2, useTabs: false, trailingComma: 'none', bracketSpacing: true }
var nanoModal; (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var ModalEvent = require("./ModalEvent"); function El(tag, classNames) { var doc = document; var el = (tag.nodeType || tag === window) ? tag : doc.createElement(tag); var eventHandlers = []; if (classNames) { el.className = classNames; } var onShowEvent = ModalEvent(); var onHideEvent = ModalEvent(); var addListener = function(event, handler) { if (el.addEventListener) { el.addEventListener(event, handler, false); } else { el.attachEvent("on" + event, handler); } eventHandlers.push({ event: event, handler: handler }); }; var removeListener = function(event, handler) { if (el.removeEventListener) { el.removeEventListener(event, handler); } else { el.detachEvent("on" + event, handler); } var t = eventHandlers.length; var handlerObj; while (t-- > 0) { handlerObj = eventHandlers[t]; if (handlerObj.event === event && handlerObj.handler === handler) { eventHandlers.splice(t, 1); break; } } }; var addClickListener = function(handler) { var throttle = false; var throttleHandler = function(e) { if (!throttle) { throttle = true; setTimeout(function() { throttle = false; }, 100); handler(e); } }; addListener("touchstart", throttleHandler); addListener("mousedown", throttleHandler); }; var show = function(arg) { if (el) { el.style.display = "block"; onShowEvent.fire(arg); } }; var hide = function(arg) { if (el) { el.style.display = "none"; onHideEvent.fire(arg); } }; var isShowing = function() { return el.style && el.style.display === "block"; }; var html = function(html) { if (el) { el.innerHTML = html; } }; var text = function(text) { if (el) { html(""); el.appendChild(doc.createTextNode(text)); } }; var remove = function() { if (el.parentNode) { var x = eventHandlers.length; var eventHandler; while (x-- > 0) { eventHandler = eventHandlers[x]; removeListener(eventHandler.event, eventHandler.handler); } el.parentNode.removeChild(el); onShowEvent.removeAllListeners(); onHideEvent.removeAllListeners(); } }; var add = function(elObject) { var elementToAppend = elObject.el || elObject; el.appendChild(elementToAppend); }; return { el: el, addListener: addListener, addClickListener: addClickListener, onShowEvent: onShowEvent, onHideEvent: onHideEvent, show: show, hide: hide, isShowing: isShowing, html: html, text: text, remove: remove, add: add }; } module.exports = El; },{"./ModalEvent":3}],2:[function(require,module,exports){ var El = require("./El"); function Modal(content, options, overlay, customShow, customHide) { if (content === undefined) { return; } options = options || {}; var modal = El("div", "nanoModal nanoModalOverride " + (options.classes || "")); var contentContainer = El("div", "nanoModalContent"); var buttonArea = El("div", "nanoModalButtons"); var onRequestHideListenerId; modal.add(contentContainer); modal.add(buttonArea); modal.el.style.display = "none"; var buttons = []; var pub; options.buttons = options.buttons || [{ text: "Close", handler: "hide", primary: true }]; var removeButtons = function() { var t = buttons.length; while (t-- > 0) { var button = buttons[t]; button.remove(); } buttons = []; }; var center = function() { modal.el.style.marginLeft = -modal.el.clientWidth / 2 + "px"; }; var anyModalsOpen = function() { var modals = document.querySelectorAll(".nanoModal"); var t = modals.length; while (t-- > 0) { if (modals[t].style.display !== "none") { return true; } } return false; }; var defaultShow = function() { if (!modal.isShowing()) { // Call the static method from the Modal module. Modal.resizeOverlay(); overlay.show(overlay); modal.show(pub); center(); } }; var defaultHide = function() { if (modal.isShowing()) { modal.hide(pub); if (!anyModalsOpen()) { overlay.hide(overlay); } if (options.autoRemove) { pub.remove(); } } }; var quickClone = function(obj) { var newObj = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { newObj[key] = obj[key]; } } return newObj; }; pub = { modal: modal, overlay: overlay, show: function() { if (customShow) { customShow(defaultShow, pub); } else { defaultShow(); } return pub; }, hide: function() { if (customHide) { customHide(defaultHide, pub); } else { defaultHide(); } return pub; }, onShow: function(callback) { modal.onShowEvent.addListener(function() { callback(pub); }); return pub; }, onHide: function(callback) { modal.onHideEvent.addListener(function() { callback(pub); }); return pub; }, remove: function() { overlay.onRequestHide.removeListener(onRequestHideListenerId); onRequestHideListenerId = null; removeButtons(); modal.remove(); }, setButtons: function(buttonList) { var btnIdx = buttonList.length; var btnObj; var btnEl; var classes; var giveButtonCustomClickListener = function(btnEl, btnObj) { var pubCopy = quickClone(pub); btnEl.addClickListener(function(e) { pubCopy.event = e || window.event; btnObj.handler(pubCopy); }); }; removeButtons(); if (btnIdx === 0) { buttonArea.hide(); } else { buttonArea.show(); while (btnIdx-- > 0) { btnObj = buttonList[btnIdx]; classes = "nanoModalBtn"; if (btnObj.primary) { classes += " nanoModalBtnPrimary"; } classes += btnObj.classes ? " " + btnObj.classes : ""; btnEl = El("button", classes); if (btnObj.handler === "hide") { btnEl.addClickListener(pub.hide); } else if (btnObj.handler) { giveButtonCustomClickListener(btnEl, btnObj); } btnEl.text(btnObj.text); buttonArea.add(btnEl); buttons.push(btnEl); } } center(); return pub; }, setContent: function(newContent) { // Only good way of checking if a node in IE8... if (newContent.nodeType) { contentContainer.html(""); contentContainer.add(newContent); } else { contentContainer.html(newContent); } center(); content = newContent; return pub; }, getContent: function() { return content; } }; onRequestHideListenerId = overlay.onRequestHide.addListener(function() { if (options.overlayClose !== false && modal.isShowing()) { pub.hide(); } }); pub.setContent(content).setButtons(options.buttons); document.body.appendChild(modal.el); return pub; } var doc = document; var getDocumentDim = function(name) { var docE = doc.documentElement; var scroll = "scroll" + name; var offset = "offset" + name; return Math.max(doc.body[scroll], docE[scroll], doc.body[offset], docE[offset], docE["client" + name]); }; // Make this a static function so that main.js has access to it so it can // add a window keydown event listener. Modal.js also needs this function. Modal.resizeOverlay = function() { var overlay = doc.getElementById("nanoModalOverlay"); overlay.style.width = getDocumentDim("Width") + "px"; overlay.style.height = getDocumentDim("Height") + "px"; }; module.exports = Modal; },{"./El":1}],3:[function(require,module,exports){ function ModalEvent() { var listeners = {}; var nextListenerId = 0; var addListener = function(callback) { listeners[nextListenerId] = callback; return nextListenerId++; }; var removeListener = function(id) { if (id) { delete listeners[id]; } }; var removeAllListeners = function() { listeners = {}; }; var fire = function() { for (var x = 0, num = nextListenerId; x < num; ++x) { if (listeners[x]) { listeners[x].apply(null, arguments); } } }; return { addListener: addListener, removeListener: removeListener, removeAllListeners: removeAllListeners, fire: fire }; } module.exports = ModalEvent; },{}],4:[function(require,module,exports){ var ModalEvent = require("./ModalEvent"); var nanoModalAPI = (function() { var El = require("./El"); var Modal = require("./Modal"); var overlay; var doc = document; function init() { if (!doc.querySelector("#nanoModalOverlay")) { // Put the main styles on the page. var styleObj = El("style"); var style = styleObj.el; var firstElInHead = doc.querySelectorAll("head")[0].childNodes[0]; firstElInHead.parentNode.insertBefore(style, firstElInHead); var styleText = ".nanoModal{position:absolute;top:100px;left:50%;display:none;z-index:9999;min-width:300px;padding:15px 20px 10px;-webkit-border-radius:10px;-moz-border-radius:10px;border-radius:10px;background:#fff;background:-moz-linear-gradient(top,#fff 0,#ddd 100%);background:-webkit-gradient(linear,left top,left bottom,color-stop(0%,#fff),color-stop(100%,#ddd));background:-webkit-linear-gradient(top,#fff 0,#ddd 100%);background:-o-linear-gradient(top,#fff 0,#ddd 100%);background:-ms-linear-gradient(top,#fff 0,#ddd 100%);background:linear-gradient(to bottom,#fff 0,#ddd 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#dddddd', GradientType=0)}.nanoModalOverlay{position:absolute;top:0;left:0;width:100%;height:100%;z-index:9998;background:#000;display:none;-ms-filter:\"alpha(Opacity=50)\";-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}.nanoModalButtons{border-top:1px solid #ddd;margin-top:15px;text-align:right}.nanoModalBtn{color:#333;background-color:#fff;display:inline-block;padding:6px 12px;margin:8px 4px 0;font-size:14px;text-align:center;white-space:nowrap;vertical-align:middle;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;border:1px solid transparent;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.nanoModalBtn:active,.nanoModalBtn:focus,.nanoModalBtn:hover{color:#333;background-color:#e6e6e6;border-color:#adadad}.nanoModalBtn.nanoModalBtnPrimary{color:#fff;background-color:#428bca;border-color:#357ebd}.nanoModalBtn.nanoModalBtnPrimary:active,.nanoModalBtn.nanoModalBtnPrimary:focus,.nanoModalBtn.nanoModalBtnPrimary:hover{color:#fff;background-color:#3071a9;border-color:#285e8e}"; if (style.styleSheet) { style.styleSheet.cssText = styleText; } else { styleObj.text(styleText); } // Make the overlay and put it on the page. overlay = El("div", "nanoModalOverlay nanoModalOverride"); overlay.el.id = "nanoModalOverlay"; doc.body.appendChild(overlay.el); // Add an event so that the modals can hook into it to close. overlay.onRequestHide = ModalEvent(); var overlayCloseFunc = function() { overlay.onRequestHide.fire(); }; overlay.addClickListener(overlayCloseFunc); El(doc).addListener("keydown", function(e) { var keyCode = e.which || e.keyCode; if (keyCode === 27) { // 27 is Escape overlayCloseFunc(); } }); var windowEl = El(window); var resizeOverlayTimeout; windowEl.addListener("resize", function() { if (resizeOverlayTimeout) { clearTimeout(resizeOverlayTimeout); } resizeOverlayTimeout = setTimeout(Modal.resizeOverlay, 100); }); // Make SURE we have the correct dimensions so we make the overlay the right size. // Some devices fire the event before the document is ready to return the new dimensions. windowEl.addListener("orientationchange", function() { for (var t = 0; t < 3; ++t) { setTimeout(Modal.resizeOverlay, 1000 * t + 200); } }); } } if (document.body) { init(); } var api = function(content, options) { init(); return Modal(content, options, overlay, api.customShow, api.customHide); }; api.resizeOverlay = Modal.resizeOverlay; return api; })(); // expose api to var outside browserify so that we can export a module correctly. nanoModal = nanoModalAPI; },{"./El":1,"./Modal":2,"./ModalEvent":3}]},{},[1,2,3,4]); if (typeof window !== "undefined") { if (typeof window.define === "function" && window.define.amd) { window.define(function() { return nanoModal; }); } window.nanoModal = nanoModal; } if (typeof module !== "undefined") { module.exports = nanoModal; }
/* * GET home page. */ var data = require("../suggestions.json"); exports.view = function(req, res){ res.render('newchat', data); };
module.exports={viewBox:'0 0 448 512',d:'M188.8 512c45.616 0 83.2-37.765 83.2-83.2v-35.647a93.148 93.148 0 0 0 22.064-7.929c22.006 2.507 44.978-3.503 62.791-15.985C409.342 368.1 448 331.841 448 269.299V248c0-60.063-40-98.512-40-127.2v-2.679c4.952-5.747 8-13.536 8-22.12V32c0-17.673-12.894-32-28.8-32H156.8C140.894 0 128 14.327 128 32v64c0 8.584 3.048 16.373 8 22.12v2.679c0 6.964-6.193 14.862-23.668 30.183l-.148.129-.146.131c-9.937 8.856-20.841 18.116-33.253 25.851C48.537 195.798 0 207.486 0 252.8c0 56.928 35.286 92 83.2 92 8.026 0 15.489-.814 22.4-2.176V428.8c0 45.099 38.101 83.2 83.2 83.2zm0-48c-18.7 0-35.2-16.775-35.2-35.2V270.4c-17.325 0-35.2 26.4-70.4 26.4-26.4 0-35.2-20.625-35.2-44 0-8.794 32.712-20.445 56.1-34.926 14.575-9.074 27.225-19.524 39.875-30.799 18.374-16.109 36.633-33.836 39.596-59.075h176.752C364.087 170.79 400 202.509 400 248v21.299c0 40.524-22.197 57.124-61.325 50.601-8.001 14.612-33.979 24.151-53.625 12.925-18.225 19.365-46.381 17.787-61.05 4.95V428.8c0 18.975-16.225 35.2-35.2 35.2zM328 64c0-13.255 10.745-24 24-24s24 10.745 24 24-10.745 24-24 24-24-10.745-24-24z'}
import moment from 'moment'; const DateFormatter = { format(date) { return moment(date).format('YYYY-MM-DD'); }, }; export default DateFormatter;
import React from "react" import ReactDOM from "react-dom" import { Router, Route, Switch } from "react-router-dom" import { Provider } from "react-redux" import store from "./store" import history from "./history" import Dashboard from "./components/Dashboard" import Login from "./components/Login" import Logout from "./components/Logout" import { PrivateRoute } from "./components/PrivateRoute" import "bootstrap/dist/css/bootstrap.min.css" import "./index.css" ReactDOM.render( <Provider store={store}> <Router history={history}> <Switch> <PrivateRoute exact path="/" component={Dashboard} /> <Route path="/login" component={Login} /> {/* <Route path="/logout" component={Logout} /> */} </Switch> </Router> </Provider>, document.getElementById("root") )
/** * @flow */ import * as React from 'react'; import {Button, PlatformColor} from 'react-native'; export default (props: React.ElementProps<typeof Button>): React.Node => ( <Button color={PlatformColor('SystemAccentColor')} {...props} /> );
(window.webpackJsonp=window.webpackJsonp||[]).push([[81],{1592:function(e,t,a){"use strict";a.r(t);var n=a(25),l=a.n(n),r=a(24),o=a.n(r),i=a(26),s=a.n(i),c=a(27),u=a.n(c),m=a(28),d=a.n(m),p=a(0),f=a.n(p),h=a(33),v=function(e){return{type:"FETCH_EMAIL_TEMPLATE",id:e}},b=a(21),E=a.n(b),g=a(6),y=a.n(g),N=a(4),w=a(685),T=a(98),C=Object(h.b)(null,(function(e){return{deleteEmailTemplate:function(t){e(function(e){return{type:"DELETE_EMAIL_TEMPLATE",id:e}}(t))}}}))((function(e){return f.a.createElement(T.a,{buttonConfirmText:"Verwijder",buttonClassName:"btn-danger",closeModal:e.closeDeleteItemModal,confirmAction:function(){return e.deleteEmailTemplate(e.templateId),void e.closeDeleteItemModal()},title:"Verwijderen"},"Verwijder e-mail template: ",f.a.createElement("strong",null," ",e.templateName," "))})),k=function(e){function t(e){var a;return l()(this,t),a=s()(this,u()(t).call(this,e)),y()(E()(a),"toggleDelete",(function(){a.setState({showDelete:!a.state.showDelete})})),a.state={showDelete:!1},a}return d()(t,e),o()(t,[{key:"render",value:function(){return f.a.createElement("div",{className:"row"},f.a.createElement("div",{className:"col-md-4"},f.a.createElement("div",{className:"btn-group",role:"group"},f.a.createElement(w.a,{iconName:"glyphicon-arrow-left",onClickAction:N.e.goBack}),f.a.createElement(w.a,{iconName:"glyphicon-trash",onClickAction:this.toggleDelete}))),f.a.createElement("div",{className:"col-md-4"},f.a.createElement("h4",{className:"text-center"},"E-mail template: "+this.props.templateName)),f.a.createElement("div",{className:"col-md-4"}),this.state.showDelete&&f.a.createElement(C,{closeDeleteItemModal:this.toggleDelete,templateName:this.props.templateName,templateId:this.props.templateId}))}}]),t}(p.Component),O=Object(h.b)((function(e){return{templateName:e.emailTemplate.name,templateId:e.emailTemplate.id}}),null)(k),j=a(198),D=a(682),_=a(683),M=a(684),P=a(696),x=a(733),S=a(689),A=a.n(S),I=a(101);function L(e,t){var a=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),a.push.apply(a,n)}return a}function q(e){for(var t=1;t<arguments.length;t++){var a=null!=arguments[t]?arguments[t]:{};t%2?L(Object(a),!0).forEach((function(t){y()(e,t,a[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(a)):L(Object(a)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(a,t))}))}return e}var R=function(e){function t(e){var a;l()(this,t),a=s()(this,u()(t).call(this,e)),y()(E()(a),"handleInputChange",(function(e){var t=e.target,n="checkbox"===t.type?t.checked:t.value,l=t.name;a.setState(q({},a.state,{emailTemplate:q({},a.state.emailTemplate,y()({},l,n))}))})),y()(E()(a),"handleSubmit",(function(e){e.preventDefault();var t=a.state.emailTemplate,n={},l=!1;A.a.isEmpty(t.name)&&(n.name=!0,l=!0),a.setState(q({},a.state,{errors:n})),!l&&I.a.updateEmailTemplate(t).then((function(e){a.props.fetchEmailTemplate(e.id),a.props.switchToView()}))}));var n=e.emailTemplate,r=n.id,o=n.name,i=n.subject,c=n.htmlBody;return a.state={emailTemplate:{id:r,name:o,subject:i||"",htmlBody:c||""},errors:{name:!1}},a.handleTextChange=a.handleTextChange.bind(E()(a)),a}return d()(t,e),o()(t,[{key:"handleTextChange",value:function(e){this.setState(q({},this.state,{emailTemplate:q({},this.state.emailTemplate,{htmlBody:e.target.getContent({format:"raw"})})}))}},{key:"render",value:function(){var e=this.state.emailTemplate,t=e.name,a=e.subject,n=e.htmlBody,l=this.props.emailTemplate.createdBy;return f.a.createElement("div",null,f.a.createElement("div",{className:"row"},f.a.createElement("div",{className:"form-group col-sm-12"},f.a.createElement("div",{className:"row"},f.a.createElement("div",{className:"col-sm-3"},f.a.createElement("label",{className:"col-sm-12 required"},"Naam")),f.a.createElement("div",{className:"col-sm-9"},f.a.createElement("input",{type:"text",className:"form-control input-sm "+(this.state.errors.name?"has-error":""),name:"name",value:t,onChange:this.handleInputChange}))))),f.a.createElement("div",{className:"row"},f.a.createElement("div",{className:"form-group col-sm-12"},f.a.createElement("div",{className:"row"},f.a.createElement("div",{className:"col-sm-3"},f.a.createElement("label",{className:"col-sm-12"},"Standaard onderwerp")),f.a.createElement("div",{className:"col-sm-9"},f.a.createElement("input",{type:"text",className:"form-control input-sm",name:"subject",value:a,onChange:this.handleInputChange}))))),f.a.createElement("div",{className:"row"},f.a.createElement("div",{className:"form-group col-sm-12"},f.a.createElement("div",{className:"row"},f.a.createElement(x.a,{label:"Tekst",value:n,onChangeAction:this.handleTextChange})))),f.a.createElement("div",{className:"row margin-10-top",onClick:this.props.switchToEdit},f.a.createElement("div",{className:"col-sm-12"},f.a.createElement("div",{className:"row"},f.a.createElement("div",{className:"col-sm-3"},f.a.createElement("label",{className:"col-sm-12"},"Gemaakt door")),f.a.createElement("div",{className:"col-sm-9"},f.a.createElement(N.b,{to:l?"gebruiker/"+l.id:"",className:"link-underline"},l?l.fullName:""))))),f.a.createElement(P.a,null,f.a.createElement("div",{className:"pull-right btn-group",role:"group"},f.a.createElement(M.a,{buttonClassName:"btn-default",buttonText:"Annuleren",onClickAction:this.props.switchToView}),f.a.createElement(M.a,{buttonText:"Opslaan",onClickAction:this.handleSubmit,type:"submit",value:"Submit"}))))}}]),t}(p.Component),V=Object(h.b)((function(e){return{emailTemplate:e.emailTemplate}}),(function(e){return{fetchEmailTemplate:function(t){e(v(t))}}}))(R),B=a(8),F=a.n(B),U=a(728);F.a.locale("nl");var G=Object(h.b)((function(e){return{emailTemplate:e.emailTemplate}}))((function(e){var t=e.emailTemplate,a=t.name,n=t.subject,l=t.htmlBody,r=t.createdBy;return f.a.createElement("div",null,f.a.createElement("div",{className:"row margin-10-top",onClick:e.switchToEdit},f.a.createElement("div",{className:"col-sm-12"},f.a.createElement("div",{className:"row"},f.a.createElement("div",{className:"col-sm-3"},f.a.createElement("label",{className:"col-sm-12"},"Naam")),f.a.createElement("div",{className:"col-sm-9"},a)))),f.a.createElement("div",{className:"row margin-10-top",onClick:e.switchToEdit},f.a.createElement("div",{className:"col-sm-12"},f.a.createElement("div",{className:"row"},f.a.createElement("div",{className:"col-sm-3"},f.a.createElement("label",{className:"col-sm-12"},"Standaard onderwerp")),f.a.createElement("div",{className:"col-sm-9"},n)))),f.a.createElement("div",{className:"row",onClick:e.switchToEdit},f.a.createElement(U.a,{label:"Tekst",value:l,switchToEdit:e.switchToEdit})),f.a.createElement("div",{className:"row margin-10-top",onClick:e.switchToEdit},f.a.createElement("div",{className:"col-sm-12"},f.a.createElement("div",{className:"row"},f.a.createElement("div",{className:"col-sm-3"},f.a.createElement("label",{className:"col-sm-12"},"Gemaakt door")),f.a.createElement("div",{className:"col-sm-9"},f.a.createElement(N.b,{to:r?"gebruiker/"+r.id:"",className:"link-underline"},r?r.fullName:""))))))})),H=function(e){function t(e){var a;return l()(this,t),a=s()(this,u()(t).call(this,e)),y()(E()(a),"switchToEdit",(function(){a.setState({showEdit:!0})})),y()(E()(a),"switchToView",(function(){a.setState({showEdit:!1,activeDiv:""})})),a.state={showEdit:!1,activeDiv:""},a}return d()(t,e),o()(t,[{key:"onDivEnter",value:function(){this.setState({activeDiv:"panel-grey"})}},{key:"onDivLeave",value:function(){this.state.showEdit||this.setState({activeDiv:""})}},{key:"render",value:function(){var e=this;return f.a.createElement(D.a,{className:this.state.activeDiv,onMouseEnter:function(){return e.onDivEnter()},onMouseLeave:function(){return e.onDivLeave()}},f.a.createElement(_.a,null,this.state.showEdit?f.a.createElement(V,{switchToView:this.switchToView}):f.a.createElement(G,{switchToEdit:this.switchToEdit})))}}]),t}(p.Component),J=Object(h.b)((function(e){return{emailTemplate:e.emailTemplate}}))(H),W=function(e){function t(e){return l()(this,t),s()(this,u()(t).call(this,e))}return d()(t,e),o()(t,[{key:"render",value:function(){var e="",t=!0;return this.props.hasError?e="Fout bij het ophalen van e-mailtemplate.":this.props.isLoading?e="Gegevens aan het laden.":Object(j.isEmpty)(this.props.emailTemplate)?e="Geen e-mailtemplate gevonden!":t=!1,t?f.a.createElement("div",null,e):f.a.createElement("div",null,f.a.createElement(J,null))}}]),t}(p.Component),z=Object(h.b)((function(e){return{emailTemplate:e.emailTemplate,isLoading:e.loadingData.isLoading,hasError:e.loadingData.hasError}}),(function(e){return{fetchEmailTemplate:function(t){e(v(t))}}}))(W),Y=function(e){function t(e){return l()(this,t),s()(this,u()(t).call(this,e))}return d()(t,e),o()(t,[{key:"componentDidMount",value:function(){this.props.fetchEmailTemplate(this.props.params.id)}},{key:"render",value:function(){return f.a.createElement("div",{className:"row"},f.a.createElement("div",{className:"col-md-9"},f.a.createElement("div",{className:"col-md-12 margin-10-top"},f.a.createElement(D.a,null,f.a.createElement(_.a,{className:"panel-small"},f.a.createElement(O,null)))),f.a.createElement("div",{className:"col-md-12 margin-10-top"},f.a.createElement(z,null))),f.a.createElement("div",{className:"col-md-3"}))}}]),t}(p.Component);t.default=Object(h.b)((function(e){return{emailTemplateDetails:e.emailTemplateDetails}}),(function(e){return{fetchEmailTemplate:function(t){e(v(t))}}}))(Y)},682:function(e,t,a){"use strict";var n=a(0),l=a.n(n),r=a(14),o=a.n(r),i=function(e){var t=e.children,a=e.className,n=e.onMouseEnter,r=e.onMouseLeave;return l.a.createElement("div",{className:"panel panel-default ".concat(a),onMouseEnter:n,onMouseLeave:r},t)};i.defaultProps={className:"",onMouseEnter:function(){},onMouseLeave:function(){}},i.propTypes={className:o.a.string,onMouseEnter:o.a.func,onMouseLeave:o.a.func},t.a=i},683:function(e,t,a){"use strict";var n=a(0),l=a.n(n),r=a(14),o=a.n(r),i=function(e){var t=e.className,a=e.children;return l.a.createElement("div",{className:"panel-body ".concat(t)},a)};i.defaultProps={className:""},i.propTypes={className:o.a.string},t.a=i},684:function(e,t,a){"use strict";var n=a(0),l=a.n(n),r=a(14),o=a.n(r),i=function(e){var t=e.buttonClassName,a=e.buttonText,n=e.onClickAction,r=e.type,o=e.value,i=e.loading,s=e.loadText,c=e.disabled;return i?l.a.createElement("button",{type:r,className:"btn btn-sm btn-loading ".concat(t),value:o,disabled:i},l.a.createElement("span",{className:"glyphicon glyphicon-refresh glyphicon-refresh-animate"})," ",s):l.a.createElement("button",{type:r,className:"btn btn-sm ".concat(t),onClick:n,value:o,disabled:c},a)};i.defaultProps={buttonClassName:"btn-success",type:"button",value:"",loading:!1,loadText:"Aan het laden",disabled:!1},i.propTypes={buttonClassName:o.a.string,buttonText:o.a.string.isRequired,onClickAction:o.a.func,type:o.a.string,value:o.a.string,loading:o.a.bool,loadText:o.a.string,disabled:o.a.bool},t.a=i},685:function(e,t,a){"use strict";var n=a(0),l=a.n(n),r=a(14),o=a.n(r),i=function(e){var t=e.buttonClassName,a=e.iconName,n=e.onClickAction,r=e.title,o=e.disabled;return l.a.createElement("button",{type:"button",className:"btn ".concat(t),onClick:n,disabled:o,title:r},l.a.createElement("span",{className:"glyphicon ".concat(a)}))};i.defaultProps={buttonClassName:"btn-success btn-sm",title:"",disabled:!1},i.propTypes={buttonClassName:o.a.string,iconName:o.a.string.isRequired,onClickAction:o.a.func,title:o.a.string,disabled:o.a.bool},t.a=i},696:function(e,t,a){"use strict";var n=a(0),l=a.n(n),r=a(14),o=a.n(r),i=function(e){var t=e.className,a=e.children;return l.a.createElement("div",{className:"panel-footer ".concat(t)},a)};i.defaultProps={className:""},i.propTypes={className:o.a.string},t.a=i},728:function(e,t,a){"use strict";var n=a(0),l=a.n(n),r=a(737),o=a.n(r),i=a(14),s=a.n(i),c=a(682),u=a(684),m=function(e){var t=e.label,a=e.className,n=e.id,r=e.value,i=e.switchToEdit;return l.a.createElement("div",{className:a},l.a.createElement("label",{htmlFor:n,className:"col-sm-3"},t,i?l.a.createElement("span",null,l.a.createElement("br",null),l.a.createElement(u.a,{buttonClassName:"btn-success btn-padding-small",buttonText:"Wijzig",onClickAction:i})):""),l.a.createElement(c.a,{className:"col-sm-9"},l.a.createElement(o.a,null,l.a.createElement("div",{id:n,dangerouslySetInnerHTML:{__html:r}}))))};m.defaultProps={className:"col-sm-12",value:""},m.propTypes={label:s.a.string.isRequired,className:s.a.string,id:s.a.string,value:s.a.oneOfType([s.a.string,s.a.number])},t.a=m},733:function(e,t,a){"use strict";var n=a(0),l=a.n(n),r=a(14),o=a.n(r),i=(a(753),a(754),a(755),a(756),a(757),a(758),a(759),a(760),a(761),a(762),a(763),a(768)),s=function(e){var t=e.label,a=e.value,n=e.onChangeAction;return l.a.createElement("div",null,l.a.createElement("div",{className:"col-sm-3"},l.a.createElement("label",{htmlFor:"quotationText",className:"col-sm-12"},t)),l.a.createElement("div",{className:"col-sm-9"},l.a.createElement(i.a,{initialValue:a,init:{branding:!1,language:"nl",menubar:!1,plugins:"paste lists advlist link image code table textcolor pagebreak",toolbar:"undo redo | formatselect fontselect | bold italic forecolor | alignleft aligncenter alignright | pagebreak | bullist numlist outdent indent | table | link image | code",height:"300",browser_spellcheck:!0,font_formats:"Courier New=courier new;Tahoma=tahoma;Times New Roman=times new roman;Verdana=verdana;"},onChange:n})))};s.defaultProps={value:"",errorMessage:""},s.propTypes={label:o.a.string.isRequired,type:o.a.string,id:o.a.string,placeholder:o.a.string,value:o.a.string,onChangeAction:o.a.func},t.a=s},737:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n,l=a(738),r=(n=l)&&n.__esModule?n:{default:n};t.default=r.default},738:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var n in a)Object.prototype.hasOwnProperty.call(a,n)&&(e[n]=a[n])}return e},l=function(){function e(e,t){for(var a=0;a<t.length;a++){var n=t[a];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,a,n){return a&&e(t.prototype,a),n&&e(t,n),t}}(),r=a(0),o=u(r),i=u(a(79)),s=u(a(14)),c=u(a(739));function u(e){return e&&e.__esModule?e:{default:e}}var m,d="undefined"!=typeof window&&window.console,p=function(){},f=p,h=p;d&&(m=console.error,f=function(){console.error=function(e){/<head>/.test(e)||m.call(console,e)}},h=function(){return console.error=m});var v=function(e){function t(e,a){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var n=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,a));return n._isMounted=!1,n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),l(t,[{key:"componentDidMount",value:function(){this._isMounted=!0,this.renderFrameContents()}},{key:"componentDidUpdate",value:function(){this.renderFrameContents()}},{key:"componentWillUnmount",value:function(){this._isMounted=!1;var e=this.getDoc(),t=this.getMountTarget();e&&t&&i.default.unmountComponentAtNode(t)}},{key:"getDoc",value:function(){return i.default.findDOMNode(this).contentDocument}},{key:"getMountTarget",value:function(){var e=this.getDoc();return this.props.mountTarget?e.querySelector(this.props.mountTarget):e.body.children[0]}},{key:"renderFrameContents",value:function(){if(this._isMounted){var e=this.getDoc();if(e&&"complete"===e.readyState){null===e.querySelector("div")&&(this._setInitialContent=!1);var t=e.defaultView||e.parentView,a=!this._setInitialContent,n=o.default.createElement(c.default,{document:e,window:t},o.default.createElement("div",{className:"frame-content"},this.props.head,this.props.children));a&&(e.open("text/html","replace"),e.write(this.props.initialContent),e.close(),this._setInitialContent=!0),f();var l=a?this.props.contentDidMount:this.props.contentDidUpdate,r=this.getMountTarget();i.default.unstable_renderSubtreeIntoContainer(this,n,r,l),h()}else setTimeout(this.renderFrameContents.bind(this),0)}}},{key:"render",value:function(){var e=n({},this.props,{children:void 0});return delete e.head,delete e.initialContent,delete e.mountTarget,delete e.contentDidMount,delete e.contentDidUpdate,o.default.createElement("iframe",e)}}]),t}(r.Component);v.propTypes={style:s.default.object,head:s.default.node,initialContent:s.default.string,mountTarget:s.default.string,contentDidMount:s.default.func,contentDidUpdate:s.default.func,children:s.default.oneOfType([s.default.element,s.default.arrayOf(s.default.element)])},v.defaultProps={style:{},head:null,children:void 0,mountTarget:void 0,contentDidMount:function(){},contentDidUpdate:function(){},initialContent:'<!DOCTYPE html><html><head></head><body><div class="frame-root"></div></body></html>'},t.default=v},739:function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e,t){for(var a=0;a<t.length;a++){var n=t[a];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,a,n){return a&&e(t.prototype,a),n&&e(t,n),t}}(),l=a(0),r=(o(l),o(a(14)));function o(e){return e&&e.__esModule?e:{default:e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}var c=function(e){function t(){return i(this,t),s(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),n(t,[{key:"getChildContext",value:function(){return{document:this.props.document,window:this.props.window}}},{key:"render",value:function(){return l.Children.only(this.props.children)}}]),t}(l.Component);c.propTypes={document:r.default.object.isRequired,window:r.default.object.isRequired,children:r.default.element.isRequired},c.childContextTypes={document:r.default.object.isRequired,window:r.default.object.isRequired},t.default=c}}]);
/* Common functions */ var jFormErrorHandler = function(response) { unblockUI(); jAlert(response.status + ": " + response.statusText); } var angularErrorHandler = function(response) { // TODO : better error handling unblockUI(); motechAlert("error"); } var alertHandler = function(msg, title) { return function() { unblockUI(); motechAlert(msg, title); } } var alertHandlerWithCallback = function(msg, callback) { return function() { unblockUI(); motechAlert(msg, "", callback); } } var dummyHandler = function() {} function motechAlert(msg) { jAlert(jQuery.i18n.prop(msg), ""); } function motechAlert(msg, title) { jAlert(jQuery.i18n.prop(msg), jQuery.i18n.prop(title)); } function motechAlert(msg, title, callback) { jAlert(jQuery.i18n.prop(msg), jQuery.i18n.prop(title), callback); } /* Define "finished typing" as 5 second puase */ var typingTimer; var doneTypingInterval = 5 * 1000; function captureTyping(callback) { clearTimeout(typingTimer); typingTimer = setTimeout(callback, doneTypingInterval); } function blockUI() { $.blockUI({message : '<h1><img src="img/bigloader.gif" alt="loading" /></h1>'}); } function unblockUI() { $.unblockUI(); }
(window.webpackJsonp=window.webpackJsonp||[]).push([[4],{"+ZDr":function(e,t,n){"use strict";var r=n("5NKs");t.__esModule=!0,t.withPrefix=h,t.withAssetPrefix=function(e){return h(e,"")},t.navigateTo=t.replace=t.push=t.navigate=t.default=void 0;var o=r(n("uDP2")),a=r(n("j8BX")),i=r(n("v06X")),u=r(n("XEEL")),c=r(n("17x9")),s=r(n("q1tI")),l=n("YwZP"),p=n("LYrO"),f=n("cu4x");t.parsePath=f.parsePath;var d=function(e){return null==e?void 0:e.startsWith("/")};function h(e,t){var n,r;if(void 0===t&&(t=""),!v(e))return e;if(e.startsWith("./")||e.startsWith("../"))return e;var o=null!==(n=null!==(r=t)&&void 0!==r?r:"")&&void 0!==n?n:"/";return""+((null==o?void 0:o.endsWith("/"))?o.slice(0,-1):o)+(e.startsWith("/")?e:"/"+e)}var v=function(e){return e&&!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("//")};var m=function(e,t){return v(e)?d(e)?h(e):function(e,t){return d(e)?e:(0,p.resolve)(e,t)}(e,t):e},g={activeClassName:c.default.string,activeStyle:c.default.object,partiallyActive:c.default.bool},w=function(e){function t(t){var n;(n=e.call(this,t)||this).defaultGetProps=function(e){var t=e.isPartiallyCurrent,r=e.isCurrent;return(n.props.partiallyActive?t:r)?{className:[n.props.className,n.props.activeClassName].filter(Boolean).join(" "),style:(0,a.default)({},n.props.style,n.props.activeStyle)}:null};var r=!1;return"undefined"!=typeof window&&window.IntersectionObserver&&(r=!0),n.state={IOSupported:r},n.handleRef=n.handleRef.bind((0,i.default)(n)),n}(0,u.default)(t,e);var n=t.prototype;return n.componentDidUpdate=function(e,t){this.props.to===e.to||this.state.IOSupported||___loader.enqueue((0,f.parsePath)(m(this.props.to,window.location.pathname)).pathname)},n.componentDidMount=function(){this.state.IOSupported||___loader.enqueue((0,f.parsePath)(m(this.props.to,window.location.pathname)).pathname)},n.componentWillUnmount=function(){if(this.io){var e=this.io,t=e.instance,n=e.el;t.unobserve(n),t.disconnect()}},n.handleRef=function(e){var t,n,r,o=this;this.props.innerRef&&this.props.innerRef.hasOwnProperty("current")?this.props.innerRef.current=e:this.props.innerRef&&this.props.innerRef(e),this.state.IOSupported&&e&&(this.io=(t=e,n=function(){___loader.enqueue((0,f.parsePath)(m(o.props.to,window.location.pathname)).pathname)},(r=new window.IntersectionObserver((function(e){e.forEach((function(e){t===e.target&&(e.isIntersecting||e.intersectionRatio>0)&&(r.unobserve(t),r.disconnect(),n())}))}))).observe(t),{instance:r,el:t}))},n.render=function(){var e=this,t=this.props,n=t.to,r=t.getProps,i=void 0===r?this.defaultGetProps:r,u=t.onClick,c=t.onMouseEnter,p=(t.activeClassName,t.activeStyle,t.innerRef,t.partiallyActive,t.state),d=t.replace,h=(0,o.default)(t,["to","getProps","onClick","onMouseEnter","activeClassName","activeStyle","innerRef","partiallyActive","state","replace"]);return s.default.createElement(l.Location,null,(function(t){var r=t.location,o=m(n,r.pathname);return v(o)?s.default.createElement(l.Link,(0,a.default)({to:o,state:p,getProps:i,innerRef:e.handleRef,onMouseEnter:function(e){c&&c(e),___loader.hovering((0,f.parsePath)(o).pathname)},onClick:function(t){if(u&&u(t),!(0!==t.button||e.props.target||t.defaultPrevented||t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)){t.preventDefault();var n=d,r=encodeURI(o)===window.location.pathname;"boolean"!=typeof d&&r&&(n=!0),window.___navigate(o,{state:p,replace:n})}return!0}},h)):s.default.createElement("a",(0,a.default)({href:o},h))}))},t}(s.default.Component);w.propTypes=(0,a.default)({},g,{onClick:c.default.func,to:c.default.string.isRequired,replace:c.default.bool,state:c.default.object});var y=function(e,t,n){return console.warn('The "'+e+'" method is now deprecated and will be removed in Gatsby v'+n+'. Please use "'+t+'" instead.')},b=s.default.forwardRef((function(e,t){return s.default.createElement(w,(0,a.default)({innerRef:t},e))}));t.default=b;t.navigate=function(e,t){window.___navigate(m(e,window.location.pathname),t)};var P=function(e){y("push","navigate",3),window.___push(m(e,window.location.pathname))};t.push=P;t.replace=function(e){y("replace","navigate",3),window.___replace(m(e,window.location.pathname))};t.navigateTo=function(e){return y("navigateTo","navigate",3),P(e)}},"+pfR":function(e,t,n){},"/hTd":function(e,t,n){"use strict";t.__esModule=!0,t.SessionStorage=void 0;var r=function(){function e(){}var t=e.prototype;return t.read=function(e,t){var n=this.getStateKey(e,t);try{var r=window.sessionStorage.getItem(n);return r?JSON.parse(r):0}catch(o){return window&&window.___GATSBY_REACT_ROUTER_SCROLL&&window.___GATSBY_REACT_ROUTER_SCROLL[n]?window.___GATSBY_REACT_ROUTER_SCROLL[n]:0}},t.save=function(e,t,n){var r=this.getStateKey(e,t),o=JSON.stringify(n);try{window.sessionStorage.setItem(r,o)}catch(a){window&&window.___GATSBY_REACT_ROUTER_SCROLL||(window.___GATSBY_REACT_ROUTER_SCROLL={}),window.___GATSBY_REACT_ROUTER_SCROLL[r]=JSON.parse(o)}},t.getStateKey=function(e,t){var n="@@scroll|"+(e.key||e.pathname);return null==t?n:n+"|"+t},e}();t.SessionStorage=r},"3uz+":function(e,t,n){"use strict";t.__esModule=!0,t.useScrollRestoration=function(e){var t=(0,a.useLocation)(),n=(0,o.useContext)(r.ScrollContext),i=(0,o.useRef)();return(0,o.useLayoutEffect)((function(){if(i.current){var r=n.read(t,e);i.current.scrollTo(0,r||0)}}),[]),{ref:i,onScroll:function(){i.current&&n.save(t,e,i.current.scrollTop)}}};var r=n("Enzk"),o=n("q1tI"),a=n("YwZP")},"5NKs":function(e,t){e.exports=function(e){return e&&e.__esModule?e:{default:e}}},"5yr3":function(e,t,n){"use strict";var r=function(e){return e=e||Object.create(null),{on:function(t,n){(e[t]||(e[t]=[])).push(n)},off:function(t,n){e[t]&&e[t].splice(e[t].indexOf(n)>>>0,1)},emit:function(t,n){(e[t]||[]).slice().map((function(e){e(n)})),(e["*"]||[]).slice().map((function(e){e(t,n)}))}}}();t.a=r},"6qGY":function(e,t){e.exports=Object.assign},"7hJ6":function(e,t,n){"use strict";t.__esModule=!0,t.useScrollRestoration=t.ScrollContainer=t.ScrollContext=void 0;var r=n("Enzk");t.ScrollContext=r.ScrollHandler;var o=n("hd9s");t.ScrollContainer=o.ScrollContainer;var a=n("3uz+");t.useScrollRestoration=a.useScrollRestoration},"94VI":function(e,t){t.polyfill=function(e){return e}},"9Hrx":function(e,t,n){"use strict";function r(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}n.d(t,"a",(function(){return r}))},"9Xx/":function(e,t,n){"use strict";n.d(t,"c",(function(){return c})),n.d(t,"d",(function(){return s})),n.d(t,"a",(function(){return a})),n.d(t,"b",(function(){return i}));var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o=function(e){var t=e.location,n=t.search,r=t.hash,o=t.href,a=t.origin,i=t.protocol,c=t.host,s=t.hostname,l=t.port,p=e.location.pathname;!p&&o&&u&&(p=new URL(o).pathname);return{pathname:encodeURI(decodeURI(p)),search:n,hash:r,href:o,origin:a,protocol:i,host:c,hostname:s,port:l,state:e.history.state,key:e.history.state&&e.history.state.key||"initial"}},a=function(e,t){var n=[],a=o(e),i=!1,u=function(){};return{get location(){return a},get transitioning(){return i},_onTransitionComplete:function(){i=!1,u()},listen:function(t){n.push(t);var r=function(){a=o(e),t({location:a,action:"POP"})};return e.addEventListener("popstate",r),function(){e.removeEventListener("popstate",r),n=n.filter((function(e){return e!==t}))}},navigate:function(t){var c=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=c.state,l=c.replace,p=void 0!==l&&l;if("number"==typeof t)e.history.go(t);else{s=r({},s,{key:Date.now()+""});try{i||p?e.history.replaceState(s,null,t):e.history.pushState(s,null,t)}catch(d){e.location[p?"replace":"assign"](t)}}a=o(e),i=!0;var f=new Promise((function(e){return u=e}));return n.forEach((function(e){return e({location:a,action:"PUSH"})})),f}}},i=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/",t=e.indexOf("?"),n={pathname:t>-1?e.substr(0,t):e,search:t>-1?e.substr(t):""},r=0,o=[n],a=[null];return{get location(){return o[r]},addEventListener:function(e,t){},removeEventListener:function(e,t){},history:{get entries(){return o},get index(){return r},get state(){return a[r]},pushState:function(e,t,n){var i=n.split("?"),u=i[0],c=i[1],s=void 0===c?"":c;r++,o.push({pathname:u,search:s.length?"?"+s:s}),a.push(e)},replaceState:function(e,t,n){var i=n.split("?"),u=i[0],c=i[1],s=void 0===c?"":c;o[r]={pathname:u,search:s},a[r]=e},go:function(e){var t=r+e;t<0||t>a.length-1||(r=t)}}}},u=!("undefined"==typeof window||!window.document||!window.document.createElement),c=a(u?window:i()),s=c.navigate},BOnt:function(e,t,n){"use strict";var r=n("5NKs"),o=n("Wbzz"),a=r(n("hqbx"));t.onClientEntry=function(e,t){void 0===t&&(t={}),(0,a.default)(window,t,(function(e){(0,o.navigate)(e)}))}},Enzk:function(e,t,n){"use strict";var r=n("jGDn"),o=n("5NKs");t.__esModule=!0,t.ScrollHandler=t.ScrollContext=void 0;var a=o(n("v06X")),i=o(n("XEEL")),u=r(n("q1tI")),c=o(n("17x9")),s=n("/hTd"),l=u.createContext(new s.SessionStorage);t.ScrollContext=l,l.displayName="GatsbyScrollContext";var p=function(e){function t(){for(var t,n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];return(t=e.call.apply(e,[this].concat(r))||this)._stateStorage=new s.SessionStorage,t.scrollListener=function(){var e=t.props.location.key;e&&t._stateStorage.save(t.props.location,e,window.scrollY)},t.windowScroll=function(e,n){t.shouldUpdateScroll(n,t.props)&&window.scrollTo(0,e)},t.scrollToHash=function(e,n){var r=document.getElementById(e.substring(1));r&&t.shouldUpdateScroll(n,t.props)&&r.scrollIntoView()},t.shouldUpdateScroll=function(e,n){var r=t.props.shouldUpdateScroll;return!r||r.call((0,a.default)(t),e,n)},t}(0,i.default)(t,e);var n=t.prototype;return n.componentDidMount=function(){var e;window.addEventListener("scroll",this.scrollListener);var t=this.props.location,n=t.key,r=t.hash;n&&(e=this._stateStorage.read(this.props.location,n)),e?this.windowScroll(e,void 0):r&&this.scrollToHash(decodeURI(r),void 0)},n.componentWillUnmount=function(){window.removeEventListener("scroll",this.scrollListener)},n.componentDidUpdate=function(e){var t,n=this.props.location,r=n.hash,o=n.key;o&&(t=this._stateStorage.read(this.props.location,o)),r&&0===t?this.scrollToHash(decodeURI(r),e):this.windowScroll(t,e)},n.render=function(){return u.createElement(l.Provider,{value:this._stateStorage},this.props.children)},t}(u.Component);t.ScrollHandler=p,p.propTypes={shouldUpdateScroll:c.default.func,children:c.default.element.isRequired,location:c.default.object.isRequired}},GddB:function(e,t,n){"use strict";n.r(t);n("tb+u"),n("GevN");n("+pfR")},GevN:function(e,t,n){},IOVJ:function(e,t,n){"use strict";var r=n("9Hrx"),o=n("q1tI"),a=n.n(o),i=n("emEt"),u=n("xtsi"),c=function(e){function t(){return e.apply(this,arguments)||this}return Object(r.a)(t,e),t.prototype.render=function(){var e=Object.assign({},this.props,{pathContext:this.props.pageContext}),t=Object(u.apiRunner)("replaceComponentRenderer",{props:this.props,loader:i.publicLoader})[0]||Object(o.createElement)(this.props.pageResources.component,Object.assign({},e,{key:this.props.path||this.props.pageResources.page.path}));return Object(u.apiRunner)("wrapPageElement",{element:t,props:e},t,(function(t){return{element:t.result,props:e}})).pop()},t}(a.a.Component);t.a=c},LYrO:function(e,t,n){"use strict";n.r(t),n.d(t,"startsWith",(function(){return a})),n.d(t,"pick",(function(){return i})),n.d(t,"match",(function(){return u})),n.d(t,"resolve",(function(){return c})),n.d(t,"insertParams",(function(){return s})),n.d(t,"validateRedirect",(function(){return l})),n.d(t,"shallowCompare",(function(){return y}));var r=n("QLaP"),o=n.n(r),a=function(e,t){return e.substr(0,t.length)===t},i=function(e,t){for(var n=void 0,r=void 0,a=t.split("?")[0],i=m(a),u=""===i[0],c=v(e),s=0,l=c.length;s<l;s++){var f=!1,h=c[s].route;if(h.default)r={route:h,params:{},uri:t};else{for(var g=m(h.path),y={},b=Math.max(i.length,g.length),P=0;P<b;P++){var R=g[P],S=i[P];if(d(R)){y[R.slice(1)||"*"]=i.slice(P).map(decodeURIComponent).join("/");break}if(void 0===S){f=!0;break}var E=p.exec(R);if(E&&!u){-1===w.indexOf(E[1])||o()(!1);var O=decodeURIComponent(S);y[E[1]]=O}else if(R!==S){f=!0;break}}if(!f){n={route:h,params:y,uri:"/"+i.slice(0,P).join("/")};break}}}return n||r||null},u=function(e,t){return i([{path:e}],t)},c=function(e,t){if(a(e,"/"))return e;var n=e.split("?"),r=n[0],o=n[1],i=t.split("?")[0],u=m(r),c=m(i);if(""===u[0])return g(i,o);if(!a(u[0],".")){var s=c.concat(u).join("/");return g(("/"===i?"":"/")+s,o)}for(var l=c.concat(u),p=[],f=0,d=l.length;f<d;f++){var h=l[f];".."===h?p.pop():"."!==h&&p.push(h)}return g("/"+p.join("/"),o)},s=function(e,t){var n=e.split("?"),r=n[0],o=n[1],a=void 0===o?"":o,i="/"+m(r).map((function(e){var n=p.exec(e);return n?t[n[1]]:e})).join("/"),u=t.location,c=(u=void 0===u?{}:u).search,s=(void 0===c?"":c).split("?")[1]||"";return i=g(i,a,s)},l=function(e,t){var n=function(e){return f(e)};return m(e).filter(n).sort().join("/")===m(t).filter(n).sort().join("/")},p=/^:(.+)/,f=function(e){return p.test(e)},d=function(e){return e&&"*"===e[0]},h=function(e,t){return{route:e,score:e.default?0:m(e.path).reduce((function(e,t){return e+=4,!function(e){return""===e}(t)?f(t)?e+=2:d(t)?e-=5:e+=3:e+=1,e}),0),index:t}},v=function(e){return e.map(h).sort((function(e,t){return e.score<t.score?1:e.score>t.score?-1:e.index-t.index}))},m=function(e){return e.replace(/(^\/+|\/+$)/g,"").split("/")},g=function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return e+((n=n.filter((function(e){return e&&e.length>0})))&&n.length>0?"?"+n.join("&"):"")},w=["uri","path"],y=function(e,t){var n=Object.keys(e);return n.length===Object.keys(t).length&&n.every((function(n){return t.hasOwnProperty(n)&&e[n]===t[n]}))}},LeKB:function(e,t,n){e.exports=[{plugin:n("q9nr"),options:{plugins:[],maxWidth:590}},{plugin:n("BOnt"),options:{plugins:[]}},{plugin:n("pWkz"),options:{plugins:[],trackingId:"UA-147358815-1"}},{plugin:n("e/UW"),options:{plugins:[]}},{plugin:n("GddB"),options:{plugins:[]}}]},MMVs:function(e,t,n){e.exports=function(){var e=!1;-1!==navigator.appVersion.indexOf("MSIE 10")&&(e=!0);var t,n=[],r="object"==typeof document&&document,o=e?r.documentElement.doScroll("left"):r.documentElement.doScroll,a=r&&(o?/^loaded|^c/:/^loaded|^i|^c/).test(r.readyState);return!a&&r&&r.addEventListener("DOMContentLoaded",t=function(){for(r.removeEventListener("DOMContentLoaded",t),a=1;t=n.shift();)t()}),function(e){a?setTimeout(e,0):n.push(e)}}()},NSX3:function(e,t,n){"use strict";n.r(t);var r=n("xtsi");"https:"!==window.location.protocol&&"localhost"!==window.location.hostname?console.error("Service workers can only be used over HTTPS, or on localhost for development"):"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then((function(e){e.addEventListener("updatefound",(function(){Object(r.apiRunner)("onServiceWorkerUpdateFound",{serviceWorker:e});var t=e.installing;console.log("installingWorker",t),t.addEventListener("statechange",(function(){switch(t.state){case"installed":navigator.serviceWorker.controller?(window.___swUpdated=!0,Object(r.apiRunner)("onServiceWorkerUpdateReady",{serviceWorker:e}),window.___failedResources&&(console.log("resources failed, SW updated - reloading"),window.location.reload())):(console.log("Content is now available offline!"),Object(r.apiRunner)("onServiceWorkerInstalled",{serviceWorker:e}));break;case"redundant":console.error("The installing service worker became redundant."),Object(r.apiRunner)("onServiceWorkerRedundant",{serviceWorker:e});break;case"activated":Object(r.apiRunner)("onServiceWorkerActive",{serviceWorker:e})}}))}))})).catch((function(e){console.error("Error during service worker registration:",e)}))},QLaP:function(e,t,n){"use strict";e.exports=function(e,t,n,r,o,a,i,u){if(!e){var c;if(void 0===t)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var s=[n,r,o,a,i,u],l=0;(c=new Error(t.replace(/%s/g,(function(){return s[l++]})))).name="Invariant Violation"}throw c.framesToPop=1,c}}},UxWs:function(e,t,n){"use strict";n.r(t);var r=n("9Hrx"),o=n("xtsi"),a=n("q1tI"),i=n.n(a),u=n("i8i4"),c=n.n(u),s=n("YwZP"),l=n("7hJ6"),p=n("MMVs"),f=n.n(p),d=n("emEt"),h=n("YLt+"),v=n("5yr3"),m={id:"gatsby-announcer",style:{position:"absolute",top:0,width:1,height:1,padding:0,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},"aria-live":"assertive","aria-atomic":"true"},g=n("9Xx/"),w=n("+ZDr"),y=h.reduce((function(e,t){return e[t.fromPath]=t,e}),{});function b(e){var t=y[e];return null!=t&&(window.___replace(t.toPath),!0)}var P=function(e,t){b(e.pathname)||Object(o.apiRunner)("onPreRouteUpdate",{location:e,prevLocation:t})},R=function(e,t){b(e.pathname)||Object(o.apiRunner)("onRouteUpdate",{location:e,prevLocation:t})},S=function(e,t){void 0===t&&(t={});var n=Object(w.parsePath)(e).pathname,r=y[n];if(r&&(e=r.toPath,n=Object(w.parsePath)(e).pathname),window.___swUpdated)window.location=n;else{var a=setTimeout((function(){v.a.emit("onDelayedLoadPageResources",{pathname:n}),Object(o.apiRunner)("onRouteUpdateDelayed",{location:window.location})}),1e3);d.default.loadPage(n).then((function(r){if(!r||r.status===d.PageResourceStatus.Error)return window.history.replaceState({},"",location.href),window.location=n,void clearTimeout(a);r&&r.page.webpackCompilationHash!==window.___webpackCompilationHash&&("serviceWorker"in navigator&&null!==navigator.serviceWorker.controller&&"activated"===navigator.serviceWorker.controller.state&&navigator.serviceWorker.controller.postMessage({gatsbyApi:"clearPathResources"}),console.log("Site has changed on server. Reloading browser"),window.location=n),Object(s.navigate)(e,t),clearTimeout(a)}))}};function E(e,t){var n=this,r=t.location,a=r.pathname,i=r.hash,u=Object(o.apiRunner)("shouldUpdateScroll",{prevRouterProps:e,pathname:a,routerProps:{location:r},getSavedScrollPosition:function(e){return n._stateStorage.read(e)}});if(u.length>0)return u[u.length-1];if(e&&e.location.pathname===a)return i?decodeURI(i.slice(1)):[0,0];return!0}var O=function(e){function t(t){var n;return(n=e.call(this,t)||this).announcementRef=i.a.createRef(),n}Object(r.a)(t,e);var n=t.prototype;return n.componentDidUpdate=function(e,t){var n=this;requestAnimationFrame((function(){var e="new page at "+n.props.location.pathname;document.title&&(e=document.title);var t=document.querySelectorAll("#gatsby-focus-wrapper h1");t&&t.length&&(e=t[0].textContent);var r="Navigated to "+e;n.announcementRef.current&&(n.announcementRef.current.innerText!==r&&(n.announcementRef.current.innerText=r))}))},n.render=function(){return i.a.createElement("div",Object.assign({},m,{ref:this.announcementRef}))},t}(i.a.Component),_=function(e){function t(t){var n;return n=e.call(this,t)||this,P(t.location,null),n}Object(r.a)(t,e);var n=t.prototype;return n.componentDidMount=function(){R(this.props.location,null)},n.componentDidUpdate=function(e,t,n){n&&R(this.props.location,e.location)},n.getSnapshotBeforeUpdate=function(e){return this.props.location.pathname!==e.location.pathname&&(P(this.props.location,e.location),!0)},n.render=function(){return i.a.createElement(i.a.Fragment,null,this.props.children,i.a.createElement(O,{location:location}))},t}(i.a.Component),C=n("IOVJ"),j=n("XyBk"),x=n.n(j);function k(e,t){for(var n in e)if(!(n in t))return!0;for(var r in t)if(e[r]!==t[r])return!0;return!1}var L=function(e){function t(t){var n;n=e.call(this)||this;var r=t.location,o=t.pageResources;return n.state={location:Object.assign({},r),pageResources:o||d.default.loadPageSync(r.pathname)},n}Object(r.a)(t,e),t.getDerivedStateFromProps=function(e,t){var n=e.location;return t.location.href!==n.href?{pageResources:d.default.loadPageSync(n.pathname),location:Object.assign({},n)}:{location:Object.assign({},n)}};var n=t.prototype;return n.loadResources=function(e){var t=this;d.default.loadPage(e).then((function(n){n&&n.status!==d.PageResourceStatus.Error?t.setState({location:Object.assign({},window.location),pageResources:n}):(window.history.replaceState({},"",location.href),window.location=e)}))},n.shouldComponentUpdate=function(e,t){return t.pageResources?this.state.pageResources!==t.pageResources||(this.state.pageResources.component!==t.pageResources.component||(this.state.pageResources.json!==t.pageResources.json||(!(this.state.location.key===t.location.key||!t.pageResources.page||!t.pageResources.page.matchPath&&!t.pageResources.page.path)||function(e,t,n){return k(e.props,t)||k(e.state,n)}(this,e,t)))):(this.loadResources(e.location.pathname),!1)},n.render=function(){return this.props.children(this.state)},t}(i.a.Component),D=n("cSJ8"),T=n("o2xN"),A=new d.ProdLoader(x.a,T);Object(d.setLoader)(A),A.setApiRunner(o.apiRunner),window.asyncRequires=x.a,window.___emitter=v.a,window.___loader=d.publicLoader,g.c.listen((function(e){e.location.action=e.action})),window.___push=function(e){return S(e,{replace:!1})},window.___replace=function(e){return S(e,{replace:!0})},window.___navigate=function(e,t){return S(e,t)},b(window.location.pathname),Object(o.apiRunnerAsync)("onClientEntry").then((function(){Object(o.apiRunner)("registerServiceWorker").length>0&&n("NSX3");var e=function(e){return i.a.createElement(s.BaseContext.Provider,{value:{baseuri:"/",basepath:"/"}},i.a.createElement(C.a,e))},t=function(t){function n(){return t.apply(this,arguments)||this}return Object(r.a)(n,t),n.prototype.render=function(){var t=this,n=this.props.location;return i.a.createElement(L,{location:n},(function(n){var r=n.pageResources,o=n.location;return i.a.createElement(_,{location:o},i.a.createElement(l.ScrollContext,{location:o,shouldUpdateScroll:E},i.a.createElement(s.Router,{basepath:"",location:o,id:"gatsby-focus-wrapper"},i.a.createElement(e,Object.assign({path:"/404.html"===r.page.path?Object(D.a)(o.pathname,""):encodeURI(r.page.matchPath||r.page.path)},t.props,{location:o,pageResources:r},r.json)))))}))},n}(i.a.Component),a=window,u=a.pagePath,p=a.location;u&&""+u!==p.pathname&&!(A.findMatchPath(Object(D.a)(p.pathname,""))||"/404.html"===u||u.match(/^\/404\/?$/)||u.match(/^\/offline-plugin-app-shell-fallback\/?$/))&&Object(s.navigate)(""+u+p.search+p.hash,{replace:!0}),d.publicLoader.loadPage(p.pathname).then((function(e){if(!e||e.status===d.PageResourceStatus.Error)throw new Error("page resources for "+p.pathname+" not found. Not rendering React");window.___webpackCompilationHash=e.page.webpackCompilationHash;var n=function(){return i.a.createElement(s.Location,null,(function(e){return i.a.createElement(t,e)}))},r=Object(o.apiRunner)("wrapRootElement",{element:i.a.createElement(n,null)},i.a.createElement(n,null),(function(e){return{element:e.result}})).pop(),a=function(){return r},u=Object(o.apiRunner)("replaceHydrateFunction",void 0,c.a.hydrate)[0];f()((function(){u(i.a.createElement(a,null),"undefined"!=typeof window?document.getElementById("___gatsby"):void 0,(function(){Object(o.apiRunner)("onInitialClientRender")}))}))}))}))},Wbzz:function(e,t,n){"use strict";n.r(t),n.d(t,"graphql",(function(){return h})),n.d(t,"StaticQueryContext",(function(){return l})),n.d(t,"StaticQuery",(function(){return f})),n.d(t,"useStaticQuery",(function(){return d})),n.d(t,"prefetchPathname",(function(){return s}));var r=n("q1tI"),o=n.n(r),a=n("+ZDr"),i=n.n(a);n.d(t,"Link",(function(){return i.a})),n.d(t,"withAssetPrefix",(function(){return a.withAssetPrefix})),n.d(t,"withPrefix",(function(){return a.withPrefix})),n.d(t,"parsePath",(function(){return a.parsePath})),n.d(t,"navigate",(function(){return a.navigate})),n.d(t,"push",(function(){return a.push})),n.d(t,"replace",(function(){return a.replace})),n.d(t,"navigateTo",(function(){return a.navigateTo}));var u=n("lw3w"),c=n.n(u);n.d(t,"PageRenderer",(function(){return c.a}));var s=n("emEt").default.enqueue,l=o.a.createContext({});function p(e){var t=e.staticQueryData,n=e.data,r=e.query,a=e.render,i=n?n.data:t[r]&&t[r].data;return o.a.createElement(o.a.Fragment,null,i&&a(i),!i&&o.a.createElement("div",null,"Loading (StaticQuery)"))}var f=function(e){var t=e.data,n=e.query,r=e.render,a=e.children;return o.a.createElement(l.Consumer,null,(function(e){return o.a.createElement(p,{data:t,query:n,render:r||a,staticQueryData:e})}))},d=function(e){o.a.useContext;var t=o.a.useContext(l);if(isNaN(Number(e)))throw new Error("useStaticQuery was called with a string but expects to be called using `graphql`. Try this:\n\nimport { useStaticQuery, graphql } from 'gatsby';\n\nuseStaticQuery(graphql`"+e+"`);\n");if(t[e]&&t[e].data)return t[e].data;throw new Error("The result of this StaticQuery could not be fetched.\n\nThis is likely a bug in Gatsby and if refreshing the page does not fix it, please open an issue in https://github.com/gatsbyjs/gatsby/issues")};function h(){throw new Error("It appears like Gatsby is misconfigured. Gatsby related `graphql` calls are supposed to only be evaluated at compile time, and then compiled away. Unfortunately, something went wrong and the query was left in the compiled code.\n\nUnless your site has a complex or custom babel/Gatsby configuration this is likely a bug in Gatsby.")}},XEEL:function(e,t){e.exports=function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}},XyBk:function(e,t,n){t.components={"component---node-modules-gatsby-plugin-offline-app-shell-js":function(){return n.e(5).then(n.t.bind(null,"MqWW",7))},"component---src-pages-404-js":function(){return Promise.all([n.e(0),n.e(1),n.e(2),n.e(6)]).then(n.bind(null,"w2l6"))},"component---src-pages-contact-js":function(){return Promise.all([n.e(0),n.e(1),n.e(2),n.e(7)]).then(n.bind(null,"Cuy+"))},"component---src-pages-index-js":function(){return Promise.all([n.e(0),n.e(1),n.e(2),n.e(8)]).then(n.bind(null,"RXBc"))},"component---src-pages-newsletter-js":function(){return Promise.all([n.e(0),n.e(1),n.e(2),n.e(9)]).then(n.bind(null,"KoSn"))},"component---src-pages-thankyou-js":function(){return Promise.all([n.e(0),n.e(1),n.e(2),n.e(10)]).then(n.bind(null,"5IE7"))},"component---src-templates-blog-post-js":function(){return Promise.all([n.e(0),n.e(1),n.e(2),n.e(11)]).then(n.bind(null,"yZlL"))}}},"YLt+":function(e){e.exports=JSON.parse("[]")},YwZP:function(e,t,n){"use strict";n.r(t),n.d(t,"Link",(function(){return D})),n.d(t,"Location",(function(){return y})),n.d(t,"LocationProvider",(function(){return b})),n.d(t,"Match",(function(){return M})),n.d(t,"Redirect",(function(){return I})),n.d(t,"Router",(function(){return S})),n.d(t,"ServerLocation",(function(){return P})),n.d(t,"isRedirect",(function(){return A})),n.d(t,"redirectTo",(function(){return U})),n.d(t,"useLocation",(function(){return q})),n.d(t,"useNavigate",(function(){return N})),n.d(t,"useParams",(function(){return F})),n.d(t,"useMatch",(function(){return B})),n.d(t,"BaseContext",(function(){return R}));var r=n("q1tI"),o=n.n(r),a=(n("17x9"),n("QLaP")),i=n.n(a),u=n("nqlD"),c=n.n(u),s=n("94VI"),l=n("LYrO");n.d(t,"matchPath",(function(){return l.match}));var p=n("9Xx/");n.d(t,"createHistory",(function(){return p.a})),n.d(t,"createMemorySource",(function(){return p.b})),n.d(t,"navigate",(function(){return p.d})),n.d(t,"globalHistory",(function(){return p.c}));var f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};function d(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function h(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function v(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function m(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var g=function(e,t){var n=c()(t);return n.displayName=e,n},w=g("Location"),y=function(e){var t=e.children;return o.a.createElement(w.Consumer,null,(function(e){return e?t(e):o.a.createElement(b,null,t)}))},b=function(e){function t(){var n,r;h(this,t);for(var o=arguments.length,a=Array(o),i=0;i<o;i++)a[i]=arguments[i];return n=r=v(this,e.call.apply(e,[this].concat(a))),r.state={context:r.getContext(),refs:{unlisten:null}},v(r,n)}return m(t,e),t.prototype.getContext=function(){var e=this.props.history;return{navigate:e.navigate,location:e.location}},t.prototype.componentDidCatch=function(e,t){if(!A(e))throw e;(0,this.props.history.navigate)(e.uri,{replace:!0})},t.prototype.componentDidUpdate=function(e,t){t.context.location!==this.state.context.location&&this.props.history._onTransitionComplete()},t.prototype.componentDidMount=function(){var e=this,t=this.state.refs,n=this.props.history;n._onTransitionComplete(),t.unlisten=n.listen((function(){Promise.resolve().then((function(){requestAnimationFrame((function(){e.unmounted||e.setState((function(){return{context:e.getContext()}}))}))}))}))},t.prototype.componentWillUnmount=function(){var e=this.state.refs;this.unmounted=!0,e.unlisten()},t.prototype.render=function(){var e=this.state.context,t=this.props.children;return o.a.createElement(w.Provider,{value:e},"function"==typeof t?t(e):t||null)},t}(o.a.Component);b.defaultProps={history:p.c};var P=function(e){var t=e.url,n=e.children,r=t.indexOf("?"),a=void 0,i="";return r>-1?(a=t.substring(0,r),i=t.substring(r)):a=t,o.a.createElement(w.Provider,{value:{location:{pathname:a,search:i,hash:""},navigate:function(){throw new Error("You can't call navigate on the server.")}}},n)},R=g("Base",{baseuri:"/",basepath:"/"}),S=function(e){return o.a.createElement(R.Consumer,null,(function(t){return o.a.createElement(y,null,(function(n){return o.a.createElement(E,f({},t,n,e))}))}))},E=function(e){function t(){return h(this,t),v(this,e.apply(this,arguments))}return m(t,e),t.prototype.render=function(){var e=this.props,t=e.location,n=e.navigate,r=e.basepath,a=e.primary,i=e.children,u=(e.baseuri,e.component),c=void 0===u?"div":u,s=d(e,["location","navigate","basepath","primary","children","baseuri","component"]),p=o.a.Children.toArray(i).reduce((function(e,t){var n=G(r)(t);return e.concat(n)}),[]),h=t.pathname,v=Object(l.pick)(p,h);if(v){var m=v.params,g=v.uri,w=v.route,y=v.route.value;r=w.default?r:w.path.replace(/\*$/,"");var b=f({},m,{uri:g,location:t,navigate:function(e,t){return n(Object(l.resolve)(e,g),t)}}),P=o.a.cloneElement(y,b,y.props.children?o.a.createElement(S,{location:t,primary:a},y.props.children):void 0),E=a?_:c,O=a?f({uri:g,location:t,component:c},s):s;return o.a.createElement(R.Provider,{value:{baseuri:g,basepath:r}},o.a.createElement(E,O,P))}return null},t}(o.a.PureComponent);E.defaultProps={primary:!0};var O=g("Focus"),_=function(e){var t=e.uri,n=e.location,r=e.component,a=d(e,["uri","location","component"]);return o.a.createElement(O.Consumer,null,(function(e){return o.a.createElement(x,f({},a,{component:r,requestFocus:e,uri:t,location:n}))}))},C=!0,j=0,x=function(e){function t(){var n,r;h(this,t);for(var o=arguments.length,a=Array(o),i=0;i<o;i++)a[i]=arguments[i];return n=r=v(this,e.call.apply(e,[this].concat(a))),r.state={},r.requestFocus=function(e){!r.state.shouldFocus&&e&&e.focus()},v(r,n)}return m(t,e),t.getDerivedStateFromProps=function(e,t){if(null==t.uri)return f({shouldFocus:!0},e);var n=e.uri!==t.uri,r=t.location.pathname!==e.location.pathname&&e.location.pathname===e.uri;return f({shouldFocus:n||r},e)},t.prototype.componentDidMount=function(){j++,this.focus()},t.prototype.componentWillUnmount=function(){0===--j&&(C=!0)},t.prototype.componentDidUpdate=function(e,t){e.location!==this.props.location&&this.state.shouldFocus&&this.focus()},t.prototype.focus=function(){var e=this.props.requestFocus;e?e(this.node):C?C=!1:this.node&&(this.node.contains(document.activeElement)||this.node.focus())},t.prototype.render=function(){var e=this,t=this.props,n=(t.children,t.style),r=(t.requestFocus,t.component),a=void 0===r?"div":r,i=(t.uri,t.location,d(t,["children","style","requestFocus","component","uri","location"]));return o.a.createElement(a,f({style:f({outline:"none"},n),tabIndex:"-1",ref:function(t){return e.node=t}},i),o.a.createElement(O.Provider,{value:this.requestFocus},this.props.children))},t}(o.a.Component);Object(s.polyfill)(x);var k=function(){},L=o.a.forwardRef;void 0===L&&(L=function(e){return e});var D=L((function(e,t){var n=e.innerRef,r=d(e,["innerRef"]);return o.a.createElement(R.Consumer,null,(function(e){e.basepath;var a=e.baseuri;return o.a.createElement(y,null,(function(e){var i=e.location,u=e.navigate,c=r.to,s=r.state,p=r.replace,h=r.getProps,v=void 0===h?k:h,m=d(r,["to","state","replace","getProps"]),g=Object(l.resolve)(c,a),w=encodeURI(g),y=i.pathname===w,b=Object(l.startsWith)(i.pathname,w);return o.a.createElement("a",f({ref:t||n,"aria-current":y?"page":void 0},m,v({isCurrent:y,isPartiallyCurrent:b,href:g,location:i}),{href:g,onClick:function(e){if(m.onClick&&m.onClick(e),K(e)){e.preventDefault();var t=p;if("boolean"!=typeof p&&y){var n=f({},i.state),r=(n.key,d(n,["key"]));t=Object(l.shallowCompare)(f({},s),r)}u(g,{state:s,replace:t})}}}))}))}))}));function T(e){this.uri=e}D.displayName="Link";var A=function(e){return e instanceof T},U=function(e){throw new T(e)},W=function(e){function t(){return h(this,t),v(this,e.apply(this,arguments))}return m(t,e),t.prototype.componentDidMount=function(){var e=this.props,t=e.navigate,n=e.to,r=(e.from,e.replace),o=void 0===r||r,a=e.state,i=(e.noThrow,e.baseuri),u=d(e,["navigate","to","from","replace","state","noThrow","baseuri"]);Promise.resolve().then((function(){var e=Object(l.resolve)(n,i);t(Object(l.insertParams)(e,u),{replace:o,state:a})}))},t.prototype.render=function(){var e=this.props,t=(e.navigate,e.to),n=(e.from,e.replace,e.state,e.noThrow),r=e.baseuri,o=d(e,["navigate","to","from","replace","state","noThrow","baseuri"]),a=Object(l.resolve)(t,r);return n||U(Object(l.insertParams)(a,o)),null},t}(o.a.Component),I=function(e){return o.a.createElement(R.Consumer,null,(function(t){var n=t.baseuri;return o.a.createElement(y,null,(function(t){return o.a.createElement(W,f({},t,{baseuri:n},e))}))}))},M=function(e){var t=e.path,n=e.children;return o.a.createElement(R.Consumer,null,(function(e){var r=e.baseuri;return o.a.createElement(y,null,(function(e){var o=e.navigate,a=e.location,i=Object(l.resolve)(t,r),u=Object(l.match)(i,a.pathname);return n({navigate:o,location:a,match:u?f({},u.params,{uri:u.uri,path:t}):null})}))}))},q=function(){var e=Object(r.useContext)(w);if(!e)throw new Error("useLocation hook was used but a LocationContext.Provider was not found in the parent tree. Make sure this is used in a component that is a child of Router");return e.location},N=function(){var e=Object(r.useContext)(w);if(!e)throw new Error("useNavigate hook was used but a LocationContext.Provider was not found in the parent tree. Make sure this is used in a component that is a child of Router");return e.navigate},F=function(){var e=Object(r.useContext)(R);if(!e)throw new Error("useParams hook was used but a LocationContext.Provider was not found in the parent tree. Make sure this is used in a component that is a child of Router");var t=q(),n=Object(l.match)(e.basepath,t.pathname);return n?n.params:null},B=function(e){if(!e)throw new Error("useMatch(path: string) requires an argument of a string to match against");var t=Object(r.useContext)(R);if(!t)throw new Error("useMatch hook was used but a LocationContext.Provider was not found in the parent tree. Make sure this is used in a component that is a child of Router");var n=q(),o=Object(l.resolve)(e,t.baseuri),a=Object(l.match)(o,n.pathname);return a?f({},a.params,{uri:a.uri,path:e}):null},H=function(e){return e.replace(/(^\/+|\/+$)/g,"")},G=function e(t){return function(n){if(!n)return null;if(n.type===o.a.Fragment&&n.props.children)return o.a.Children.map(n.props.children,e(t));if(n.props.path||n.props.default||n.type===I||i()(!1),n.type!==I||n.props.from&&n.props.to||i()(!1),n.type!==I||Object(l.validateRedirect)(n.props.from,n.props.to)||i()(!1),n.props.default)return{value:n,default:!0};var r=n.type===I?n.props.from:n.props.path,a="/"===r?t:H(t)+"/"+H(r);return{value:n,default:n.props.default,path:n.props.children?H(a)+"/*":a}}},K=function(e){return!e.defaultPrevented&&0===e.button&&!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}},cSJ8:function(e,t,n){"use strict";function r(e,t){return void 0===t&&(t=""),t?e===t?"/":e.startsWith(t+"/")?e.slice(t.length):e:e}n.d(t,"a",(function(){return r}))},cjBy:function(e,t){function n(t){return"function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?e.exports=n=function(e){return typeof e}:e.exports=n=function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(t)}e.exports=n},cu4x:function(e,t,n){"use strict";t.__esModule=!0,t.parsePath=function(e){var t=e||"/",n="",r="",o=t.indexOf("#");-1!==o&&(r=t.substr(o),t=t.substr(0,o));var a=t.indexOf("?");-1!==a&&(n=t.substr(a),t=t.substr(0,a));return{pathname:t,search:"?"===n?"":n,hash:"#"===r?"":r}}},"e/UW":function(e,t,n){"use strict";t.registerServiceWorker=function(){return!0};var r=[];t.onServiceWorkerActive=function(e){var t=e.getResourceURLsForPathname,n=e.serviceWorker;if(window.___swUpdated)n.active.postMessage({gatsbyApi:"clearPathResources"});else{var o=document.querySelectorAll("\n head > script[src],\n head > link[href],\n head > style[data-href]\n "),a=[].slice.call(o).map((function(e){return e.src||e.href||e.getAttribute("data-href")})),i=[];r.forEach((function(e){var r=t(e);i.push.apply(i,r),n.active.postMessage({gatsbyApi:"setPathResources",path:e,resources:r})})),a.concat(i).forEach((function(e){var t=document.createElement("link");t.rel="prefetch",t.href=e,t.onload=t.remove,t.onerror=t.remove,document.head.appendChild(t)}))}},t.onPostPrefetchPathname=function(e){var t=e.pathname,n=e.getResourceURLsForPathname;if(!window.___swUpdated&&"serviceWorker"in navigator){var o=navigator.serviceWorker;null===o.controller?r.push(t):o.controller.postMessage({gatsbyApi:"setPathResources",path:t,resources:n(t)})}}},emEt:function(e,t,n){"use strict";n.r(t),n.d(t,"PageResourceStatus",(function(){return S})),n.d(t,"BaseLoader",(function(){return x})),n.d(t,"ProdLoader",(function(){return L})),n.d(t,"setLoader",(function(){return D})),n.d(t,"publicLoader",(function(){return T}));var r=n("9Hrx");function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function a(e){return function(e){if(Array.isArray(e))return o(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return o(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?o(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var i=function(e){if("undefined"==typeof document)return!1;var t=document.createElement("link");try{if(t.relList&&"function"==typeof t.relList.supports)return t.relList.supports(e)}catch(n){return!1}return!1}("prefetch")?function(e,t){return new Promise((function(n,r){if("undefined"!=typeof document){var o=document.createElement("link");o.setAttribute("rel","prefetch"),o.setAttribute("href",e),Object.keys(t).forEach((function(e){o.setAttribute(e,t[e])})),o.onload=n,o.onerror=r,(document.getElementsByTagName("head")[0]||document.getElementsByName("script")[0].parentNode).appendChild(o)}else r()}))}:function(e){return new Promise((function(t,n){var r=new XMLHttpRequest;r.open("GET",e,!0),r.onload=function(){200===r.status?t():n()},r.send(null)}))},u={},c=function(e,t){return new Promise((function(n){u[e]?n():i(e,t).then((function(){n(),u[e]=!0})).catch((function(){}))}))},s=n("5yr3"),l=n("LYrO"),p=n("cSJ8"),f=function(e){return void 0===e?e:"/"===e?"/":"/"===e.charAt(e.length-1)?e.slice(0,-1):e};function d(e,t){var n;if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return h(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return h(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(n=e[Symbol.iterator]()).next.bind(n)}function h(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var v=new Map,m=[],g=function(e){var t=decodeURIComponent(e);return Object(p.a)(t,"").split("#")[0].split("?")[0]};function w(e){return e.startsWith("/")||e.startsWith("https://")||e.startsWith("http://")?e:new URL(e,window.location.href+(window.location.href.endsWith("/")?"":"/")).pathname}var y,b=function(e){for(var t,n=R(e),r=d(m);!(t=r()).done;){var o=t.value,a=o.matchPath,i=o.path;if(Object(l.match)(a,n))return f(i)}return null},P=function(e){var t=g(w(e));if(v.has(t))return v.get(t);var n=b(t);return n||(n=R(e)),v.set(t,n),n},R=function(e){var t=g(w(e));return"/index.html"===t&&(t="/"),t=f(t)},S={Error:"error",Success:"success"},E=function(e){return e&&e.default||e},O=function(e){var t;return"/page-data/"+("/"===e?"index":t=(t="/"===(t=e)[0]?t.slice(1):t).endsWith("/")?t.slice(0,-1):t)+"/page-data.json"},_=function(e,t){return void 0===t&&(t="GET"),new Promise((function(n,r){var o=new XMLHttpRequest;o.open(t,e,!0),o.onreadystatechange=function(){4==o.readyState&&n(o)},o.send(null)}))},C=function(e){var t=e.pagePath,n=e.retries,r=void 0===n?0:n,o=O(t);return _(o).then((function(n){var o=n.status,a=n.responseText;if(200===o)try{var i=JSON.parse(a);if(void 0===i.path)throw new Error("not a valid pageData response");return Object.assign(e,{status:S.Success,payload:i})}catch(u){}return 404===o||200===o?"/404.html"===t?Object.assign(e,{status:S.Error}):C(Object.assign(e,{pagePath:"/404.html",notFound:!0})):500===o?Object.assign(e,{status:S.Error}):r<3?C(Object.assign(e,{retries:r+1})):Object.assign(e,{status:S.Error})}))},j=function(e,t){void 0===t&&(t=null);var n={componentChunkName:e.componentChunkName,path:e.path,webpackCompilationHash:e.webpackCompilationHash,matchPath:e.matchPath};return{component:t,json:e.result,page:n}},x=function(){function e(e,t){this.pageDb=new Map,this.inFlightDb=new Map,this.pageDataDb=new Map,this.prefetchTriggered=new Set,this.prefetchCompleted=new Set,this.loadComponent=e,m=t}var t=e.prototype;return t.setApiRunner=function(e){this.apiRunner=e,this.prefetchDisabled=e("disableCorePrefetching").some((function(e){return e}))},t.loadPageDataJson=function(e){var t=this,n=P(e);return this.pageDataDb.has(n)?Promise.resolve(this.pageDataDb.get(n)):C({pagePath:n}).then((function(e){return t.pageDataDb.set(n,e),e}))},t.findMatchPath=function(e){return b(e)},t.loadPage=function(e){var t=this,n=P(e);if(this.pageDb.has(n)){var r=this.pageDb.get(n);return Promise.resolve(r.payload)}if(this.inFlightDb.has(n))return this.inFlightDb.get(n);var o=Promise.all([this.loadAppData(),this.loadPageDataJson(n)]).then((function(e){var r=e[1];if(r.status===S.Error)return{status:S.Error};var o=r.payload,a=o.componentChunkName;return t.loadComponent(a).then((function(a){var i,u={createdAt:new Date};return a?(u.status=S.Success,!0===r.notFound&&(u.notFound=!0),o=Object.assign(o,{webpackCompilationHash:e[0]?e[0].webpackCompilationHash:""}),i=j(o,a),u.payload=i,s.a.emit("onPostLoadPageResources",{page:i,pageResources:i})):u.status=S.Error,t.pageDb.set(n,u),i}))})).then((function(e){return t.inFlightDb.delete(n),e})).catch((function(e){throw t.inFlightDb.delete(n),e}));return this.inFlightDb.set(n,o),o},t.loadPageSync=function(e){var t=P(e);if(this.pageDb.has(t))return this.pageDb.get(t).payload},t.shouldPrefetch=function(e){return!!function(){if("connection"in navigator&&void 0!==navigator.connection){if((navigator.connection.effectiveType||"").includes("2g"))return!1;if(navigator.connection.saveData)return!1}return!0}()&&!this.pageDb.has(e)},t.prefetch=function(e){var t=this;if(!this.shouldPrefetch(e))return!1;if(this.prefetchTriggered.has(e)||(this.apiRunner("onPrefetchPathname",{pathname:e}),this.prefetchTriggered.add(e)),this.prefetchDisabled)return!1;var n=P(e);return this.doPrefetch(n).then((function(){t.prefetchCompleted.has(e)||(t.apiRunner("onPostPrefetchPathname",{pathname:e}),t.prefetchCompleted.add(e))})),!0},t.doPrefetch=function(e){throw new Error("doPrefetch not implemented")},t.hovering=function(e){this.loadPage(e)},t.getResourceURLsForPathname=function(e){var t=P(e),n=this.pageDataDb.get(t);if(n){var r=j(n.payload);return[].concat(a(k(r.page.componentChunkName)),[O(t)])}return null},t.isPageNotFound=function(e){var t=P(e),n=this.pageDb.get(t);return n&&!0===n.notFound},t.loadAppData=function(e){var t=this;return void 0===e&&(e=0),_("/page-data/app-data.json").then((function(n){var r,o=n.status,a=n.responseText;if(200!==o&&e<3)return t.loadAppData(e+1);if(200===o)try{var i=JSON.parse(a);if(void 0===i.webpackCompilationHash)throw new Error("not a valid app-data response");r=i}catch(u){}return r}))},e}(),k=function(e){return(window.___chunkMapping[e]||[]).map((function(e){return""+e}))},L=function(e){function t(t,n){return e.call(this,(function(e){return t.components[e]?t.components[e]().then(E).catch((function(){return null})):Promise.resolve()}),n)||this}Object(r.a)(t,e);var n=t.prototype;return n.doPrefetch=function(e){var t=this,n=O(e);return c(n,{crossOrigin:"anonymous",as:"fetch"}).then((function(){return t.loadPageDataJson(e)})).then((function(e){if(e.status!==S.Success)return Promise.resolve();var t=e.payload,n=t.componentChunkName,r=k(n);return Promise.all(r.map(c)).then((function(){return t}))}))},n.loadPageDataJson=function(t){return e.prototype.loadPageDataJson.call(this,t).then((function(e){return e.notFound?_(t,"HEAD").then((function(t){return 200===t.status?{status:S.Error}:e})):e}))},t}(x),D=function(e){y=e},T={getResourcesForPathname:function(e){return console.warn("Warning: getResourcesForPathname is deprecated. Use loadPage instead"),y.i.loadPage(e)},getResourcesForPathnameSync:function(e){return console.warn("Warning: getResourcesForPathnameSync is deprecated. Use loadPageSync instead"),y.i.loadPageSync(e)},enqueue:function(e){return y.prefetch(e)},getResourceURLsForPathname:function(e){return y.getResourceURLsForPathname(e)},loadPage:function(e){return y.loadPage(e)},loadPageSync:function(e){return y.loadPageSync(e)},prefetch:function(e){return y.prefetch(e)},isPageNotFound:function(e){return y.isPageNotFound(e)},hovering:function(e){return y.hovering(e)},loadAppData:function(){return y.loadAppData()}};t.default=T},hd9s:function(e,t,n){"use strict";var r=n("jGDn"),o=n("5NKs");t.__esModule=!0,t.ScrollContainer=void 0;var a=o(n("j8BX")),i=o(n("XEEL")),u=r(n("q1tI")),c=o(n("i8i4")),s=o(n("17x9")),l=n("Enzk"),p=n("YwZP"),f={scrollKey:s.default.string.isRequired,shouldUpdateScroll:s.default.func,children:s.default.element.isRequired},d=function(e){function t(t){return e.call(this,t)||this}(0,i.default)(t,e);var n=t.prototype;return n.componentDidMount=function(){var e=this,t=c.default.findDOMNode(this),n=this.props,r=n.location,o=n.scrollKey;if(t){t.addEventListener("scroll",(function(){e.props.context.save(r,o,t.scrollTop)}));var a=this.props.context.read(r,o);t.scrollTo(0,a||0)}},n.render=function(){return this.props.children},t}(u.Component),h=function(e){return u.createElement(p.Location,null,(function(t){var n=t.location;return u.createElement(l.ScrollContext.Consumer,null,(function(t){return u.createElement(d,(0,a.default)({},e,{context:t,location:n}))}))}))};t.ScrollContainer=h,h.propTypes=f},hqbx:function(e,t,n){"use strict";var r=n("5NKs");t.__esModule=!0,t.default=function(e,t,n){var r=v(n,t);return e.addEventListener("click",r),function(){return e.removeEventListener("click",r)}},t.routeThroughBrowserOrApp=t.hashShouldBeFollowed=t.pathIsNotHandledByApp=t.urlsAreOnSameOrigin=t.authorIsForcingNavigation=t.anchorsTargetIsEquivalentToSelf=t.findClosestAnchor=t.navigationWasHandledElsewhere=t.slashedPathname=t.userIsForcingNavigation=void 0;var o=r(n("oxjq")),a=n("Wbzz"),i=function(e){return 0!==e.button||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey};t.userIsForcingNavigation=i;var u=function(e){return"/"===e[0]?e:"/"+e};t.slashedPathname=u;var c=function(e){return e.defaultPrevented};t.navigationWasHandledElsewhere=c;var s=function(e){for(;e.parentNode;e=e.parentNode)if("a"===e.nodeName.toLowerCase())return e;return null};t.findClosestAnchor=s;var l=function(e){return!1===e.hasAttribute("target")||null==e.target||["_self",""].includes(e.target)||"_parent"===e.target&&(!e.ownerDocument.defaultView.parent||e.ownerDocument.defaultView.parent===e.ownerDocument.defaultView)||"_top"===e.target&&(!e.ownerDocument.defaultView.top||e.ownerDocument.defaultView.top===e.ownerDocument.defaultView)};t.anchorsTargetIsEquivalentToSelf=l;var p=function(e){return!0===e.hasAttribute("download")||!1===l(e)};t.authorIsForcingNavigation=p;var f=function(e,t){return e.protocol===t.protocol&&e.host===t.host};t.urlsAreOnSameOrigin=f;var d=function(e,t){return!1===t.test(u(e.pathname))||-1!==e.pathname.search(/^.*\.((?!htm)[a-z0-9]{1,5})$/i)};t.pathIsNotHandledByApp=d;var h=function(e,t){return""!==t.hash&&(""===t.pathname||t.pathname===e.pathname)};t.hashShouldBeFollowed=h;var v=function(e,t){return function(n){if(window.___failedResources)return!0;if(i(n))return!0;if(c(n))return!0;var r=s(n.target);if(null==r)return!0;if(p(r))return!0;var l=document.createElement("a");""!==r.href&&(l.href=r.href),r.href instanceof SVGAnimatedString&&(l.href=r.href.animVal);var v=document.createElement("a");if(v.href=window.location.href,!1===f(v,l))return!0;var m=new RegExp("^"+(0,o.default)((0,a.withPrefix)("/")));if(d(l,m))return!0;if(h(v,l))return!0;if(t.excludePattern&&new RegExp(t.excludePattern).test(l.pathname))return!0;n.preventDefault();var g=u(l.pathname).replace(m,"/");return e(""+g+l.search+l.hash),!1}};t.routeThroughBrowserOrApp=v},j8BX:function(e,t){function n(){return e.exports=n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},n.apply(this,arguments)}e.exports=n},jGDn:function(e,t,n){var r=n("cjBy");function o(){if("function"!=typeof WeakMap)return null;var e=new WeakMap;return o=function(){return e},e}e.exports=function(e){if(e&&e.__esModule)return e;if(null===e||"object"!==r(e)&&"function"!=typeof e)return{default:e};var t=o();if(t&&t.has(e))return t.get(e);var n={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in e)if(Object.prototype.hasOwnProperty.call(e,i)){var u=a?Object.getOwnPropertyDescriptor(e,i):null;u&&(u.get||u.set)?Object.defineProperty(n,i,u):n[i]=e[i]}return n.default=e,t&&t.set(e,n),n}},lw3w:function(e,t,n){var r;e.exports=(r=n("rzlk"))&&r.default||r},nqlD:function(e,t,n){var r=n("q1tI").createContext;e.exports=r,e.exports.default=r},nwwn:function(e,t,n){"use strict";t.DEFAULT_OPTIONS={maxWidth:650,wrapperStyle:"",backgroundColor:"white",linkImagesToOriginal:!0,showCaptions:!1,markdownCaptions:!1,withWebp:!1,tracedSVG:!1,loading:"lazy"},t.imageClass="gatsby-resp-image-image",t.imageWrapperClass="gatsby-resp-image-wrapper",t.imageBackgroundClass="gatsby-resp-image-background-image"},o2xN:function(e){e.exports=JSON.parse("[]")},oxjq:function(e,t,n){"use strict";var r=/[|\\{}()[\]^$+*?.]/g;e.exports=function(e){if("string"!=typeof e)throw new TypeError("Expected a string");return e.replace(r,"\\$&")}},pWkz:function(e,t,n){"use strict";t.__esModule=!0,t.onRouteUpdate=void 0;t.onRouteUpdate=function(e,t){var n=e.location;if(void 0===t&&(t={}),"function"!=typeof ga)return null;if(n&&void 0!==window.excludeGAPaths&&window.excludeGAPaths.some((function(e){return e.test(n.pathname)})))return null;var r=Math.max(32,t.pageTransitionDelay||0);return setTimeout((function(){var e=n?n.pathname+n.search+n.hash:void 0;window.ga("set","page",e),window.ga("send","pageview")}),r),null}},q9nr:function(e,t,n){"use strict";var r=n("nwwn"),o=r.DEFAULT_OPTIONS,a=r.imageClass,i=r.imageBackgroundClass,u=r.imageWrapperClass;t.onRouteUpdate=function(e,t){for(var n=Object.assign({},o,t),r=document.querySelectorAll("."+u),c=function(e){var t=r[e],o=t.querySelector("."+i),u=t.querySelector("."+a),c=function(){o.style.transition="opacity 0.5s 0.5s",u.style.transition="opacity 0.5s",s()},s=function e(){o.style.opacity=0,u.style.opacity=1,u.style.color="inherit",u.style.boxShadow="inset 0px 0px 0px 400px "+n.backgroundColor,u.removeEventListener("load",c),u.removeEventListener("error",e)};u.style.opacity=0,u.addEventListener("load",c),u.addEventListener("error",s),u.complete&&s()},s=0;s<r.length;s++)c(s)}},rzlk:function(e,t,n){"use strict";n.r(t);var r=n("q1tI"),o=n.n(r),a=n("IOVJ");t.default=function(e){var t=e.location,n=e.pageResources;return n?o.a.createElement(a.a,Object.assign({location:t,pageResources:n},n.json)):null}},"tb+u":function(e,t,n){},uDP2:function(e,t){e.exports=function(e,t){if(null==e)return{};var n,r,o={},a=Object.keys(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}},v06X:function(e,t){e.exports=function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}},xtsi:function(e,t,n){var r=n("LeKB"),o=n("emEt").publicLoader,a=o.getResourcesForPathname,i=o.getResourcesForPathnameSync,u=o.getResourceURLsForPathname,c=o.loadPage,s=o.loadPageSync;t.apiRunner=function(e,t,n,o){void 0===t&&(t={});var l=r.map((function(n){if(n.plugin[e]){t.getResourcesForPathnameSync=i,t.getResourcesForPathname=a,t.getResourceURLsForPathname=u,t.loadPage=c,t.loadPageSync=s;var r=n.plugin[e](t,n.options);return r&&o&&(t=o({args:t,result:r,plugin:n})),r}}));return(l=l.filter((function(e){return void 0!==e}))).length>0?l:n?[n]:[]},t.apiRunnerAsync=function(e,t,n){return r.reduce((function(n,r){return r.plugin[e]?n.then((function(){return r.plugin[e](t,r.options)})):n}),Promise.resolve())}}},[["UxWs",3,0,12]]]); //# sourceMappingURL=app-62952ca896253591ae45.js.map
import React from "react"; import Routes from "./routes"; import "./global.css"; function App() { return ( <> <Routes /> </> ); } export default App;
function date_time(id) { date = new Date; year = date.getFullYear(); month = date.getMonth(); months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'Jully', 'August', 'September', 'October', 'November', 'December'); d = date.getDate(); day = date.getDay(); days = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); h = date.getHours(); var AMPM; AMPM = h<12? "AM": "PM"; if(h<10) { h = "0"+h; } m = date.getMinutes(); if(m<10) { m = "0"+m; } s = date.getSeconds(); if(s<10) { s = "0"+s; } result = 'Today is '+days[day]+' '+months[month]+' '+d+', '+year+' '+h%12+':'+m+':'+s + AMPM; document.getElementById(id).innerHTML = result; setTimeout('date_time("'+id+'");','1000'); return true; }
const {expect} = require('chai'), parseBooks = require('./parseBooks'), faker = require('faker') describe('parseBooks', () => { let example1, example2, solution1, solution2 before(() => { solution1 = [] solution2 = [] for (let i = 0; i < 10; i++) { // solutions solution1.push({ id: faker.random.alphaNumeric(), authors: [faker.name.findName()], pageCount: faker.random.number(), publishedDate: faker.date.past(), description: faker.lorem.paragraph(), thumbnail: faker.image.imageUrl() }) const solution2temp = { id: faker.random.alphaNumeric(), authors: [faker.name.findName()], pageCount: faker.random.number(), publishedDate: faker.date.past(), description: faker.lorem.paragraph() } if (i % 2 === 0) solution2temp.thumbnail = faker.image.imageUrl() solution2.push(solution2temp) } // examples example1 = solution1.map( ({id, authors, pageCount, publishedDate, description, thumbnail}) => ({ id, volumeInfo: { authors, pageCount, description, publishedDate, imageLinks: {thumbnail} } }) ) example2 = solution2.map(obj => { const returnObj = { id: obj.id, volumeInfo: { authors: obj.authors, pageCount: obj.pageCount, description: obj.description, publishedDate: obj.publishedDate } } if (obj.hasOwnProperty('thumbnail')) { returnObj.volumeInfo.imageLinks = {thumbnail: obj.thumbnail} } return returnObj }) }) it('takes an array of books and returns another array of books', () => { expect(parseBooks([])).to.be.an('array') }) it('returns an array of the same length', () => { expect(parseBooks(example1).length).to.equal(10) }) it('takes the volumeInfo property and sets it at surface level', () => { expect(parseBooks(example1)).to.eql(solution1) }) it('can handle missing imageLinks', () => { expect(parseBooks(example2)).to.eql(solution2) }) })
const { createLogger, transports, format } = require('winston'); const logger = createLogger({ format: format.combine( format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss:ms' }), format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`) ), transports: [ new transports.Console(), ] }); module.exports = logger;
const { Task, Project } = require('../models'); const { get } = require('../utils'); const { isParticipator } = require('./Project'); const { BusinessRuleError } = require('../utils/BusinessRuleError'); const getSubTasks2 = async taskId => { const taskInstance = await Task.findByPk(taskId); const subTasks = (await taskInstance.getSubtask({ raw: true })) || []; for (const subTask of subTasks) { subTask.subTasks = await getSubTasks2(subTask.id); } return subTasks; }; const countSubTasks = task => { const { subTasks } = task; if (subTasks.length) { return subTasks.reduce((prev, curr) => { return prev + 1 + countSubTasks(curr); }, 0); } else { return 0; } }; const getById = async (id, userId) => { const task = await Task.findByPk(id, { raw: true }); if (!task) { throw new BusinessRuleError(`Task with id ${id} does not exist`); } const project = await Project.findByPk(task.projectId, { raw: true }); if (!(await isParticipator(project, userId))) { throw new BusinessRuleError('You are not part of that project!'); } const subTasks = await getSubTasks2(task.id); const subTaskCount = subTasks.reduce((prev, curr) => { return prev + 1 + countSubTasks(curr); }, 0); return { ...task, subTasks, subTaskCount }; }; const create = async (task, userId) => { const { title, details, isDone = false, projectId, taskId: parentTaskId, assigneeId } = task; const project = await Project.findByPk(projectId, { raw: true }); const parentTask = await Task.findByPk(parentTaskId, { raw: true }); if (project === null) { throw new BusinessRuleError(`parent project with id ${projectId} does not exist`); } if (!(await isParticipator(project, userId))) { throw new BusinessRuleError('You are not part of that project!'); } if (parentTaskId && (parentTask === null || projectId !== get(parentTask, 'projectId'))) { throw new BusinessRuleError(`parent task with id ${parentTaskId} does not exist`); } if (assigneeId && !(await isParticipator(project, assigneeId))) { throw new BusinessRuleError('Asignee must be a project participator'); } return await Task.create({ title, details, isDone, projectId, taskId: parentTaskId, assigneeId }); }; const update = async (task, userId) => { const { id, title, details, isDone, assigneeId } = task; const taskInstance = await Task.findByPk(id); if (!taskInstance) { throw new BusinessRuleError(`Task with id ${id} does not exist`); } const project = await Project.findByPk(taskInstance.projectId, { raw: true }); if (!(await isParticipator(project, userId))) { throw new BusinessRuleError('You are not part of that project!'); } if (assigneeId && !(await isParticipator(project, assigneeId))) { throw new BusinessRuleError('Asignee must be a project participator'); } await taskInstance.update({ title, details, isDone, assigneeId }); }; const destroy = async (id, userId) => { const task = await Task.findByPk(id); if (!task) { throw new BusinessRuleError(`Task with id ${id} does not exist`); } const project = await Project.findByPk(task.projectId, { raw: true }); if (!(await isParticipator(project, userId))) { throw new BusinessRuleError('You are not part of that project!'); } await task.destroy(); }; const getSubTasks = async (id, userId) => { const taskInstance = await Task.findByPk(id); if (!taskInstance) { throw new BusinessRuleError(`Task with id ${id} does not exist`); } const projectRawInstance = await Project.findByPk(taskInstance.projectId, { raw: true }); if (!(await isParticipator(projectRawInstance, userId))) { throw new BusinessRuleError('You are not part of that project!'); } return await taskInstance.getSubtask(); }; const getSubTaskIds = async (id, userId) => { const subTasks = await getSubTasks(id, userId); return subTasks.map(e => e.id); }; module.exports = { getById, create, update, destroy, getSubTasks, getSubTaskIds };
var model = require('../lib/model') , should = require('chai').should() , assert = require('chai').assert , expect = require('chai').expect , _ = require('underscore') , async = require('async') , util = require('util') , Datastore = require('../lib/datastore') , fs = require('fs') ; describe('Model', function () { describe('Serialization, deserialization', function () { it('Can serialize and deserialize strings', function () { var a, b, c; a = { test: "Some string" }; b = model.serialize(a); c = model.deserialize(b); b.indexOf('\n').should.equal(-1); c.test.should.equal("Some string"); // Even if a property is a string containing a new line, the serialized // version doesn't. The new line must still be there upon deserialization a = { test: "With a new\nline" }; b = model.serialize(a); c = model.deserialize(b); c.test.should.equal("With a new\nline"); a.test.indexOf('\n').should.not.equal(-1); b.indexOf('\n').should.equal(-1); c.test.indexOf('\n').should.not.equal(-1); }); it('Can serialize and deserialize booleans', function () { var a, b, c; a = { test: true }; b = model.serialize(a); c = model.deserialize(b); b.indexOf('\n').should.equal(-1); c.test.should.equal(true); }); it('Can serialize and deserialize numbers', function () { var a, b, c; a = { test: 5 }; b = model.serialize(a); c = model.deserialize(b); b.indexOf('\n').should.equal(-1); c.test.should.equal(5); }); it('Can serialize and deserialize null', function () { var a, b, c; a = { test: null }; b = model.serialize(a); c = model.deserialize(b); b.indexOf('\n').should.equal(-1); assert.isNull(a.test); }); it('undefined fields are removed when serialized', function() { var a = { bloup: undefined, hello: 'world' } , b = model.serialize(a) , c = model.deserialize(b) ; Object.keys(c).length.should.equal(1); c.hello.should.equal('world'); assert.isUndefined(c.bloup); }); it('Can serialize and deserialize a date', function () { var a, b, c , d = new Date(); a = { test: d }; b = model.serialize(a); c = model.deserialize(b); b.indexOf('\n').should.equal(-1); b.should.equal('{"test":{"$$date":' + d.getTime() + '}}'); util.isDate(c.test).should.equal(true); c.test.getTime().should.equal(d.getTime()); }); it('Can serialize and deserialize sub objects', function () { var a, b, c , d = new Date(); a = { test: { something: 39, also: d, yes: { again: 'yes' } } }; b = model.serialize(a); c = model.deserialize(b); b.indexOf('\n').should.equal(-1); c.test.something.should.equal(39); c.test.also.getTime().should.equal(d.getTime()); c.test.yes.again.should.equal('yes'); }); it('Can serialize and deserialize sub arrays', function () { var a, b, c , d = new Date(); a = { test: [ 39, d, { again: 'yes' } ] }; b = model.serialize(a); c = model.deserialize(b); b.indexOf('\n').should.equal(-1); c.test[0].should.equal(39); c.test[1].getTime().should.equal(d.getTime()); c.test[2].again.should.equal('yes'); }); it('Reject field names beginning with a $ sign or containing a dot, except the four edge cases', function () { var a1 = { $something: 'totest' } , a2 = { "with.dot": 'totest' } , e1 = { $$date: 4321 } , e2 = { $$deleted: true } , e3 = { $$indexCreated: "indexName" } , e4 = { $$indexRemoved: "indexName" } , b; // Normal cases (function () { b = model.serialize(a1); }).should.throw(); (function () { b = model.serialize(a2); }).should.throw(); // Edge cases b = model.serialize(e1); b = model.serialize(e2); b = model.serialize(e3); b = model.serialize(e4); }); it('Can serialize string fields with a new line without breaking the DB', function (done) { var db1, db2 , badString = "world\r\nearth\nother\rline" ; if (fs.existsSync('workspace/test1.db')) { fs.unlinkSync('workspace/test1.db'); } fs.existsSync('workspace/test1.db').should.equal(false); db1 = new Datastore({ filename: 'workspace/test1.db' }); db1.loadDatabase(function (err) { assert.isNull(err); db1.insert({ hello: badString }, function (err) { assert.isNull(err); db2 = new Datastore({ filename: 'workspace/test1.db' }); db2.loadDatabase(function (err) { assert.isNull(err); db2.find({}, function (err, docs) { assert.isNull(err); docs.length.should.equal(1); docs[0].hello.should.equal(badString); done(); }); }); }); }); }); it('Can accept objects whose keys are numbers', function () { var o = { 42: true }; var s = model.serialize(o); }); }); // ==== End of 'Serialization, deserialization' ==== // describe('Object checking', function () { it('Field names beginning with a $ sign are forbidden', function () { assert.isDefined(model.checkObject); (function () { model.checkObject({ $bad: true }); }).should.throw(); (function () { model.checkObject({ some: 42, nested: { again: "no", $worse: true } }); }).should.throw(); // This shouldn't throw since "$actuallyok" is not a field name model.checkObject({ some: 42, nested: [ 5, "no", "$actuallyok", true ] }); (function () { model.checkObject({ some: 42, nested: [ 5, "no", "$actuallyok", true, { $hidden: "useless" } ] }); }).should.throw(); }); it('Field names cannot contain a .', function () { assert.isDefined(model.checkObject); (function () { model.checkObject({ "so.bad": true }); }).should.throw(); // Recursive behaviour testing done in the above test on $ signs }); it('Properties with a null value dont trigger an error', function () { var obj = { prop: null }; model.checkObject(obj); }); it('Can check if an object is a primitive or not', function () { model.isPrimitiveType(5).should.equal(true); model.isPrimitiveType('sdsfdfs').should.equal(true); model.isPrimitiveType(0).should.equal(true); model.isPrimitiveType(true).should.equal(true); model.isPrimitiveType(false).should.equal(true); model.isPrimitiveType(new Date()).should.equal(true); model.isPrimitiveType([]).should.equal(true); model.isPrimitiveType([3, 'try']).should.equal(true); model.isPrimitiveType(null).should.equal(true); model.isPrimitiveType({}).should.equal(false); model.isPrimitiveType({ a: 42 }).should.equal(false); }); }); // ==== End of 'Object checking' ==== // describe('Deep copying', function () { it('Should be able to deep copy any serializable model', function () { var d = new Date() , obj = { a: ['ee', 'ff', 42], date: d, subobj: { a: 'b', b: 'c' } } , res = model.deepCopy(obj); ; res.a.length.should.equal(3); res.a[0].should.equal('ee'); res.a[1].should.equal('ff'); res.a[2].should.equal(42); res.date.getTime().should.equal(d.getTime()); res.subobj.a.should.equal('b'); res.subobj.b.should.equal('c'); obj.a.push('ggg'); obj.date = 'notadate'; obj.subobj = []; // Even if the original object is modified, the copied one isn't res.a.length.should.equal(3); res.a[0].should.equal('ee'); res.a[1].should.equal('ff'); res.a[2].should.equal(42); res.date.getTime().should.equal(d.getTime()); res.subobj.a.should.equal('b'); res.subobj.b.should.equal('c'); }); it('Should deep copy the contents of an array', function () { var a = [{ hello: 'world' }] , b = model.deepCopy(a) ; b[0].hello.should.equal('world'); b[0].hello = 'another'; b[0].hello.should.equal('another'); a[0].hello.should.equal('world'); }); it('Without the strictKeys option, everything gets deep copied', function () { var a = { a: 4, $e: 'rrr', 'eee.rt': 42, nested: { yes: 1, 'tt.yy': 2, $nopenope: 3 }, array: [{ 'rr.hh': 1 }, { yes: true }, { $yes: false }] } , b = model.deepCopy(a) ; assert.deepEqual(a, b); }); it('With the strictKeys option, only valid keys gets deep copied', function () { var a = { a: 4, $e: 'rrr', 'eee.rt': 42, nested: { yes: 1, 'tt.yy': 2, $nopenope: 3 }, array: [{ 'rr.hh': 1 }, { yes: true }, { $yes: false }] } , b = model.deepCopy(a, true) ; assert.deepEqual(b, { a: 4, nested: { yes: 1 }, array: [{}, { yes: true }, {}] }); }); }); // ==== End of 'Deep copying' ==== // describe('Modifying documents', function () { it('Queries not containing any modifier just replace the document by the contents of the query but keep its _id', function () { var obj = { some: 'thing', _id: 'keepit' } , updateQuery = { replace: 'done', bloup: [ 1, 8] } , t ; t = model.modify(obj, updateQuery); t.replace.should.equal('done'); t.bloup.length.should.equal(2); t.bloup[0].should.equal(1); t.bloup[1].should.equal(8); assert.isUndefined(t.some); t._id.should.equal('keepit'); }); it('Throw an error if trying to change the _id field in a copy-type modification', function () { var obj = { some: 'thing', _id: 'keepit' } , updateQuery = { replace: 'done', bloup: [ 1, 8], _id: 'donttryit' } ; expect(function () { model.modify(obj, updateQuery); }).to.throw("You cannot change a document's _id"); updateQuery._id = 'keepit'; model.modify(obj, updateQuery); // No error thrown }); it('Throw an error if trying to use modify in a mixed copy+modify way', function () { var obj = { some: 'thing' } , updateQuery = { replace: 'me', $modify: 'metoo' }; expect(function () { model.modify(obj, updateQuery); }).to.throw("You cannot mix modifiers and normal fields"); }); it('Throw an error if trying to use an inexistent modifier', function () { var obj = { some: 'thing' } , updateQuery = { $set: { it: 'exists' }, $modify: 'not this one' }; expect(function () { model.modify(obj, updateQuery); }).to.throw(/^Unknown modifier .modify/); }); it('Throw an error if a modifier is used with a non-object argument', function () { var obj = { some: 'thing' } , updateQuery = { $set: 'this exists' }; expect(function () { model.modify(obj, updateQuery); }).to.throw(/Modifier .set's argument must be an object/); }); describe('$set modifier', function () { it('Can change already set fields without modfifying the underlying object', function () { var obj = { some: 'thing', yup: 'yes', nay: 'noes' } , updateQuery = { $set: { some: 'changed', nay: 'yes indeed' } } , modified = model.modify(obj, updateQuery); Object.keys(modified).length.should.equal(3); modified.some.should.equal('changed'); modified.yup.should.equal('yes'); modified.nay.should.equal('yes indeed'); Object.keys(obj).length.should.equal(3); obj.some.should.equal('thing'); obj.yup.should.equal('yes'); obj.nay.should.equal('noes'); }); it('Creates fields to set if they dont exist yet', function () { var obj = { yup: 'yes' } , updateQuery = { $set: { some: 'changed', nay: 'yes indeed' } } , modified = model.modify(obj, updateQuery); Object.keys(modified).length.should.equal(3); modified.some.should.equal('changed'); modified.yup.should.equal('yes'); modified.nay.should.equal('yes indeed'); }); it('Can set sub-fields and create them if necessary', function () { var obj = { yup: { subfield: 'bloup' } } , updateQuery = { $set: { "yup.subfield": 'changed', "yup.yop": 'yes indeed', "totally.doesnt.exist": 'now it does' } } , modified = model.modify(obj, updateQuery); _.isEqual(modified, { yup: { subfield: 'changed', yop: 'yes indeed' }, totally: { doesnt: { exist: 'now it does' } } }).should.equal(true); }); it("Doesn't replace a falsy field by an object when recursively following dot notation", function () { var obj = { nested: false } , updateQuery = { $set: { "nested.now": 'it is' } } , modified = model.modify(obj, updateQuery); assert.deepEqual(modified, { nested: false }); // Object not modified as the nested field doesn't exist }); }); // End of '$set modifier' describe('$unset modifier', function () { it('Can delete a field, not throwing an error if the field doesnt exist', function () { var obj, updateQuery, modified; obj = { yup: 'yes', other: 'also' } updateQuery = { $unset: { yup: true } } modified = model.modify(obj, updateQuery); assert.deepEqual(modified, { other: 'also' }); obj = { yup: 'yes', other: 'also' } updateQuery = { $unset: { nope: true } } modified = model.modify(obj, updateQuery); assert.deepEqual(modified, obj); obj = { yup: 'yes', other: 'also' } updateQuery = { $unset: { nope: true, other: true } } modified = model.modify(obj, updateQuery); assert.deepEqual(modified, { yup: 'yes' }); }); it('Can unset sub-fields and entire nested documents', function () { var obj, updateQuery, modified; obj = { yup: 'yes', nested: { a: 'also', b: 'yeah' } } updateQuery = { $unset: { nested: true } } modified = model.modify(obj, updateQuery); assert.deepEqual(modified, { yup: 'yes' }); obj = { yup: 'yes', nested: { a: 'also', b: 'yeah' } } updateQuery = { $unset: { 'nested.a': true } } modified = model.modify(obj, updateQuery); assert.deepEqual(modified, { yup: 'yes', nested: { b: 'yeah' } }); obj = { yup: 'yes', nested: { a: 'also', b: 'yeah' } } updateQuery = { $unset: { 'nested.a': true, 'nested.b': true } } modified = model.modify(obj, updateQuery); assert.deepEqual(modified, { yup: 'yes', nested: {} }); }); it("When unsetting nested fields, should not create an empty parent to nested field", function () { var obj = model.modify({ argh: true }, { $unset: { 'bad.worse': true } }); assert.deepEqual(obj, { argh: true }); obj = model.modify({ argh: true, bad: { worse: 'oh' } }, { $unset: { 'bad.worse': true } }); assert.deepEqual(obj, { argh: true, bad: {} }); obj = model.modify({ argh: true, bad: {} }, { $unset: { 'bad.worse': true } }); assert.deepEqual(obj, { argh: true, bad: {} }); }); }); // End of '$unset modifier' describe('$inc modifier', function () { it('Throw an error if you try to use it with a non-number or on a non number field', function () { (function () { var obj = { some: 'thing', yup: 'yes', nay: 2 } , updateQuery = { $inc: { nay: 'notanumber' } } , modified = model.modify(obj, updateQuery); }).should.throw(); (function () { var obj = { some: 'thing', yup: 'yes', nay: 'nope' } , updateQuery = { $inc: { nay: 1 } } , modified = model.modify(obj, updateQuery); }).should.throw(); }); it('Can increment number fields or create and initialize them if needed', function () { var obj = { some: 'thing', nay: 40 } , modified; modified = model.modify(obj, { $inc: { nay: 2 } }); _.isEqual(modified, { some: 'thing', nay: 42 }).should.equal(true); // Incidentally, this tests that obj was not modified modified = model.modify(obj, { $inc: { inexistent: -6 } }); _.isEqual(modified, { some: 'thing', nay: 40, inexistent: -6 }).should.equal(true); }); it('Works recursively', function () { var obj = { some: 'thing', nay: { nope: 40 } } , modified; modified = model.modify(obj, { $inc: { "nay.nope": -2, "blip.blop": 123 } }); _.isEqual(modified, { some: 'thing', nay: { nope: 38 }, blip: { blop: 123 } }).should.equal(true); }); }); // End of '$inc modifier' describe('$push modifier', function () { it('Can push an element to the end of an array', function () { var obj = { arr: ['hello'] } , modified; modified = model.modify(obj, { $push: { arr: 'world' } }); assert.deepEqual(modified, { arr: ['hello', 'world'] }); }); it('Can push an element to a non-existent field and will create the array', function () { var obj = {} , modified; modified = model.modify(obj, { $push: { arr: 'world' } }); assert.deepEqual(modified, { arr: ['world'] }); }); it('Can push on nested fields', function () { var obj = { arr: { nested: ['hello'] } } , modified; modified = model.modify(obj, { $push: { "arr.nested": 'world' } }); assert.deepEqual(modified, { arr: { nested: ['hello', 'world'] } }); obj = { arr: { a: 2 }}; modified = model.modify(obj, { $push: { "arr.nested": 'world' } }); assert.deepEqual(modified, { arr: { a: 2, nested: ['world'] } }); }); it('Throw if we try to push to a non-array', function () { var obj = { arr: 'hello' } , modified; (function () { modified = model.modify(obj, { $push: { arr: 'world' } }); }).should.throw(); obj = { arr: { nested: 45 } }; (function () { modified = model.modify(obj, { $push: { "arr.nested": 'world' } }); }).should.throw(); }); it('Can use the $each modifier to add multiple values to an array at once', function () { var obj = { arr: ['hello'] } , modified; modified = model.modify(obj, { $push: { arr: { $each: ['world', 'earth', 'everything'] } } }); assert.deepEqual(modified, { arr: ['hello', 'world', 'earth', 'everything'] }); (function () { modified = model.modify(obj, { $push: { arr: { $each: 45 } } }); }).should.throw(); (function () { modified = model.modify(obj, { $push: { arr: { $each: ['world'], unauthorized: true } } }); }).should.throw(); }); it('Can use the $slice modifier to limit the number of array elements', function () { var obj = { arr: ['hello'] } , modified; modified = model.modify(obj, { $push: { arr: { $each: ['world', 'earth', 'everything'], $slice: 1 } } }); assert.deepEqual(modified, { arr: ['hello'] }); modified = model.modify(obj, { $push: { arr: { $each: ['world', 'earth', 'everything'], $slice: -1 } } }); assert.deepEqual(modified, { arr: ['everything'] }); modified = model.modify(obj, { $push: { arr: { $each: ['world', 'earth', 'everything'], $slice: 0 } } }); assert.deepEqual(modified, { arr: [] }); modified = model.modify(obj, { $push: { arr: { $each: ['world', 'earth', 'everything'], $slice: 2 } } }); assert.deepEqual(modified, { arr: ['hello', 'world'] }); modified = model.modify(obj, { $push: { arr: { $each: ['world', 'earth', 'everything'], $slice: -2 } } }); assert.deepEqual(modified, { arr: ['earth', 'everything'] }); modified = model.modify(obj, { $push: { arr: { $each: ['world', 'earth', 'everything'], $slice: -20 } } }); assert.deepEqual(modified, { arr: ['hello', 'world', 'earth', 'everything'] }); modified = model.modify(obj, { $push: { arr: { $each: ['world', 'earth', 'everything'], $slice: 20 } } }); assert.deepEqual(modified, { arr: ['hello', 'world', 'earth', 'everything'] }); modified = model.modify(obj, { $push: { arr: { $each: [], $slice: 1 } } }); assert.deepEqual(modified, { arr: ['hello'] }); // $each not specified, but $slice is modified = model.modify(obj, { $push: { arr: { $slice: 1 } } }); assert.deepEqual(modified, { arr: ['hello'] }); (function () { modified = model.modify(obj, { $push: { arr: { $slice: 1, unauthorized: true } } }); }).should.throw(); (function () { modified = model.modify(obj, { $push: { arr: { $each: [], unauthorized: true } } }); }).should.throw(); }); }); // End of '$push modifier' describe('$addToSet modifier', function () { it('Can add an element to a set', function () { var obj = { arr: ['hello'] } , modified; modified = model.modify(obj, { $addToSet: { arr: 'world' } }); assert.deepEqual(modified, { arr: ['hello', 'world'] }); obj = { arr: ['hello'] }; modified = model.modify(obj, { $addToSet: { arr: 'hello' } }); assert.deepEqual(modified, { arr: ['hello'] }); }); it('Can add an element to a non-existent set and will create the array', function () { var obj = { arr: [] } , modified; modified = model.modify(obj, { $addToSet: { arr: 'world' } }); assert.deepEqual(modified, { arr: ['world'] }); }); it('Throw if we try to addToSet to a non-array', function () { var obj = { arr: 'hello' } , modified; (function () { modified = model.modify(obj, { $addToSet: { arr: 'world' } }); }).should.throw(); }); it('Use deep-equality to check whether we can add a value to a set', function () { var obj = { arr: [ { b: 2 } ] } , modified; modified = model.modify(obj, { $addToSet: { arr: { b: 3 } } }); assert.deepEqual(modified, { arr: [{ b: 2 }, { b: 3 }] }); obj = { arr: [ { b: 2 } ] } modified = model.modify(obj, { $addToSet: { arr: { b: 2 } } }); assert.deepEqual(modified, { arr: [{ b: 2 }] }); }); it('Can use the $each modifier to add multiple values to a set at once', function () { var obj = { arr: ['hello'] } , modified; modified = model.modify(obj, { $addToSet: { arr: { $each: ['world', 'earth', 'hello', 'earth'] } } }); assert.deepEqual(modified, { arr: ['hello', 'world', 'earth'] }); (function () { modified = model.modify(obj, { $addToSet: { arr: { $each: 45 } } }); }).should.throw(); (function () { modified = model.modify(obj, { $addToSet: { arr: { $each: ['world'], unauthorized: true } } }); }).should.throw(); }); }); // End of '$addToSet modifier' describe('$pop modifier', function () { it('Throw if called on a non array, a non defined field or a non integer', function () { var obj = { arr: 'hello' } , modified; (function () { modified = model.modify(obj, { $pop: { arr: 1 } }); }).should.throw(); obj = { bloup: 'nope' }; (function () { modified = model.modify(obj, { $pop: { arr: 1 } }); }).should.throw(); obj = { arr: [1, 4, 8] }; (function () { modified = model.modify(obj, { $pop: { arr: true } }); }).should.throw(); }); it('Can remove the first and last element of an array', function () { var obj , modified; obj = { arr: [1, 4, 8] }; modified = model.modify(obj, { $pop: { arr: 1 } }); assert.deepEqual(modified, { arr: [1, 4] }); obj = { arr: [1, 4, 8] }; modified = model.modify(obj, { $pop: { arr: -1 } }); assert.deepEqual(modified, { arr: [4, 8] }); // Empty arrays are not changed obj = { arr: [] }; modified = model.modify(obj, { $pop: { arr: 1 } }); assert.deepEqual(modified, { arr: [] }); modified = model.modify(obj, { $pop: { arr: -1 } }); assert.deepEqual(modified, { arr: [] }); }); }); // End of '$pop modifier' describe('$pull modifier', function () { it('Can remove an element from a set', function () { var obj = { arr: ['hello', 'world'] } , modified; modified = model.modify(obj, { $pull: { arr: 'world' } }); assert.deepEqual(modified, { arr: ['hello'] }); obj = { arr: ['hello'] }; modified = model.modify(obj, { $pull: { arr: 'world' } }); assert.deepEqual(modified, { arr: ['hello'] }); }); it('Can remove multiple matching elements', function () { var obj = { arr: ['hello', 'world', 'hello', 'world'] } , modified; modified = model.modify(obj, { $pull: { arr: 'world' } }); assert.deepEqual(modified, { arr: ['hello', 'hello'] }); }); it('Throw if we try to pull from a non-array', function () { var obj = { arr: 'hello' } , modified; (function () { modified = model.modify(obj, { $pull: { arr: 'world' } }); }).should.throw(); }); it('Use deep-equality to check whether we can remove a value from a set', function () { var obj = { arr: [{ b: 2 }, { b: 3 }] } , modified; modified = model.modify(obj, { $pull: { arr: { b: 3 } } }); assert.deepEqual(modified, { arr: [ { b: 2 } ] }); obj = { arr: [ { b: 2 } ] } modified = model.modify(obj, { $pull: { arr: { b: 3 } } }); assert.deepEqual(modified, { arr: [{ b: 2 }] }); }); it('Can use any kind of nedb query with $pull', function () { var obj = { arr: [4, 7, 12, 2], other: 'yup' } , modified ; modified = model.modify(obj, { $pull: { arr: { $gte: 5 } } }); assert.deepEqual(modified, { arr: [4, 2], other: 'yup' }); obj = { arr: [{ b: 4 }, { b: 7 }, { b: 1 }], other: 'yeah' }; modified = model.modify(obj, { $pull: { arr: { b: { $gte: 5} } } }); assert.deepEqual(modified, { arr: [{ b: 4 }, { b: 1 }], other: 'yeah' }); }); }); // End of '$pull modifier' describe('$max modifier', function () { it('Will set the field to the updated value if value is greater than current one, without modifying the original object', function () { var obj = { some:'thing', number: 10 } , updateQuery = { $max: { number:12 } } , modified = model.modify(obj, updateQuery); modified.should.deep.equal({ some: 'thing', number: 12 }); obj.should.deep.equal({ some: 'thing', number: 10 }); }); it('Will not update the field if new value is smaller than current one', function () { var obj = { some:'thing', number: 10 } , updateQuery = { $max: { number: 9 } } , modified = model.modify(obj, updateQuery); modified.should.deep.equal({ some:'thing', number:10 }); }); it('Will create the field if it does not exist', function () { var obj = { some: 'thing' } , updateQuery = { $max: { number: 10 } } , modified = model.modify(obj, updateQuery); modified.should.deep.equal({ some: 'thing', number: 10 }); }); it('Works on embedded documents', function () { var obj = { some: 'thing', somethingElse: { number:10 } } , updateQuery = { $max: { 'somethingElse.number': 12 } } , modified = model.modify(obj,updateQuery); modified.should.deep.equal({ some: 'thing', somethingElse: { number:12 } }); }); });// End of '$max modifier' describe('$min modifier', function () { it('Will set the field to the updated value if value is smaller than current one, without modifying the original object', function () { var obj = { some:'thing', number: 10 } , updateQuery = { $min: { number: 8 } } , modified = model.modify(obj, updateQuery); modified.should.deep.equal({ some: 'thing', number: 8 }); obj.should.deep.equal({ some: 'thing', number: 10 }); }); it('Will not update the field if new value is greater than current one', function () { var obj = { some: 'thing', number: 10 } , updateQuery = { $min: { number: 12 } } , modified = model.modify(obj, updateQuery); modified.should.deep.equal({ some: 'thing', number: 10 }); }); it('Will create the field if it does not exist', function () { var obj = { some: 'thing' } , updateQuery = { $min: { number: 10 } } , modified = model.modify(obj, updateQuery); modified.should.deep.equal({ some: 'thing', number: 10 }); }); it('Works on embedded documents', function () { var obj = { some: 'thing', somethingElse: { number: 10 } } , updateQuery = { $min: { 'somethingElse.number': 8 } } , modified = model.modify(obj, updateQuery); modified.should.deep.equal({ some: 'thing', somethingElse: { number: 8 } } ); }); });// End of '$min modifier' }); // ==== End of 'Modifying documents' ==== // describe('Comparing things', function () { it('undefined is the smallest', function () { var otherStuff = [null, "string", "", -1, 0, 5.3, 12, true, false, new Date(12345), {}, { hello: 'world' }, [], ['quite', 5]]; model.compareThings(undefined, undefined).should.equal(0); otherStuff.forEach(function (stuff) { model.compareThings(undefined, stuff).should.equal(-1); model.compareThings(stuff, undefined).should.equal(1); }); }); it('Then null', function () { var otherStuff = ["string", "", -1, 0, 5.3, 12, true, false, new Date(12345), {}, { hello: 'world' }, [], ['quite', 5]]; model.compareThings(null, null).should.equal(0); otherStuff.forEach(function (stuff) { model.compareThings(null, stuff).should.equal(-1); model.compareThings(stuff, null).should.equal(1); }); }); it('Then numbers', function () { var otherStuff = ["string", "", true, false, new Date(4312), {}, { hello: 'world' }, [], ['quite', 5]] , numbers = [-12, 0, 12, 5.7]; model.compareThings(-12, 0).should.equal(-1); model.compareThings(0, -3).should.equal(1); model.compareThings(5.7, 2).should.equal(1); model.compareThings(5.7, 12.3).should.equal(-1); model.compareThings(0, 0).should.equal(0); model.compareThings(-2.6, -2.6).should.equal(0); model.compareThings(5, 5).should.equal(0); otherStuff.forEach(function (stuff) { numbers.forEach(function (number) { model.compareThings(number, stuff).should.equal(-1); model.compareThings(stuff, number).should.equal(1); }); }); }); it('Then strings', function () { var otherStuff = [true, false, new Date(4321), {}, { hello: 'world' }, [], ['quite', 5]] , strings = ['', 'string', 'hello world']; model.compareThings('', 'hey').should.equal(-1); model.compareThings('hey', '').should.equal(1); model.compareThings('hey', 'hew').should.equal(1); model.compareThings('hey', 'hey').should.equal(0); otherStuff.forEach(function (stuff) { strings.forEach(function (string) { model.compareThings(string, stuff).should.equal(-1); model.compareThings(stuff, string).should.equal(1); }); }); }); it('Then booleans', function () { var otherStuff = [new Date(4321), {}, { hello: 'world' }, [], ['quite', 5]] , bools = [true, false]; model.compareThings(true, true).should.equal(0); model.compareThings(false, false).should.equal(0); model.compareThings(true, false).should.equal(1); model.compareThings(false, true).should.equal(-1); otherStuff.forEach(function (stuff) { bools.forEach(function (bool) { model.compareThings(bool, stuff).should.equal(-1); model.compareThings(stuff, bool).should.equal(1); }); }); }); it('Then dates', function () { var otherStuff = [{}, { hello: 'world' }, [], ['quite', 5]] , dates = [new Date(-123), new Date(), new Date(5555), new Date(0)] , now = new Date(); model.compareThings(now, now).should.equal(0); model.compareThings(new Date(54341), now).should.equal(-1); model.compareThings(now, new Date(54341)).should.equal(1); model.compareThings(new Date(0), new Date(-54341)).should.equal(1); model.compareThings(new Date(123), new Date(4341)).should.equal(-1); otherStuff.forEach(function (stuff) { dates.forEach(function (date) { model.compareThings(date, stuff).should.equal(-1); model.compareThings(stuff, date).should.equal(1); }); }); }); it('Then arrays', function () { var otherStuff = [{}, { hello: 'world' }] , arrays = [[], ['yes'], ['hello', 5]] ; model.compareThings([], []).should.equal(0); model.compareThings(['hello'], []).should.equal(1); model.compareThings([], ['hello']).should.equal(-1); model.compareThings(['hello'], ['hello', 'world']).should.equal(-1); model.compareThings(['hello', 'earth'], ['hello', 'world']).should.equal(-1); model.compareThings(['hello', 'zzz'], ['hello', 'world']).should.equal(1); model.compareThings(['hello', 'world'], ['hello', 'world']).should.equal(0); otherStuff.forEach(function (stuff) { arrays.forEach(function (array) { model.compareThings(array, stuff).should.equal(-1); model.compareThings(stuff, array).should.equal(1); }); }); }); it('And finally objects', function () { model.compareThings({}, {}).should.equal(0); model.compareThings({ a: 42 }, { a: 312}).should.equal(-1); model.compareThings({ a: '42' }, { a: '312'}).should.equal(1); model.compareThings({ a: 42, b: 312 }, { b: 312, a: 42 }).should.equal(0); model.compareThings({ a: 42, b: 312, c: 54 }, { b: 313, a: 42 }).should.equal(-1); }); it('Can specify custom string comparison function', function () { model.compareThings('hello', 'bloup', function (a, b) { return a < b ? -1 : 1; }).should.equal(1); model.compareThings('hello', 'bloup', function (a, b) { return a > b ? -1 : 1; }).should.equal(-1); }); }); // ==== End of 'Comparing things' ==== // describe('Querying', function () { describe('Comparing things', function () { it('Two things of different types cannot be equal, two identical native things are equal', function () { var toTest = [null, 'somestring', 42, true, new Date(72998322), { hello: 'world' }] , toTestAgainst = [null, 'somestring', 42, true, new Date(72998322), { hello: 'world' }] // Use another array so that we don't test pointer equality , i, j ; for (i = 0; i < toTest.length; i += 1) { for (j = 0; j < toTestAgainst.length; j += 1) { model.areThingsEqual(toTest[i], toTestAgainst[j]).should.equal(i === j); } } }); it('Can test native types null undefined string number boolean date equality', function () { var toTest = [null, undefined, 'somestring', 42, true, new Date(72998322), { hello: 'world' }] , toTestAgainst = [undefined, null, 'someotherstring', 5, false, new Date(111111), { hello: 'mars' }] , i ; for (i = 0; i < toTest.length; i += 1) { model.areThingsEqual(toTest[i], toTestAgainst[i]).should.equal(false); } }); it('If one side is an array or undefined, comparison fails', function () { var toTestAgainst = [null, undefined, 'somestring', 42, true, new Date(72998322), { hello: 'world' }] , i ; for (i = 0; i < toTestAgainst.length; i += 1) { model.areThingsEqual([1, 2, 3], toTestAgainst[i]).should.equal(false); model.areThingsEqual(toTestAgainst[i], []).should.equal(false); model.areThingsEqual(undefined, toTestAgainst[i]).should.equal(false); model.areThingsEqual(toTestAgainst[i], undefined).should.equal(false); } }); it('Can test objects equality', function () { model.areThingsEqual({ hello: 'world' }, {}).should.equal(false); model.areThingsEqual({ hello: 'world' }, { hello: 'mars' }).should.equal(false); model.areThingsEqual({ hello: 'world' }, { hello: 'world', temperature: 42 }).should.equal(false); model.areThingsEqual({ hello: 'world', other: { temperature: 42 }}, { hello: 'world', other: { temperature: 42 }}).should.equal(true); }); }); describe('Getting a fields value in dot notation', function () { it('Return first-level and nested values', function () { model.getDotValue({ hello: 'world' }, 'hello').should.equal('world'); model.getDotValue({ hello: 'world', type: { planet: true, blue: true } }, 'type.planet').should.equal(true); }); it('Return undefined if the field cannot be found in the object', function () { assert.isUndefined(model.getDotValue({ hello: 'world' }, 'helloo')); assert.isUndefined(model.getDotValue({ hello: 'world', type: { planet: true } }, 'type.plane')); }); it("Can navigate inside arrays with dot notation, and return the array of values in that case", function () { var dv; // Simple array of subdocuments dv = model.getDotValue({ planets: [ { name: 'Earth', number: 3 }, { name: 'Mars', number: 2 }, { name: 'Pluton', number: 9 } ] }, 'planets.name'); assert.deepEqual(dv, ['Earth', 'Mars', 'Pluton']); // Nested array of subdocuments dv = model.getDotValue({ nedb: true, data: { planets: [ { name: 'Earth', number: 3 }, { name: 'Mars', number: 2 }, { name: 'Pluton', number: 9 } ] } }, 'data.planets.number'); assert.deepEqual(dv, [3, 2, 9]); // Nested array in a subdocument of an array (yay, inception!) // TODO: make sure MongoDB doesn't flatten the array (it wouldn't make sense) dv = model.getDotValue({ nedb: true, data: { planets: [ { name: 'Earth', numbers: [ 1, 3 ] }, { name: 'Mars', numbers: [ 7 ] }, { name: 'Pluton', numbers: [ 9, 5, 1 ] } ] } }, 'data.planets.numbers'); assert.deepEqual(dv, [[ 1, 3 ], [ 7 ], [ 9, 5, 1 ]]); }); it("Can get a single value out of an array using its index", function () { var dv; // Simple index in dot notation dv = model.getDotValue({ planets: [ { name: 'Earth', number: 3 }, { name: 'Mars', number: 2 }, { name: 'Pluton', number: 9 } ] }, 'planets.1'); assert.deepEqual(dv, { name: 'Mars', number: 2 }); // Out of bounds index dv = model.getDotValue({ planets: [ { name: 'Earth', number: 3 }, { name: 'Mars', number: 2 }, { name: 'Pluton', number: 9 } ] }, 'planets.3'); assert.isUndefined(dv); // Index in nested array dv = model.getDotValue({ nedb: true, data: { planets: [ { name: 'Earth', number: 3 }, { name: 'Mars', number: 2 }, { name: 'Pluton', number: 9 } ] } }, 'data.planets.2'); assert.deepEqual(dv, { name: 'Pluton', number: 9 }); // Dot notation with index in the middle dv = model.getDotValue({ nedb: true, data: { planets: [ { name: 'Earth', number: 3 }, { name: 'Mars', number: 2 }, { name: 'Pluton', number: 9 } ] } }, 'data.planets.0.name'); dv.should.equal('Earth'); }); }); describe('Field equality', function () { it('Can find documents with simple fields', function () { model.match({ test: 'yeah' }, { test: 'yea' }).should.equal(false); model.match({ test: 'yeah' }, { test: 'yeahh' }).should.equal(false); model.match({ test: 'yeah' }, { test: 'yeah' }).should.equal(true); }); it('Can find documents with the dot-notation', function () { model.match({ test: { ooo: 'yeah' } }, { "test.ooo": 'yea' }).should.equal(false); model.match({ test: { ooo: 'yeah' } }, { "test.oo": 'yeah' }).should.equal(false); model.match({ test: { ooo: 'yeah' } }, { "tst.ooo": 'yeah' }).should.equal(false); model.match({ test: { ooo: 'yeah' } }, { "test.ooo": 'yeah' }).should.equal(true); }); it('Cannot find undefined', function () { model.match({ test: undefined }, { test: undefined }).should.equal(false); model.match({ test: { pp: undefined } }, { "test.pp": undefined }).should.equal(false); }); it('Nested objects are deep-equality matched and not treated as sub-queries', function () { model.match({ a: { b: 5 } }, { a: { b: 5 } }).should.equal(true); model.match({ a: { b: 5, c: 3 } }, { a: { b: 5 } }).should.equal(false); model.match({ a: { b: 5 } }, { a: { b: { $lt: 10 } } }).should.equal(false); (function () { model.match({ a: { b: 5 } }, { a: { $or: [ { b: 10 }, { b: 5 } ] } }) }).should.throw(); }); it("Can match for field equality inside an array with the dot notation", function () { model.match({ a: true, b: [ 'node', 'embedded', 'database' ] }, { 'b.1': 'node' }).should.equal(false); model.match({ a: true, b: [ 'node', 'embedded', 'database' ] }, { 'b.1': 'embedded' }).should.equal(true); model.match({ a: true, b: [ 'node', 'embedded', 'database' ] }, { 'b.1': 'database' }).should.equal(false); }) }); describe('Regular expression matching', function () { it('Matching a non-string to a regular expression always yields false', function () { var d = new Date() , r = new RegExp(d.getTime()); model.match({ test: true }, { test: /true/ }).should.equal(false); model.match({ test: null }, { test: /null/ }).should.equal(false); model.match({ test: 42 }, { test: /42/ }).should.equal(false); model.match({ test: d }, { test: r }).should.equal(false); }); it('Can match strings using basic querying', function () { model.match({ test: 'true' }, { test: /true/ }).should.equal(true); model.match({ test: 'babaaaar' }, { test: /aba+r/ }).should.equal(true); model.match({ test: 'babaaaar' }, { test: /^aba+r/ }).should.equal(false); model.match({ test: 'true' }, { test: /t[ru]e/ }).should.equal(false); }); it('Can match strings using the $regex operator', function () { model.match({ test: 'true' }, { test: { $regex: /true/ } }).should.equal(true); model.match({ test: 'babaaaar' }, { test: { $regex: /aba+r/ } }).should.equal(true); model.match({ test: 'babaaaar' }, { test: { $regex: /^aba+r/ } }).should.equal(false); model.match({ test: 'true' }, { test: { $regex: /t[ru]e/ } }).should.equal(false); }); it('Will throw if $regex operator is used with a non regex value', function () { (function () { model.match({ test: 'true' }, { test: { $regex: 42 } }) }).should.throw(); (function () { model.match({ test: 'true' }, { test: { $regex: 'true' } }) }).should.throw(); }); it('Can use the $regex operator in cunjunction with other operators', function () { model.match({ test: 'helLo' }, { test: { $regex: /ll/i, $nin: ['helL', 'helLop'] } }).should.equal(true); model.match({ test: 'helLo' }, { test: { $regex: /ll/i, $nin: ['helLo', 'helLop'] } }).should.equal(false); }); it('Can use dot-notation', function () { model.match({ test: { nested: 'true' } }, { 'test.nested': /true/ }).should.equal(true); model.match({ test: { nested: 'babaaaar' } }, { 'test.nested': /^aba+r/ }).should.equal(false); model.match({ test: { nested: 'true' } }, { 'test.nested': { $regex: /true/ } }).should.equal(true); model.match({ test: { nested: 'babaaaar' } }, { 'test.nested': { $regex: /^aba+r/ } }).should.equal(false); }); }); describe('$lt', function () { it('Cannot compare a field to an object, an array, null or a boolean, it will return false', function () { model.match({ a: 5 }, { a: { $lt: { a: 6 } } }).should.equal(false); model.match({ a: 5 }, { a: { $lt: [6, 7] } }).should.equal(false); model.match({ a: 5 }, { a: { $lt: null } }).should.equal(false); model.match({ a: 5 }, { a: { $lt: true } }).should.equal(false); }); it('Can compare numbers, with or without dot notation', function () { model.match({ a: 5 }, { a: { $lt: 6 } }).should.equal(true); model.match({ a: 5 }, { a: { $lt: 5 } }).should.equal(false); model.match({ a: 5 }, { a: { $lt: 4 } }).should.equal(false); model.match({ a: { b: 5 } }, { "a.b": { $lt: 6 } }).should.equal(true); model.match({ a: { b: 5 } }, { "a.b": { $lt: 3 } }).should.equal(false); }); it('Can compare strings, with or without dot notation', function () { model.match({ a: "nedb" }, { a: { $lt: "nedc" } }).should.equal(true); model.match({ a: "nedb" }, { a: { $lt: "neda" } }).should.equal(false); model.match({ a: { b: "nedb" } }, { "a.b": { $lt: "nedc" } }).should.equal(true); model.match({ a: { b: "nedb" } }, { "a.b": { $lt: "neda" } }).should.equal(false); }); it('If field is an array field, a match means a match on at least one element', function () { model.match({ a: [5, 10] }, { a: { $lt: 4 } }).should.equal(false); model.match({ a: [5, 10] }, { a: { $lt: 6 } }).should.equal(true); model.match({ a: [5, 10] }, { a: { $lt: 11 } }).should.equal(true); }); it('Works with dates too', function () { model.match({ a: new Date(1000) }, { a: { $gte: new Date(1001) } }).should.equal(false); model.match({ a: new Date(1000) }, { a: { $lt: new Date(1001) } }).should.equal(true); }); }); // General behaviour is tested in the block about $lt. Here we just test operators work describe('Other comparison operators: $lte, $gt, $gte, $ne, $in, $exists', function () { it('$lte', function () { model.match({ a: 5 }, { a: { $lte: 6 } }).should.equal(true); model.match({ a: 5 }, { a: { $lte: 5 } }).should.equal(true); model.match({ a: 5 }, { a: { $lte: 4 } }).should.equal(false); }); it('$gt', function () { model.match({ a: 5 }, { a: { $gt: 6 } }).should.equal(false); model.match({ a: 5 }, { a: { $gt: 5 } }).should.equal(false); model.match({ a: 5 }, { a: { $gt: 4 } }).should.equal(true); }); it('$gte', function () { model.match({ a: 5 }, { a: { $gte: 6 } }).should.equal(false); model.match({ a: 5 }, { a: { $gte: 5 } }).should.equal(true); model.match({ a: 5 }, { a: { $gte: 4 } }).should.equal(true); }); it('$ne', function () { model.match({ a: 5 }, { a: { $ne: 4 } }).should.equal(true); model.match({ a: 5 }, { a: { $ne: 5 } }).should.equal(false); model.match({ a: 5 }, { b: { $ne: 5 } }).should.equal(true); model.match({ a: false }, { a: { $ne: false } }).should.equal(false); }); it('$in', function () { model.match({ a: 5 }, { a: { $in: [6, 8, 9] } }).should.equal(false); model.match({ a: 6 }, { a: { $in: [6, 8, 9] } }).should.equal(true); model.match({ a: 7 }, { a: { $in: [6, 8, 9] } }).should.equal(false); model.match({ a: 8 }, { a: { $in: [6, 8, 9] } }).should.equal(true); model.match({ a: 9 }, { a: { $in: [6, 8, 9] } }).should.equal(true); (function () { model.match({ a: 5 }, { a: { $in: 5 } }); }).should.throw(); }); it('$nin', function () { model.match({ a: 5 }, { a: { $nin: [6, 8, 9] } }).should.equal(true); model.match({ a: 6 }, { a: { $nin: [6, 8, 9] } }).should.equal(false); model.match({ a: 7 }, { a: { $nin: [6, 8, 9] } }).should.equal(true); model.match({ a: 8 }, { a: { $nin: [6, 8, 9] } }).should.equal(false); model.match({ a: 9 }, { a: { $nin: [6, 8, 9] } }).should.equal(false); // Matches if field doesn't exist model.match({ a: 9 }, { b: { $nin: [6, 8, 9] } }).should.equal(true); (function () { model.match({ a: 5 }, { a: { $in: 5 } }); }).should.throw(); }); it('$exists', function () { model.match({ a: 5 }, { a: { $exists: 1 } }).should.equal(true); model.match({ a: 5 }, { a: { $exists: true } }).should.equal(true); model.match({ a: 5 }, { a: { $exists: new Date() } }).should.equal(true); model.match({ a: 5 }, { a: { $exists: '' } }).should.equal(true); model.match({ a: 5 }, { a: { $exists: [] } }).should.equal(true); model.match({ a: 5 }, { a: { $exists: {} } }).should.equal(true); model.match({ a: 5 }, { a: { $exists: 0 } }).should.equal(false); model.match({ a: 5 }, { a: { $exists: false } }).should.equal(false); model.match({ a: 5 }, { a: { $exists: null } }).should.equal(false); model.match({ a: 5 }, { a: { $exists: undefined } }).should.equal(false); model.match({ a: 5 }, { b: { $exists: true } }).should.equal(false); model.match({ a: 5 }, { b: { $exists: false } }).should.equal(true); }); }); describe('Comparing on arrays', function () { it("Can perform a direct array match", function () { model.match({ planets: ['Earth', 'Mars', 'Pluto'], something: 'else' }, { planets: ['Earth', 'Mars'] }).should.equal(false); model.match({ planets: ['Earth', 'Mars', 'Pluto'], something: 'else' }, { planets: ['Earth', 'Mars', 'Pluto'] }).should.equal(true); model.match({ planets: ['Earth', 'Mars', 'Pluto'], something: 'else' }, { planets: ['Earth', 'Pluto', 'Mars'] }).should.equal(false); }); it('Can query on the size of an array field', function () { // Non nested documents model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens": { $size: 0 } }).should.equal(false); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens": { $size: 1 } }).should.equal(false); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens": { $size: 2 } }).should.equal(false); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens": { $size: 3 } }).should.equal(true); // Nested documents model.match({ hello: 'world', description: { satellites: ['Moon', 'Hubble'], diameter: 6300 } }, { "description.satellites": { $size: 0 } }).should.equal(false); model.match({ hello: 'world', description: { satellites: ['Moon', 'Hubble'], diameter: 6300 } }, { "description.satellites": { $size: 1 } }).should.equal(false); model.match({ hello: 'world', description: { satellites: ['Moon', 'Hubble'], diameter: 6300 } }, { "description.satellites": { $size: 2 } }).should.equal(true); model.match({ hello: 'world', description: { satellites: ['Moon', 'Hubble'], diameter: 6300 } }, { "description.satellites": { $size: 3 } }).should.equal(false); // Using a projected array model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens.names": { $size: 0 } }).should.equal(false); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens.names": { $size: 1 } }).should.equal(false); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens.names": { $size: 2 } }).should.equal(false); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens.names": { $size: 3 } }).should.equal(true); }); it('$size operator works with empty arrays', function () { model.match({ childrens: [] }, { "childrens": { $size: 0 } }).should.equal(true); model.match({ childrens: [] }, { "childrens": { $size: 2 } }).should.equal(false); model.match({ childrens: [] }, { "childrens": { $size: 3 } }).should.equal(false); }); it('Should throw an error if a query operator is used without comparing to an integer', function () { (function () { model.match({ a: [1, 5] }, { a: { $size: 1.4 } }); }).should.throw(); (function () { model.match({ a: [1, 5] }, { a: { $size: 'fdf' } }); }).should.throw(); (function () { model.match({ a: [1, 5] }, { a: { $size: { $lt: 5 } } }); }).should.throw(); }); it('Using $size operator on a non-array field should prevent match but not throw', function () { model.match({ a: 5 }, { a: { $size: 1 } }).should.equal(false); }); it('Can use $size several times in the same matcher', function () { model.match({ childrens: [ 'Riri', 'Fifi', 'Loulou' ] }, { "childrens": { $size: 3, $size: 3 } }).should.equal(true); model.match({ childrens: [ 'Riri', 'Fifi', 'Loulou' ] }, { "childrens": { $size: 3, $size: 4 } }).should.equal(false); // Of course this can never be true }); it('Can query array documents with multiple simultaneous conditions', function () { // Non nested documents model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens": { $elemMatch: { name: "Dewey", age: 7 } } }).should.equal(true); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens": { $elemMatch: { name: "Dewey", age: 12 } } }).should.equal(false); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens": { $elemMatch: { name: "Louie", age: 3 } } }).should.equal(false); // Nested documents model.match({ outer: { childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] } }, { "outer.childrens": { $elemMatch: { name: "Dewey", age: 7 } } }).should.equal(true); model.match({ outer: { childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] } }, { "outer.childrens": { $elemMatch: { name: "Dewey", age: 12 } } }).should.equal(false); model.match({ outer: { childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] } }, { "outer.childrens": { $elemMatch: { name: "Louie", age: 3 } } }).should.equal(false); }); it('$elemMatch operator works with empty arrays', function () { model.match({ childrens: [] }, { "childrens": { $elemMatch: { name: "Mitsos" } } }).should.equal(false); model.match({ childrens: [] }, { "childrens": { $elemMatch: {} } }).should.equal(false); }); it('Can use more complex comparisons inside nested query documents', function () { model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens": { $elemMatch: { name: "Dewey", age: { $gt: 6, $lt: 8 } } } }).should.equal(true); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens": { $elemMatch: { name: "Dewey", age: { $in: [ 6, 7, 8 ] } } } } ).should.equal(true); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens": { $elemMatch: { name: "Dewey", age: { $gt: 6, $lt: 7 } } } }).should.equal(false); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens": { $elemMatch: { name: "Louie", age: { $gt: 6, $lte: 7 } } } }).should.equal(false); }); }); describe('Logical operators $or, $and, $not', function () { it('Any of the subqueries should match for an $or to match', function () { model.match({ hello: 'world' }, { $or: [ { hello: 'pluton' }, { hello: 'world' } ] }).should.equal(true); model.match({ hello: 'pluton' }, { $or: [ { hello: 'pluton' }, { hello: 'world' } ] }).should.equal(true); model.match({ hello: 'nope' }, { $or: [ { hello: 'pluton' }, { hello: 'world' } ] }).should.equal(false); model.match({ hello: 'world', age: 15 }, { $or: [ { hello: 'pluton' }, { age: { $lt: 20 } } ] }).should.equal(true); model.match({ hello: 'world', age: 15 }, { $or: [ { hello: 'pluton' }, { age: { $lt: 10 } } ] }).should.equal(false); }); it('All of the subqueries should match for an $and to match', function () { model.match({ hello: 'world', age: 15 }, { $and: [ { age: 15 }, { hello: 'world' } ] }).should.equal(true); model.match({ hello: 'world', age: 15 }, { $and: [ { age: 16 }, { hello: 'world' } ] }).should.equal(false); model.match({ hello: 'world', age: 15 }, { $and: [ { hello: 'world' }, { age: { $lt: 20 } } ] }).should.equal(true); model.match({ hello: 'world', age: 15 }, { $and: [ { hello: 'pluton' }, { age: { $lt: 20 } } ] }).should.equal(false); }); it('Subquery should not match for a $not to match', function () { model.match({ a: 5, b: 10 }, { a: 5 }).should.equal(true); model.match({ a: 5, b: 10 }, { $not: { a: 5 } }).should.equal(false); }); it('Logical operators are all top-level, only other logical operators can be above', function () { (function () { model.match({ a: { b: 7 } }, { a: { $or: [ { b: 5 }, { b: 7 } ] } })}).should.throw(); model.match({ a: { b: 7 } }, { $or: [ { "a.b": 5 }, { "a.b": 7 } ] }).should.equal(true); }); it('Logical operators can be combined as long as they are on top of the decision tree', function () { model.match({ a: 5, b: 7, c: 12 }, { $or: [ { $and: [ { a: 5 }, { b: 8 } ] }, { $and: [{ a: 5 }, { c : { $lt: 40 } }] } ] }).should.equal(true); model.match({ a: 5, b: 7, c: 12 }, { $or: [ { $and: [ { a: 5 }, { b: 8 } ] }, { $and: [{ a: 5 }, { c : { $lt: 10 } }] } ] }).should.equal(false); }); it('Should throw an error if a logical operator is used without an array or if an unknown logical operator is used', function () { (function () { model.match({ a: 5 }, { $or: { a: 5, a: 6 } }); }).should.throw(); (function () { model.match({ a: 5 }, { $and: { a: 5, a: 6 } }); }).should.throw(); (function () { model.match({ a: 5 }, { $unknown: [ { a: 5 } ] }); }).should.throw(); }); }); describe('Comparison operator $where', function () { it('Function should match and not match correctly', function () { model.match({ a: 4}, { $where: function () { return this.a === 4; } }).should.equal(true); model.match({ a: 4}, { $where: function () { return this.a === 5; } }).should.equal(false); }); it('Should throw an error if the $where function is not, in fact, a function', function () { (function () { model.match({ a: 4 }, { $where: 'not a function' }); }).should.throw(); }); it('Should throw an error if the $where function returns a non-boolean', function () { (function () { model.match({ a: 4 }, { $where: function () { return 'not a boolean'; } }); }).should.throw(); }); it('Should be able to do the complex matching it must be used for', function () { var checkEmail = function() { if (!this.firstName || !this.lastName) { return false; } return this.firstName.toLowerCase() + "." + this.lastName.toLowerCase() + "@gmail.com" === this.email; }; model.match({ firstName: "John", lastName: "Doe", email: "john.doe@gmail.com" }, { $where: checkEmail }).should.equal(true); model.match({ firstName: "john", lastName: "doe", email: "john.doe@gmail.com" }, { $where: checkEmail }).should.equal(true); model.match({ firstName: "Jane", lastName: "Doe", email: "john.doe@gmail.com" }, { $where: checkEmail }).should.equal(false); model.match({ firstName: "John", lastName: "Deere", email: "john.doe@gmail.com" }, { $where: checkEmail }).should.equal(false); model.match({ lastName: "Doe", email: "john.doe@gmail.com" }, { $where: checkEmail }).should.equal(false); }); }); describe('Array fields', function () { it('Field equality', function () { model.match({ tags: ['node', 'js', 'db'] }, { tags: 'python' }).should.equal(false); model.match({ tags: ['node', 'js', 'db'] }, { tagss: 'js' }).should.equal(false); model.match({ tags: ['node', 'js', 'db'] }, { tags: 'js' }).should.equal(true); model.match({ tags: ['node', 'js', 'db'] }, { tags: 'js', tags: 'node' }).should.equal(true); // Mixed matching with array and non array model.match({ tags: ['node', 'js', 'db'], nedb: true }, { tags: 'js', nedb: true }).should.equal(true); // Nested matching model.match({ number: 5, data: { tags: ['node', 'js', 'db'] } }, { "data.tags": 'js' }).should.equal(true); model.match({ number: 5, data: { tags: ['node', 'js', 'db'] } }, { "data.tags": 'j' }).should.equal(false); }); it('With one comparison operator', function () { model.match({ ages: [3, 7, 12] }, { ages: { $lt: 2 } }).should.equal(false); model.match({ ages: [3, 7, 12] }, { ages: { $lt: 3 } }).should.equal(false); model.match({ ages: [3, 7, 12] }, { ages: { $lt: 4 } }).should.equal(true); model.match({ ages: [3, 7, 12] }, { ages: { $lt: 8 } }).should.equal(true); model.match({ ages: [3, 7, 12] }, { ages: { $lt: 13 } }).should.equal(true); }); it('Works with arrays that are in subdocuments', function () { model.match({ children: { ages: [3, 7, 12] } }, { "children.ages": { $lt: 2 } }).should.equal(false); model.match({ children: { ages: [3, 7, 12] } }, { "children.ages": { $lt: 3 } }).should.equal(false); model.match({ children: { ages: [3, 7, 12] } }, { "children.ages": { $lt: 4 } }).should.equal(true); model.match({ children: { ages: [3, 7, 12] } }, { "children.ages": { $lt: 8 } }).should.equal(true); model.match({ children: { ages: [3, 7, 12] } }, { "children.ages": { $lt: 13 } }).should.equal(true); }); it('Can query inside arrays thanks to dot notation', function () { model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens.age": { $lt: 2 } }).should.equal(false); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens.age": { $lt: 3 } }).should.equal(false); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens.age": { $lt: 4 } }).should.equal(true); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens.age": { $lt: 8 } }).should.equal(true); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens.age": { $lt: 13 } }).should.equal(true); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens.name": 'Louis' }).should.equal(false); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens.name": 'Louie' }).should.equal(true); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens.name": 'Lewi' }).should.equal(false); }); it('Can query for a specific element inside arrays thanks to dot notation', function () { model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens.0.name": 'Louie' }).should.equal(false); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens.1.name": 'Louie' }).should.equal(false); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens.2.name": 'Louie' }).should.equal(true); model.match({ childrens: [ { name: "Huey", age: 3 }, { name: "Dewey", age: 7 }, { name: "Louie", age: 12 } ] }, { "childrens.3.name": 'Louie' }).should.equal(false); }); it('A single array-specific operator and the query is treated as array specific', function () { (function () { model.match({ childrens: [ 'Riri', 'Fifi', 'Loulou' ] }, { "childrens": { "Fifi": true, $size: 3 } })}).should.throw(); }); it('Can mix queries on array fields and non array filds with array specific operators', function () { model.match({ uncle: 'Donald', nephews: [ 'Riri', 'Fifi', 'Loulou' ] }, { nephews: { $size: 2 }, uncle: 'Donald' }).should.equal(false); model.match({ uncle: 'Donald', nephews: [ 'Riri', 'Fifi', 'Loulou' ] }, { nephews: { $size: 3 }, uncle: 'Donald' }).should.equal(true); model.match({ uncle: 'Donald', nephews: [ 'Riri', 'Fifi', 'Loulou' ] }, { nephews: { $size: 4 }, uncle: 'Donald' }).should.equal(false); model.match({ uncle: 'Donals', nephews: [ 'Riri', 'Fifi', 'Loulou' ] }, { nephews: { $size: 3 }, uncle: 'Picsou' }).should.equal(false); model.match({ uncle: 'Donald', nephews: [ 'Riri', 'Fifi', 'Loulou' ] }, { nephews: { $size: 3 }, uncle: 'Donald' }).should.equal(true); model.match({ uncle: 'Donald', nephews: [ 'Riri', 'Fifi', 'Loulou' ] }, { nephews: { $size: 3 }, uncle: 'Daisy' }).should.equal(false); }); }); }); // ==== End of 'Querying' ==== // });
import React from "react"; import { Flex, HStack, Text, Stack, IconButton } from "@chakra-ui/react"; import { SiGithub, SiLinkedin, SiTwitter, SiGmail } from "react-icons/si"; const Footer = () => { const icons = [ { title: "GitHub", to: "https://github.com/angelhodar", icon: <SiGithub size={32} />, }, { title: "Twitter", to: "https://twitter.com/angelhodar", icon: <SiTwitter size={32} />, color: "twitter", }, { title: "Mail", to: "mailto:angelhodar76@gmail.com", icon: <SiGmail size={32} />, }, { title: "LinkedIn", to: "https://www.linkedin.com/in/angel-rodriguez-hodar-541bb8199/", icon: <SiLinkedin size={32} />, color: "linkedin", }, ]; return ( <Flex direction={{ base: "column", md: "row" }} justify="center" mb="10" mt="10" align="center" > <Stack align="center" spacing="20px" direction={{ base: "column", md: "row" }} > <Text>&copy; {new Date().getFullYear()} Angel Hodar</Text> <HStack spacing="5"> {icons.map(({ title, to, icon, color }) => ( <IconButton key={title} as="a" href={to} target="_blank" aria-label={title} icon={icon} variant="ghost" colorScheme={color} /> ))} </HStack> </Stack> </Flex> ); }; export default Footer;
import Vue from "../../utils/vue"; import { mergeData } from "vue-functional-data-merge"; import { NlyForm, props as formProps } from "../form/form"; export const NlyDropdownForm = Vue.extend({ name: "NlyDropdownForm", functional: true, props: { ...formProps, disabled: { type: Boolean, default: false }, formClass: { type: [String, Object, Array] // default: null } }, render(h, { props, data, children }) { const $attrs = data.attrs || {}; const $listeners = data.on || {}; data.attrs = {}; data.on = {}; return h("li", mergeData(data, { attrs: { role: "presentation" } }), [ h( NlyForm, { ref: "form", staticClass: "nly-dropdown-form", class: [props.formClass, { disabled: props.disabled }], props, attrs: { ...$attrs, disabled: props.disabled, // Tab index of -1 for keyboard navigation tabindex: props.disabled ? null : "-1" }, on: $listeners }, children ) ]); } });
function naiveStringSearch(long, short) { let count = 0; for (let i = 0; i < long.length; i++) { for (let j = 0; j < short.length; j++) { if (long[i + j] !== short[j]) break; if (j === short.length - 1) count++; } } return count; } console.log(naiveStringSearch('yabadabadooada', 'ada'));