code
stringlengths 2
1.05M
|
---|
var templates = []
var icons = {
"application/vnd.ms-excel" : "fa-file-excel-o",
"text/plain" : "fa-file-text-o",
"image/gif" : "fa-file-image-o",
"image/png" : "fa-file-image-o",
"application/pdf" : "fa-file-pdf-o",
"application/x-zip-compressed" : "fa-file-archive-o",
"application/x-gzip" : "fa-file-archive-o",
"application/vnd.openxmlformats-officedocument.presentationml.presentation" : "fa-file-powerpoint-o",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document" : "fa-file-word-o",
"application/octet-stream" : "fa-file-o",
"application/x-msdownload" : "fa-file-o"
}
// Save attempts to POST to /templates/
function save(idx){
var template = {attachments:[]}
template.name = $("#name").val()
template.subject = $("#subject").val()
template.html = CKEDITOR.instances["html_editor"].getData();
template.text = $("#text_editor").val()
// Add the attachments
$.each($("#attachmentsTable").DataTable().rows().data(), function(i, target){
template.attachments.push({
name : target[1],
content: target[3],
type: target[4],
})
})
if (idx != -1){
template.id = templates[idx].id
api.templateId.put(template)
.success(function(data){
successFlash("Template edited successfully!")
load()
dismiss()
})
} else {
// Submit the template
api.templates.post(template)
.success(function(data){
successFlash("Template added successfully!")
load()
dismiss()
})
.error(function(data){
modalError(data.responseJSON.message)
})
}
}
function dismiss(){
$("#modal\\.flashes").empty()
$("#attachmentsTable").dataTable().DataTable().clear().draw()
$("#name").val("")
$("#text_editor").val("")
$("#html_editor").val("")
$("#modal").modal('hide')
}
function deleteTemplate(idx){
if (confirm("Delete " + templates[idx].name + "?")){
api.templateId.delete(templates[idx].id)
.success(function(data){
successFlash(data.message)
load()
})
}
}
function attach(files){
attachmentsTable = $("#attachmentsTable").DataTable();
$.each(files, function(i, file){
var reader = new FileReader();
/* Make this a datatable */
reader.onload = function(e){
var icon = icons[file.type] || "fa-file-o"
// Add the record to the modal
attachmentsTable.row.add([
'<i class="fa ' + icon + '"></i>',
file.name,
'<span class="remove-row"><i class="fa fa-trash-o"></i></span>',
reader.result.split(",")[1],
file.type || "application/octet-stream"
]).draw()
}
reader.onerror = function(e) {
console.log(e)
}
reader.readAsDataURL(file)
})
}
function edit(idx){
$("#modalSubmit").unbind('click').click(function(){save(idx)})
$("#attachmentUpload").unbind('click').click(function(){this.value=null})
$("#html_editor").ckeditor()
$("#attachmentsTable").show()
attachmentsTable = null
if ( $.fn.dataTable.isDataTable('#attachmentsTable') ) {
attachmentsTable = $('#attachmentsTable').DataTable();
}
else {
attachmentsTable = $("#attachmentsTable").DataTable({
"aoColumnDefs" : [{
"targets" : [3,4],
"sClass" : "datatable_hidden"
}]
});
}
var template = {attachments:[]}
if (idx != -1) {
template = templates[idx]
$("#name").val(template.name)
$("#subject").val(template.subject)
$("#html_editor").val(template.html)
$("#text_editor").val(template.text)
$.each(template.attachments, function(i, file){
var icon = icons[file.type] || "fa-file-o"
// Add the record to the modal
attachmentsTable.row.add([
'<i class="fa ' + icon + '"></i>',
file.name,
'<span class="remove-row"><i class="fa fa-trash-o"></i></span>',
file.content,
file.type || "application/octet-stream"
]).draw()
})
}
// Handle Deletion
$("#attachmentsTable").unbind('click').on("click", "span>i.fa-trash-o", function(){
attachmentsTable.row( $(this).parents('tr') )
.remove()
.draw();
})
}
function importEmail(){
raw = $("#email_content").val()
if (!raw){
modalError("No Content Specified!")
} else {
$.ajax({
type: "POST",
url: "/api/import/email",
data: raw,
dataType: "json",
contentType: "text/plain"
})
.success(function(data){
$("#text_editor").val(data.text)
$("#html_editor").val(data.html)
$("#subject").val(data.subject)
$("#importEmailModal").modal("hide")
})
.error(function(data){
modalError(data.responseJSON.message)
})
}
}
function load(){
$("#templateTable").hide()
$("#emptyMessage").hide()
$("#loading").show()
api.templates.get()
.success(function(ts){
templates = ts
$("#loading").hide()
if (templates.length > 0){
$("#templateTable").show()
templateTable = $("#templateTable").DataTable();
templateTable.clear()
$.each(templates, function(i, template){
templateTable.row.add([
template.name,
moment(template.modified_date).format('MMMM Do YYYY, h:mm:ss a'),
"<div class='pull-right'><button class='btn btn-primary' data-toggle='modal' data-target='#modal' onclick='edit(" + i + ")'>\
<i class='fa fa-pencil'></i>\
</button>\
<button class='btn btn-danger' onclick='deleteTemplate(" + i + ")'>\
<i class='fa fa-trash-o'></i>\
</button></div>"
]).draw()
})
} else {
$("#emptyMessage").show()
}
})
.error(function(){
$("#loading").hide()
errorFlash("Error fetching templates")
})
}
$(document).ready(function(){
// Setup multiple modals
// Code based on http://miles-by-motorcycle.com/static/bootstrap-modal/index.html
$('.modal').on('hidden.bs.modal', function( event ) {
$(this).removeClass( 'fv-modal-stack' );
$('body').data( 'fv_open_modals', $('body').data( 'fv_open_modals' ) - 1 );
});
$( '.modal' ).on( 'shown.bs.modal', function ( event ) {
// Keep track of the number of open modals
if ( typeof( $('body').data( 'fv_open_modals' ) ) == 'undefined' )
{
$('body').data( 'fv_open_modals', 0 );
}
// if the z-index of this modal has been set, ignore.
if ( $(this).hasClass( 'fv-modal-stack' ) )
{
return;
}
$(this).addClass( 'fv-modal-stack' );
// Increment the number of open modals
$('body').data( 'fv_open_modals', $('body').data( 'fv_open_modals' ) + 1 );
// Setup the appropriate z-index
$(this).css('z-index', 1040 + (10 * $('body').data( 'fv_open_modals' )));
$( '.modal-backdrop' ).not( '.fv-modal-stack' ).css( 'z-index', 1039 + (10 * $('body').data( 'fv_open_modals' )));
$( '.modal-backdrop' ).not( 'fv-modal-stack' ).addClass( 'fv-modal-stack' );
});
$.fn.modal.Constructor.prototype.enforceFocus = function() {
$( document )
.off( 'focusin.bs.modal' ) // guard against infinite focus loop
.on( 'focusin.bs.modal', $.proxy( function( e ) {
if (
this.$element[ 0 ] !== e.target && !this.$element.has( e.target ).length
// CKEditor compatibility fix start.
&& !$( e.target ).closest( '.cke_dialog, .cke' ).length
// CKEditor compatibility fix end.
) {
this.$element.trigger( 'focus' );
}
}, this ) );
};
load()
})
|
/* Mastermind */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['backbone', 'underscore', 'backbone.radio'], function (Backbone, _) {
return (root.Mastermind = root.Mm = factory(root, Backbone, _));
});
} else if (typeof exports !== 'undefined') {
var Backbone = require('backbone');
var _ = require('underscore');
var Radio = require('backbone.radio');
module.exports = factory(root, Backbone, _);
} else {
root.Mastermind = root.Mm = factory(root, root.Backbone, root._);
}
}(this, function (root, Backbone, _) {
'use strict';
var previousMastermind = root.Mastermind;
var previousMm = root.Mm;
var Mastermind = Backbone.Mastermind = {};
Mastermind.VERSION = '0.0.1';
Mastermind.noConflict = function () {
root.Mastermind = previousMastermind;
root.Mm = previousMm;
return this;
};
//Declare index of models
Mastermind.Models = {};
Mastermind.Screens = {};
Mastermind.Sections = {};
Mastermind.Components = {};
Mastermind.Views = {};
Mastermind.Apps = {};
//Wrap extend to add new extended objects to indexes
var extend = function (properties, classProperties) {
var props = properties || {}, indexKey;
if (props.indexName) {
if (this.prototype instanceof Backbone.Model) {
indexKey = 'Models';
} else if (this.prototype instanceof Backbone.View) {
indexKey = 'Views';
} else if (this.prototype instanceof Backbone.Collection) {
indexKey = 'Collections';
}
if (indexKey) {
Mastermind[indexKey][props.indexName] = this;
}
}
return Backbone.Model.extend.apply(this, arguments);
};
var triggerMethod = function (event) {
var args = [].slice.call(arguments, 1),
methodName = event.split(":").reduce(function (acc, el) {
return acc + el[0].toUpperCase() + el.slice(1);
}, "on");
this.trigger.apply(this, [event].concat(args));
if (typeof(this[methodName]) === "function") {
this[methodName].apply(this, args);
}
};
Mastermind.Class = function () {
if (this.initialize) {
this.initialize.apply(this, arguments);
}
};
_.extend(Mastermind.Class.prototype, Backbone.Events);
Mastermind.Class.extend = extend;
var Model = Mastermind.Model = Backbone.Model.extend({
constructor: function (options) {
Backbone.Model.apply(this, arguments);
}
});
var View = Mastermind.View = Backbone.View.extend({
constructor: function (options) {
Backbone.View.apply(this, arguments);
}
});
var Region = Mastermind.Region = Mastermind.Class.extend({
constructor: function (options) {
options = options || {};
this.$el = options.$el;
Region.__super__.constructor.apply(this, arguments);
},
setElement: function ($el) {
this.$el = $el;
if (this.currentView) {
this.currentView.$el.detach();
this.$el.empty().append(this.currentView.$el);
} else if (this._pendingView) {
this.show(this._pendingView);
this._pendingView = undefined;
}
},
delegateEvents: function () {
if (this.currentView) {
this.currentView.delegateEvents();
}
},
show: function (view) {
if (!this.$el || this.$el.length === 0) {
this._pendingView = view;
return;
}
if (this.currentView) {
this.currentView.triggerMethod("remove");
this.close();
}
this.open(view.render());
view.delegateEvents();
this.currentView = view;
this.currentView.triggerMethod("show");
},
close: function () {
if (this.currentView) {
this.currentView.remove();
}
},
open: function (view) {
this.$el.empty().append(view.el);
}
});
var Layout = Mastermind.Layout = Mastermind.View.extend({
constructor: function (options) {
options = options || {};
var regions = options.regions || this.regions || {};
this.regions = {};
this._regions = [];
_.each(regions, this.addRegion, this);
Layout.__super__.constructor.apply(this, arguments);
},
regionType: Region,
addRegions: function (regions) {
_.each(regions, this.addRegion, this);
},
addRegion: function (value, name) {
var RegionType = value.regionType || this.regionType,
selector = (typeof(value) === "string") ? value : value.selector,
region = new RegionType({$el: this.el ? this.$(selector) : null});
this._regions.push({region: region, selector: selector});
this.regions[name] = region;
},
reattachRegions: function () {
_.chain(this._regions)
.map(function (regionData) {
return {regionData: regionData, $el: this.$(regionData.selector)};
}, this)
.each(function (data) {
data.regionData.region.setElement(data.$el);
});
},
render: function () {
Layout.__super__.render.apply(this, arguments);
this.reattachRegions();
this.trigger("render");
return this;
},
setElement: function () {
Layout.__super__.setElement.apply(this, arguments);
this.reattachRegions();
},
delegateEvents: function () {
Layout.__super__.delegateEvents.apply(this, arguments);
_.each(this._regions, function (regionData) {
regionData.region.delegateEvents();
});
}
});
var Activity = Mastermind.Activity = Mastermind.Layout.extend({
constructor: function (options) {
Mastermind.Layout.apply(this, arguments);
}
});
var Component = Mastermind.Component = Mastermind.Layout.extend({
constructor: function (options) {
Mastermind.Layout.apply(this, arguments);
}
});
var App = Mastermind.Application = Mastermind.Class.extend({
//App constructor
constructor: function (options) {
options = options || {};
var name = options.name || "App" + (_.size(Mastermind.Apps) + 1);
Mastermind.Apps[name] = this;
App.__super__.constructor.apply(this, arguments);
}
});
_.extend(App.prototype, Backbone.Events, {
//App methods
_initCommunications: function () {
this.channels = {};
this.channels.appData = Backbone.Radio.channel("appData");
},
replyGeneralData: function () {
return this.data;
}
});
Mastermind.Region.extend = Mastermind.Model.extend = Mastermind.View.extend = Mastermind.Layout.extend = extend;
Mastermind.Class.triggerMethod = Mastermind.Region.triggerMethod = Mastermind.Model.triggerMethod = Mastermind.View.triggerMethod = Mastermind.Layout.triggerMethod = triggerMethod;
return Mastermind;
}))
;
|
/**
* dirPagination - AngularJS module for paginating (almost) anything.
*
*
* Credits =======
*
* Daniel Tabuenca:
* https://groups.google.com/d/msg/angular/an9QpzqIYiM/r8v-3W1X5vcJ for the idea
* on how to dynamically invoke the ng-repeat directive.
*
* I borrowed a couple of lines and a few attribute names from the AngularUI
* Bootstrap project:
* https://github.com/angular-ui/bootstrap/blob/master/src/pagination/pagination.js
*
* Created by Michael on 04/05/14.
*/
//replace the original app
admin_management_page_app.directive(
'dirPaginate',
[
'$compile',
'$parse',
'$timeout',
'paginationService',
function($compile, $parse, $timeout, paginationService) {
return {
priority : 5000, // High priority means it
// will execute first
terminal : true,
compile : function(element, attrs) {
attrs.$set('ngRepeat', attrs.dirPaginate); // Add
// ng-repeat
// to
// the
// dom
var expression = attrs.dirPaginate;
// regex taken directly from
// https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js#L211
var match = expression
.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
var filterPattern = /\|\s*itemsPerPage:[^|]*/;
if (match[2].match(filterPattern) === null) {
throw "pagination directive: the 'itemsPerPage' filter must be set.";
}
var itemsPerPageFilterRemoved = match[2]
.replace(filterPattern, '');
var collectionGetter = $parse(itemsPerPageFilterRemoved);
// Now that we added ng-repeat to the
// element, proceed with compilation
// but skip directives with priority 5000 or
// above to avoid infinite
// recursion (we don't want to compile
// ourselves again)
var compiled = $compile(element, null, 5000);
return function(scope, element, attrs) {
var paginationId;
paginationId = attrs.paginationId
|| "__default";
paginationService
.registerInstance(paginationId);
var currentPageGetter;
if (attrs.currentPage) {
currentPageGetter = $parse(attrs.currentPage);
} else {
// if the current-page attribute was
// not set, we'll make our own
var defaultCurrentPage = paginationId
+ '__currentPage';
scope[defaultCurrentPage] = 1;
currentPageGetter = $parse(defaultCurrentPage);
}
paginationService.setCurrentPageParser(
paginationId,
currentPageGetter, scope);
if (typeof attrs.totalItems !== 'undefined') {
paginationService
.setAsyncModeTrue(paginationId);
scope
.$watch(
function() {
return $parse(
attrs.totalItems)
(scope);
},
function(result) {
if (0 < result) {
paginationService
.setCollectionLength(
paginationId,
result);
}
});
} else {
scope
.$watchCollection(
function() {
return collectionGetter(scope);
},
function(collection) {
if (collection) {
paginationService
.setCollectionLength(
paginationId,
collection.length);
}
});
}
// When linking just delegate to the
// link function returned by the new
// compile
compiled(scope);
};
}
};
} ])
.directive(
'dirPaginationControls',
[
'paginationService',
function(paginationService) {
/**
* Generate an array of page numbers (or the '...'
* string) which is used in an ng-repeat to generate
* the links used in pagination
*
* @param currentPage
* @param rowsPerPage
* @param paginationRange
* @param collectionLength
* @returns {Array}
*/
function generatePagesArray(currentPage,
collectionLength, rowsPerPage,
paginationRange) {
var pages = [];
var totalPages = Math.ceil(collectionLength
/ rowsPerPage);
var halfWay = Math.ceil(paginationRange / 2);
var position;
if (currentPage <= halfWay) {
position = 'start';
} else if (totalPages - halfWay < currentPage) {
position = 'end';
} else {
position = 'middle';
}
var ellipsesNeeded = paginationRange < totalPages;
var i = 1;
while (i <= totalPages && i <= paginationRange) {
var pageNumber = calculatePageNumber(i,
currentPage, paginationRange,
totalPages);
var openingEllipsesNeeded = (i === 2 && (position === 'middle' || position === 'end'));
var closingEllipsesNeeded = (i === paginationRange - 1 && (position === 'middle' || position === 'start'));
if (ellipsesNeeded
&& (openingEllipsesNeeded || closingEllipsesNeeded)) {
pages.push('...');
} else {
pages.push(pageNumber);
}
i++;
}
return pages;
}
/**
* Given the position in the sequence of pagination
* links [i], figure out what page number
* corresponds to that position.
*
* @param i
* @param currentPage
* @param paginationRange
* @param totalPages
* @returns {*}
*/
function calculatePageNumber(i, currentPage,
paginationRange, totalPages) {
var halfWay = Math.ceil(paginationRange / 2);
if (i === paginationRange) {
return totalPages;
} else if (i === 1) {
return i;
} else if (paginationRange < totalPages) {
if (totalPages - halfWay < currentPage) {
return totalPages - paginationRange + i;
} else if (halfWay < currentPage) {
return currentPage - halfWay + i;
} else {
return i;
}
} else {
return i;
}
}
return {
restrict : 'AE',
templateUrl : '/ng_templates/dir_pagination_tpl.html',
scope : {
maxSize : '=?',
onPageChange : '&?'
},
link : function(scope, element, attrs) {
var paginationId;
paginationId = attrs.paginationId
|| "__default";
if (!scope.maxSize) {
scope.maxSize = 7; //set amount of pagination button
}
scope.directionLinks = angular
.isDefined(attrs.directionLinks) ? scope.$parent
.$eval(attrs.directionLinks)
: true;
scope.boundaryLinks = angular
.isDefined(attrs.boundaryLinks) ? scope.$parent
.$eval(attrs.boundaryLinks)
: false;
if (paginationService
.isRegistered(paginationId) === false) {
throw "pagination directive: the pagination controls cannot be used without the corresponding pagination directive.";
}
var paginationRange = Math.max(
scope.maxSize, 5);
scope.pages = [];
scope.pagination = {
last : 1,
current : 1
};
scope
.$watch(
function() {
return (paginationService
.getCollectionLength(paginationId) + 1)
* paginationService
.getItemsPerPage(paginationId);
},
function(length) {
if (0 < length) {
generatePagination();
}
});
scope.$watch(function() {
return paginationService
.getCurrentPage(paginationId);
}, function(currentPage) {
scope.setCurrent(currentPage);
});
scope.setCurrent = function(num) {
if (/^\d+$/.test(num)) {
if (0 < num
&& num <= scope.pagination.last) {
paginationService
.setCurrentPage(
paginationId,
num);
scope.pages = generatePagesArray(
num,
paginationService
.getCollectionLength(paginationId),
paginationService
.getItemsPerPage(paginationId),
paginationRange);
scope.pagination.current = num;
// if a callback has been set,
// then call it with the page
// number as an argument
if (scope.onPageChange) {
scope.onPageChange({
newPageNumber : num
});
}
}
}
};
function generatePagination() {
scope.pages = generatePagesArray(
1,
paginationService
.getCollectionLength(paginationId),
paginationService
.getItemsPerPage(paginationId),
paginationRange);
scope.pagination.last = scope.pages[scope.pages.length - 1];
if (scope.pagination.last < scope.pagination.current) {
scope
.setCurrent(scope.pagination.last);
}
}
}
};
} ])
.filter(
'itemsPerPage',
[
'paginationService',
function(paginationService) {
return function(collection, itemsPerPage,
paginationId) {
if (typeof (paginationId) === 'undefined') {
paginationId = "__default";
}
var end;
var start;
if (collection instanceof Array) {
itemsPerPage = itemsPerPage || 9999999999;
if (paginationService
.isAsyncMode(paginationId)) {
start = 0;
} else {
start = (paginationService
.getCurrentPage(paginationId) - 1)
* itemsPerPage;
}
end = start + itemsPerPage;
paginationService.setItemsPerPage(
paginationId, itemsPerPage);
return collection.slice(start, end);
} else {
return collection;
}
};
} ])
.service(
'paginationService',
function() {
var instances = {};
var lastRegisteredInstance;
this.paginationDirectiveInitialized = false;
this.registerInstance = function(instanceId) {
if (typeof instances[instanceId] === 'undefined') {
instances[instanceId] = {
asyncMode : false
};
lastRegisteredInstance = instanceId;
}
};
this.isRegistered = function(instanceId) {
return (typeof instances[instanceId] !== 'undefined');
};
this.getLastInstanceId = function() {
return lastRegisteredInstance;
};
this.setCurrentPageParser = function(instanceId, val, scope) {
instances[instanceId].currentPageParser = val;
instances[instanceId].context = scope;
};
this.setCurrentPage = function(instanceId, val) {
instances[instanceId].currentPageParser.assign(
instances[instanceId].context, val);
};
this.getCurrentPage = function(instanceId) {
return instances[instanceId]
.currentPageParser(instances[instanceId].context);
};
this.setItemsPerPage = function(instanceId, val) {
instances[instanceId].itemsPerPage = val;
};
this.getItemsPerPage = function(instanceId) {
return instances[instanceId].itemsPerPage;
};
this.setCollectionLength = function(instanceId, val) {
instances[instanceId].collectionLength = val;
};
this.getCollectionLength = function(instanceId) {
return instances[instanceId].collectionLength;
};
this.setAsyncModeTrue = function(instanceId) {
instances[instanceId].asyncMode = true;
};
this.isAsyncMode = function(instanceId) {
return instances[instanceId].asyncMode;
};
});
|
$(function(){
var attach = function($fileInput, policy_url, el){
$fileInput.fileupload({
paramName: 'file',
autoUpload: true,
dataType: 'xml',
add: function(e, data){
$(el).attr('class', 's3direct progress-active')
$.ajax({
url: policy_url,
type: 'POST',
data: {type: data.files[0].type},
success: function(fields) {
data.url = fields.form_action
delete fields.form_action
data.formData = fields
data.submit()
}
})
},
progress: function(e, data){
var progress = parseInt(data.loaded / data.total * 100, 10)
$(el).find('.bar').css({width: progress + '%'})
},
error: function(e, data){
alert('Oops, file upload failed, please try again')
$(el).attr('class', 's3direct form-active')
},
done: function(e, data){
var url = $(data.result).find('Location').text().replace(/%2F/g, '/')
var file_name = url.replace(/^.*[\\\/]/, '')
$(el).find('.link').attr('href', url).text(file_name)
$(el).attr('class', 's3direct link-active')
$(el).find('input[type=hidden]').val(url)
$(el).find('.bar').css({width: '0%'})
}
})
}
var setup = function(el){
var policy_url = $(el).data('url')
var file_url = $(el).find('input[type=hidden]').val()
var $fileInput = $(el).find('input[type=file]')
var class_ = (file_url === '') ? 'form-active' : 'link-active'
$(el).attr('class', 's3direct ' + class_)
$(el).find('.remove').click(function(e){
e.preventDefault()
$(el).find('input[type=hidden]').val('')
$(el).attr('class', 's3direct form-active')
})
attach($fileInput, policy_url, el)
}
$('.s3direct').each(function(i, el){
setup(el)
})
$(document).bind('DOMNodeInserted', function(e) {
var el = $(e.target).find('.s3direct').get(0)
var yes = $(el).length !== 0
if(yes) setup(el)
})
})
|
import ObjectProxy from '@ember/object/proxy';
import { computed } from '@ember/object';
import { guidFor } from '@ember/object/internals';
import fixProto from 'ember-light-table/utils/fix-proto';
/**
* @module Table
* @extends Ember.ObjectProxy
* @class Row
*/
export default class Row extends ObjectProxy.extend({
/**
* Whether the row is hidden.
*
* CSS Classes:
* - `is-hidden`
*
* @property hidden
* @type {Boolean}
* @default false
*/
hidden: false,
/**
* Whether the row is expanded.
*
* CSS Classes:
* - `is-expanded`
*
* @property expanded
* @type {Boolean}
* @default false
*/
expanded: false,
/**
* Whether the row is selected.
*
* CSS Classes:
* - `is-selected`
*
* @property selected
* @type {Boolean}
* @default false
*/
selected: false,
/**
* Class names to be applied to this row
*
* @property classNames
* @type {String | Array}
*/
classNames: null,
/**
* Data content for this row. Since this class extends Ember.ObjectProxy,
* all properties are forwarded to the content. This means that instead of
* `row.content.foo` you can just do `row.foo`. Please note that methods are
* not forwarded. You will not be able to do `row.save()`, instead, you would have
* to do `row.content.save()`.
*
* @property content
* @type {Object}
*/
content: null,
/**
* Rows's unique ID.
*
* Note: named `rowId` in order to not shadow the `content.id` property.
*
* @property rowId
* @type {String}
* @readOnly
*/
rowId: computed(function() {
return guidFor(this);
}).readOnly()
}) {}
// https://github.com/offirgolan/ember-light-table/issues/436#issuecomment-310138868
fixProto(Row);
|
'use strict';
/* Controllers */
angular.module('myApp.controllers', ['myApp.services', 'restangular'])
.controller('myController', [
"$scope", "$filter", "cardRes", "balRes", "Restangular",
function($scope, $filter, cardRes, balRes, resty) {
var Restangular = resty.all('api');
var newCard = {
name: 'New Card',
deadline: new Date(),
reward: 1,
rewardUnit: 'Miles?',
minSpend: 1
};
var newBal = {
asOf: new Date(),
amount: 0
};
$scope.newCard = angular.extend({}, newCard);
var cq = function () {
Restangular.all('cards').getList().then(function(cards) {
for(var i = 0; i < cards.length;i++) {
var x = cards[i];
x.newBalance = angular.extend({cardid: x._id}, newBal);
}
$scope.cards = cards;
});
return;
$scope.cards = cardRes.query({}, function (xx) {
angular.forEach(xx, function(x){
x.newBalance = angular.extend({cardid: x._id}, newBal);
});
});
};
cq();
$scope.saveCard = function(card) {
var mythen = function() {
};
if ( !card._id ) {
card.post().then(function() {
$scope.newCard = angular.extend({}, newCard);
}).then(mythen);
} else {
card.patch().then(mythen);
}
delete card.newBalance;
cardRes.save(card, function() {
if(!card._id) {
$scope.newCard = angular.extend({}, newCard);
}
cq();
});
};
$scope.deleteCard = function(card) {
cardRes.delete(card, function() {
cq();
});
};
$scope.showBalances = function(cardid) {
var card = $filter("filter")($scope.cards, {_id: cardid})[0];
card.balances = balRes.query({cardid: cardid});
};
$scope.saveBalance = function(card, bal) {
var b = new balRes(bal);
b.$patch({cardid: bal.cardid}, function(res, headers) {
var id = headers.location.split(/\//g).pop();
bal._id = id;
card.balances.push(bal);
card.newBalance = angular.extend({cardid: card._id}, newBal);
});
};
$scope.deleteBalance = function(cardid, balid) {
var j = {cardid:cardid, _id:balid};
var b = new balRes(j);
b.$delete(j, function() {
$scope.showBalances(cardid);
})
};
}]);
|
/*
Module dependencies.
*/
var Stack = require('digger-stack');
var Mongo = require('digger-mongo');
var Static = require('digger-static');
var Mailgun = require('digger-mailgun');
module.exports = function(config){
config = config || {};
var mongo_hostname = config.MONGO_ADDR || process.env.MONGO_PORT_27017_TCP_ADDR;
var mongo_port = config.MONGO_PORT || process.env.MONGO_PORT_27017_TCP_PORT;
// reception stack
return new Stack({
router:require('./router')(config),
suppliers:{
'/config':Static({
folder:__dirname + '/config'
}),
'/email':Mailgun({
apikey:config.MAILGUN_KEY || process.env.MAILGUN_KEY,
domain:config.MAILGUN_DOMAIN || process.env.MAILGUN_DOMAIN
}),
'/orders':Mongo({
database:config.MONGO_DATABASE,
collection:'orders',
hostname:mongo_hostname,
port:mongo_port
}),
'/stash':Mongo({
database:config.MONGO_DATABASE,
collection:'stash',
hostname:mongo_hostname,
port:mongo_port
})
}
});
}
|
/*!
* js-comments <https://github.com/jonschlinkert/js-comments>
*
* Copyright (c) 2014-2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
'use strict';
/**
* Module dependencies.
*/
var fs = require('fs');
var path = require('path');
var relative = require('relative');
var union = require('arr-union');
var parse = require('parse-comments');
var helpers = require('logging-helpers');
var writeFile = require('write');
var _ = require('lodash');
/**
* Default template to use
*/
var defaultTemplate = require('js-comments-template');
/**
* Parse comments from the given `str`.
*
* ```js
* var fs = require('fs');
* var str = fs.readFileSync('foo.js', 'utf8');
* comments.parse(str, options);
* ```
*
* @param {String} `str` The string to parse.
* @param {Object} `options` Options to pass to [parse-comments]
* @return {Array} Array of comment objects.
* @api public
*/
exports.parse = parse;
/**
* Process the given Lo-dash `template` string, passing a
* `comments` object as context.
*
* ```js
* comments.render(obj, options);
* ```
*
* @param {Array} `comments` Array of comment objects.
* @param {String} `template` The lo-dash template to use.
* @return {String}
* @api public
*/
exports.render = function render(comments, template, options) {
if (typeof template !== 'string') {
options = template;
template = null;
}
var defaults = {file: {path: ''}};
var opts = _.merge({}, defaults, options);
opts.file.path = relative(opts.src || opts.path || opts.file.path || '');
var ctx = _.cloneDeep(opts);
ctx.file.comments = comments;
_.merge(ctx, comments.options);
if (opts.filter !== false) {
ctx.file.comments = exports.filter(ctx.file.comments, ctx);
}
var settings = {};
settings.imports = _.merge({}, helpers, ctx.imports);
var fn = ctx.engine || _.template;
ctx.template = template || ctx.template || defaultTemplate;
var result = fn(ctx.template, settings)(ctx);
if (ctx.format) return exports.format(result);
return result;
};
/**
* Basic markdown corrective formatting
*/
exports.format = function format(str) {
str = str.replace(/(?:\r\n|\n){3,}/g, '\n\n');
var headingRe = /^(#{1,6})\s*([^\n]+)\s*/gm;
var boldRe = /^\s+\*\*([^\n]+)\*\*(?=\n)\s+/gm;
var match;
while(match = headingRe.exec(str)) {
str = str.split(match[0]).join(match[1] + ' ' + match[2] + '\n\n');
}
while(match = boldRe.exec(str)) {
str = str.split(match[0]).join('\n**' + match[1] + '**\n\n');
}
return str.trim();
};
/**
* Write markdown API documentation to the given `dest` from the code
* comments in the given JavaScript `src` file.
*
* @param {String} `src` Source file path.
* @param {String} `dest` Destination file path.
* @param {Object} `options`
* @return {String} API documentation
* @api public
*/
exports.renderFile = function renderFile(src, dest, options) {
var opts = _.merge({src: path.resolve(src), dest: path.resolve(dest)}, options);
var str = fs.readFileSync(opts.src, 'utf8');
var ctx = exports.filter(exports.parse(str, opts), opts);
var res = exports.format(exports.render(ctx, opts)).trim();
writeFile.sync(dest, res);
};
/**
* Filter and normalize the given `comments` object.
*
* @param {Object} `comments`
* @param {Object} `options`
* @return {Object} Normalized comments object.
*/
exports.filter = function filter(comments, opts) {
comments = comments || [];
opts = opts || {};
var len = comments.length, i = 0;
var res = [];
while (len--) {
var o = comments[i++];
if (o.comment.begin === 1) {
continue;
}
if (o.string && /^.{1,8}!/.test(o.string)) {
continue;
}
if (opts.stripBanner && i === 0) {
continue;
}
if (o.type === 'property') {
continue;
}
if (!o.api || o.api !== 'public') {
continue;
}
// If the user explicitly defines a `@type`,
// use that instead of the code context type
if (o && o.type) {
o.type = o.type;
}
if (o['public']) {
o.api = 'public';
}
// update line numbers
o.begin = o.begin || o.comment.begin;
o.context.begin = o.context.begin || o.begin;
o.end = o.end || o.comment.end;
o.line = o.end ? (o.end + 2) : o.begin;
if (o.returns && o.returns.length) {
o.returns.map(function (ele) {
var len = ele.description.length;
if (ele.description.charAt(0) === '{' && ele.description[len - 1] === '}') {
ele.type = ele.description.slice(1, len - 1);
delete ele.description;
}
});
}
if (o.doc) {
if (o.doc.indexOf('./') === 0) {
var src = opts.src || o.file && o.file.path;
if (src) {
var dir = path.dirname(src);
o.doc = path.resolve(dir, o.doc);
var str = fs.readFileSync(o.doc, 'utf8');
o.extras = str;
}
} else {
var tmp = o.doc;
var tag = makeTag(tmp, opts);
o.doc = null;
o.description = o.description || '';
o.description = tag + '\n\n' + o.description;
}
}
if (o.noname) {
o.heading.text = o.noname;
res.push(o);
o = null;
return res;
}
var heading = o.heading || {};
if (o.section === true) {
heading.level = 1;
}
var lvl = heading.level || 2;
if (o.name) {
heading.text = o.name;
}
if (!o.section) {
lvl = heading.lvl || 2;
}
var text = heading.text;
var prefix = '######'.slice(0, lvl + 1);
o.prefix = prefix;
o.lvl = lvl;
if (text) {
if (heading.prefix && heading.prefix === '.' && text.charAt(0) !== '.') {
text = heading.prefix + text;
heading = null;
}
o.prefixed = prefix + ' ' + text;
o.title = text;
if (/^\.{2,}/.test(o.title)) {
o.title = '.' + o.title.replace(/^\.+/, '');
}
}
o.examples = o.examples || [];
if (o.name && typeof opts.examples === 'object' && opts.examples.hasOwnProperty(o.name)) {
o.examples = union(o.examples, opts.examples[o.name]);
}
o.examples.forEach(function (example) {
o.description = o.description.split(example.block).join('');
o.description = o.description.split(/\s+\*\*Examples?\*\*\s+/).join('\n');
o.description = o.description.split(/\n{2,}/).join('\n').replace(/\s+$/, '');
});
res.push(o);
o = null;
}
return res;
};
function makeTag(str, opts) {
if (opts && opts.tag) return opts.tag(str);
return '<%= docs("' + str + '") %>';
}
|
function setup(){
createCanvas(innerWidth, innerHeight);
}
function draw(){
background('lightblue');
if(dist(mouseX, mouseY, width/2, height/2) > 50){
fill('red')
} else {
fill('green');
}
ellipse(width/2, height/2, 100, 100);
}
|
/*********************************************
* skel/MoSyncApp/LocalFiles/js/yloader.js
* YeAPF 0.8.48-103 built on 2016-05-24 18:54 (-3 DST)
* Copyright (C) 2004-2016 Esteban Daniel Dortta - dortta@yahoo.com
* 2016-03-07 13:46:13 (-3 DST)
* First Version (C) 2014 - esteban daniel dortta - dortta@yahoo.com
* Purpose: Build a monolitic YeAPF script so
* it can be loaded at once
**********************************************/
if (typeof console === 'undefined')
if (typeof window != 'undefined')
var console = (window.console = window.console || {});
else
var console = {};
(
function () {
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
], method;
for (var i=0; i<methods.length; i++) {
method = methods[i];
if (!console[method]) console[method] = function () {};
}
}
)();
/* START yopcontext.js */
/***********************************************************************
* First Version (C) 2014 - esteban daniel dortta - dortta@yahoo.com
*
* This is a set of function that helps to recognize operational context
**********************************************************************/
function getInternetExplorerVersion() {
/* http://msdn.microsoft.com/en-us/library/ms537509(v=vs.85).aspx
* Returns the version of Internet Explorer or a -1
* (indicating the use of another browser).
*/
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
function isInternetExplorer() {
return (getInternetExplorerVersion() >= 0);
}
function isOnMobile() {
var ret=false;
if (typeof mosync != 'undefined') {
ret = mosync.isAndroid || mosync.isIOS || mosync.isWindowsPhone;
}
return ret;
}
/* END yopcontext.js */
/* START ydebug.js */
/*********************************************
* First Version (C) 2014 - esteban daniel dortta - dortta@yahoo.com
**********************************************/
ydbg = function() {
var that = {};
that.logLevel = 0;
that.logFlag = 0;
return that;
};
function __dump__(aLineConsole) {
if (isOnMobile())
mosync.rlog(aLineConsole);
else
console.log(aLineConsole);
}
// This functions can be used with mosync or browser
// and replaces console.log() / mosync.rlog()
function _dump() {
var aLine = '',
aLineConsole,
aAnArgument;
for (var i=0; i<arguments.length; i++) {
if (aLine>'')
aLine+=', ';
aAnArgument = arguments[i];
if (typeof aAnArgument=="object")
aAnArgument = aAnArgument.toString();
aLine += aAnArgument;
}
aLineConsole = /* arguments.callee.caller.name+': '+*/aLine;
__dump__(aLine);
/* OBSOLETO 2016-02-24
if ((typeof jsDumpEnabled != "undefined") && (jsDumpEnabled)) {
aLine = '<b>'+arguments.callee.caller.name+'</b> <small>'+aLine+'</small>';
var mainBody=__getMainBody();
var isReady = (typeof mainBody.$ == 'function') && (mainBody.document.body != null);
if (isReady) {
var debug = mainBody.y$('debug');
if (!debug) {
debug = mainBody.document.createElement('div');
debug.id='debug';
debug.className='debug';
setOpacity(debug,60);
debug.onmouseover = __debugMouseOver;
debug.onmouseout = __debugMouseOut;
mainBody.document.body.appendChild(debug);
}
if (debug.innerHTML=='')
debug.innerHTML = '<b>YeAPF!</b>';
else {
var auxText = debug.innerHTML;
auxText = auxText.split('<br>');
auxText = auxText.splice(Math.max(0,auxText.length-50));
auxText = auxText.join('<br>');
debug.innerHTML = auxText;
}
debug.innerHTML += '<br>'+aLine;
debug.scrollTop = debug.scrollHeight;
} else {
aLine = aLine.replace('<small>','\n ');
aLine = aLine.replace('</small>','\n');
aLine = aLine.replace('<b>','');
aLine = aLine.replace('</b>','');
alert(aLine);
}
}
*/
}
function _setLogFlagLevel(aLogFlag, aLevel) {
ydbg.logFlag=aLogFlag;
ydbg.logLevel=aLevel;
}
function _dumpy(logFlag, logLevel) {
if (ydbg.logFlag & logFlag) {
if (ydbg.logLevel>=logLevel) {
var aLine = '', aAnArgument;
for (var i=2; i<arguments.length; i++) {
if (aLine>'')
aLine+=', ';
aAnArgument = arguments[i];
if (typeof aAnArgument=="object")
aAnArgument = aAnArgument.toString();
aLine += aAnArgument;
}
__dump__(aLine);
}
}
}
/* END ydebug.js */
var yloaderBase = function () {
var that = {};
(function () {
if (typeof document=='object') {
var scripts= document.getElementsByTagName('script');
var path= scripts[scripts.length-1].src.split('?')[0];
var mydir= path.split('/').slice(0, -1).join('/')+'/';
} else
var mydir='./';
that.selfLocation = mydir;
_dump("Loading from "+mydir);
})();
that.isWorker = (typeof importScripts == 'function');
that.isMobile = (!that.isWorker) && (typeof window.orientation !== 'undefined');
that.isChromeExtension = (!that.isWorker) && ((window.chrome && chrome.runtime && chrome.runtime.id) || (that.selfLocation.substr(0,17)=='chrome-extension:'));
that.isChromeSandbox = (!that.isWorker) && ((that.isChromeExtension) && !(chrome.storage));
that.loadLibrary = function (jsFileName) {
var libFileName;
if (jsFileName>'') {
if (that.selfLocation.substr(0,17)!='chrome-extension:')
jsFileName = that.selfLocation+'/'+jsFileName+'?v=0.8.48';
else {
// chrome.runtime.id
var auxChromeExtension = that.selfLocation.split('/');
var auxLocation = '';
for (var i=3; i<auxChromeExtension.length; i++) {
if (auxChromeExtension[i]>'') {
if (auxLocation>'')
auxLocation+='/';
auxLocation+=auxChromeExtension[i];
}
}
jsFileName = auxLocation+'/'+jsFileName+'?v=0.8.34';
}
jsFileName = jsFileName.replace(/\/\//g,'\/');
jsFileName = jsFileName.replace('http:/','http://');
var auxName = jsFileName.split('/');
if (auxName.length>0)
libFileName = auxName[auxName.length-1];
if (typeof importScripts == 'function')
importScripts(jsFileName);
else {
var _script = document.createElement('script');
_script.type=(jsFileName.indexOf('.js')>0)?'text/javascript':(jsFileName.indexOf('.css')>0)?'text/css':'text/text';
_script.src=jsFileName;
document.getElementsByTagName('head')[0].appendChild(_script);
}
_dump(libFileName+' added');
}
};
/*
if (that.isMobile) {
that.loadLibrary('wormhole.js');
document.addEventListener(
"backbutton",
function() { mosync.app.exit(); },
true);
}
*/
if (!that.isWorker) {
that.priorOnload=window.onload;
window.onload = function() {
var elem = (document.compatMode === "CSS1Compat") ?
document.documentElement :
document.body;
var appScreen=document.getElementById('screen');
if (appScreen)
appScreen.style.width = elem.clientWidth + 'px';
if (that.priorOnLoad != undefined) {
that.priorOnLoad();
}
}
}
return that;
};
_dump("R1");
var yloader=yloaderBase();
_dump("R2");
/* START ymisc.js */
/*********************************************
* First Version (C) 2014 - esteban daniel dortta - dortta@yahoo.com
*
* Many of the prototypes extensions are based
* on Douglas Crockford's JavaScript: The Good Parts
**********************************************/
/*
* dom shortcut 'y$()'
*/
( function () {
y$ = function (aElementId) {
var ret=null, auxRet;
if (aElementId>'') {
if (aElementId.substr(0,1)=='#')
aElementId = aElementId.substr(1);
ret = document.getElementById(aElementId);
if (!ret)
ret = document.getElementsByName(aElementId)[0];
if (!ret) {
if (aElementId.substr(0,1)=='.')
aElementId = aElementId.substr(1);
auxRet = getElementsByClassName(document, '*', aElementId);
if (auxRet.length>0)
ret=auxRet;
}
}
return ret;
};
})();
if (typeof $ =='undefined') $ = y$;
/*
* $frame()
* given a frame name by path it returns dom frame
* i.e. if there is a frame named innerF inside an frame called mainFrame
* that belongs to body, you can call $frame('/mainFrame/innerF')
* But you can call it by reference
* i.e. you is inside a frame called whateverF and you don't know
* who si it main frame, you can call the main frame by $frame('../')
* If you doesn't know the path, you can use $frameByName()
* If you doesn't know the path nor the name, but at least a function name
* you can use $frameOwner()
*/
function $frame(frameName) {
if (frameName.substr(0,2)=='./')
frameName=frameName.substr(2);
var rootFrame;
if (frameName.substr(0,3)=='../') {
rootFrame=parent;
frameName=frameName.substr(3);
} else if (frameName=='/') {
frameName='';
// rootFrame = this;
rootFrame = top;
} else if (frameName.substr(0,1)=='/') {
rootFrame = top;
frameName=frameName.substr(1);
} else
rootFrame=self;
if (frameName>'') {
var list=frameName.split('/');
for(var n=0; n<list.length; n++)
rootFrame=rootFrame.frames[list[n]];
}
return rootFrame;
}
function $frameByName(frameName) {
_searchFrameByName_ = function(aRootFrame, frameName)
{
var aFrame=null;
if (aRootFrame.frames) {
for (var n=0; (aFrame===null) && (n<aRootFrame.frames.length); n++)
if (aRootFrame.frames[n].name==frameName)
aFrame=aRootFrame.frames[n];
else
aFrame=_searchFrameByName_(aRootFrame.frames[n], frameName);
}
return aFrame;
};
return _searchFrameByName_(top, frameName);
}
function $frameOwner(aName, aType) {
_searchFunctionInFrame_ = function (aName, aType, f)
{
var ret;
var aux="typeof f."+aName+"=='"+aType+"'";
if (eval(aux)) {
ret=f;
} else {
var n=0;
if (f.frames)
while ((n<f.frames.length) && (ret===undefined))
ret = _searchFunctionInFrame_(aName, aType, f.frames[n++]);
}
return ret;
};
// alert("looking for "+aName+" as "+aType);
var f=$frame('/');
return _searchFunctionInFrame_(aName, aType, f);
}
function produceWaitMsg(msg) {
var feedbackCSS='<style type="text/css"><!--.yWarnBanner { font-family: Georgia, "Times New Roman", Times, serif; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; text-transform: none; margin: 16px; padding: 8px; background-color: #DFEEF2; border: 1px dotted #387589; line-height: 24px;}--></style>';
var feedbackText = '<div class=yWarnBanner><img src="images/waitIcon.gif" height=18px> {0} </div>';
var aux=feedbackCSS + feedbackText.format(msg);
return aux;
}
/*
* http://snipplr.com/view/1853/get-elements-by-attribute/
*/
function getElementsByAttribute(oRootElem, strTagName, strAttributeName, strAttributeValue){
console.log("getElementsByAttribute()");
var arrElements = oRootElem.getElementsByTagName(strTagName);
var arrReturnElements = [];
var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)", "i") : null;
var oCurrent;
var oAttribute;
for(var i=0; i<arrElements.length; i++){
oCurrent = arrElements[i];
oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName);
if(typeof oAttribute == "string" && oAttribute.length > 0){
if (typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))) {
arrReturnElements.push(oCurrent);
}
}
}
return arrReturnElements;
}
function getElementsByClassName(oRootElem, strTagName, aClassName) {
console.log("getElementsByClassName()");
var arrElements = oRootElem.getElementsByTagName(strTagName);
var arrReturnElements = [];
var oCurrent;
for(var i=0; i<arrElements.length; i++) {
oCurrent = arrElements[i];
if ((oCurrent) && (typeof oCurrent.hasClass == 'function'))
if (oCurrent.hasClass(aClassName))
arrReturnElements.push(oCurrent);
}
return arrReturnElements;
}
var getClientSize = function () {
var auxDE = (document && document.documentElement)?document.documentElement:{clientWidth:800, clientHeight: 600};
var auxW = (window)?window:{innerWidth: 800, innerHeight: 600};
var w = Math.max(auxDE.clientWidth, auxW.innerWidth || 0);
var h = Math.max(auxDE.clientHeight, auxW.innerHeight || 0);
return [w, h];
};
if (typeof resizeIframe == 'undefined') {
var resizeIframe = function (obj, objMargin) {
objMargin = objMargin || {};
objMargin.width = objMargin.width || 0;
objMargin.height = objMargin.height || 0;
var s1, s2, bestSize, onResize;
s1 = screen.height;
s2 = obj.contentWindow.document.body.scrollHeight + 40 - objMargin.height;
bestSize=Math.max(s1, s2);
obj.style.height = bestSize + 'px';
s1 = screen.width;
s2 = obj.contentWindow.document.body.scrollWidth + 40 - objMargin.width;
bestSize=Math.max(s1, s2);
obj.style.width = bestSize + 'px';
onResize = obj.getAttribute('onResize');
if (onResize) {
eval(onResize);
}
};
}
/*
* HTMLElement prototype extensions
*/
if (typeof HTMLElement=='function') {
HTMLElement.prototype.hasClass = function (aClassName) {
var ret = false;
if (this.className) {
var aClasses = this.className.split(' ');
for(var i = 0; i<aClasses.length; i++) {
if (aClasses[i] == aClassName)
ret = true;
}
}
return ret;
};
HTMLElement.prototype.deleteClass = function(aClassName) {
var aNewClasses='';
var aClasses=this.className.split(' ');
for(var i = 0; i<aClasses.length; i++) {
if (aClasses[i] != aClassName) {
if (aNewClasses>'')
aNewClasses = aNewClasses+' ';
aNewClasses = aNewClasses + aClasses[i];
}
}
this.className=aNewClasses;
return this;
};
HTMLElement.prototype.removeClass = HTMLElement.prototype.deleteClass;
HTMLElement.prototype.addClass = function(aClassName) {
var aClassExists=false;
var aClasses=this.className.split(' ');
for(var i = 0; i<aClasses.length; i++) {
if (aClasses[i] == aClassName) {
aClassExists = true;
}
}
if (!aClassExists)
this.className = aClassName+ ' ' + this.className;
return this;
};
HTMLElement.prototype.siblings = function() {
var buildChildrenList = function(aNode, aExceptionNode) {
var ret = [];
while (aNode) {
if ((aNode != aExceptionNode) && (aNode.nodeType==1)) {
ret.push(aNode);
}
aNode = aNode.nextSibling;
}
return ret;
};
return buildChildrenList(this.parentNode.firstChild, this);
};
if (!HTMLElement.prototype.getAttribute)
HTMLElement.prototype.getAttribute = function (attributeName) {
var ret='';
for(var i=0; i<this.attributes.length; i++)
if (this.attributes[i].name == attributeName)
ret = attributes[i].value;
return ret;
};
if (!HTMLElement.prototype.block)
HTMLElement.prototype.block = function () {
this.setAttribute('blocked','blocked');
return this;
};
if (!HTMLElement.prototype.unblock)
HTMLElement.prototype.unblock = function () {
this.removeAttribute('blocked');
return this;
};
if (!HTMLElement.prototype.isBlocked)
HTMLElement.prototype.isBlocked = function () {
var hasBlock = this.getAttribute('blocked');
return ( (typeof hasBlock == 'string') &&
(hasBlock.toLowerCase()=='blocked'));
};
if (!HTMLElement.prototype.lock)
HTMLElement.prototype.lock = function () {
if (!this.isBlocked())
this.readOnly = true;
return this;
};
if (!HTMLElement.prototype.unlock)
HTMLElement.prototype.unlock = function () {
if (!this.isBlocked())
this.readOnly = false;
return this;
};
}
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fun /*, thisArg */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function")
throw new TypeError();
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++)
{
if (i in t)
fun.call(thisArg, t[i], i, t);
}
};
}
/* Object extensions */
var mergeObject = function (srcObj, trgObj, overwriteIfExists) {
if (overwriteIfExists===undefined)
overwriteIfExists=false;
for (var i in srcObj)
if (srcObj.hasOwnProperty(i)) {
if ((undefined === trgObj[i]) || (overwriteIfExists))
trgObj[i] = srcObj[i];
}
};
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
if (!String.prototype.ucFirst) {
String.prototype.ucFirst=function()
{
return this.charAt(0).toUpperCase() + this.slice(1);
};
}
if (!String.prototype.lcFirst) {
String.prototype.lcFirst=function()
{
return this.charAt(0).toLowerCase() + this.slice(1);
};
}
if (!String.prototype.repeat) {
String.prototype.repeat= function(n, aChar){
n= n || 1;
aChar=aChar||this;
return Array(n+1).join(aChar);
};
}
/* returns a quoted string if it is not a number
* or a parsed float otherwise */
if (!String.prototype.quoteString) {
String.prototype.quoteString=function(emptyAsNull)
{
if (emptyAsNull===undefined)
emptyAsNull=false;
var aux=this.valueOf();
if (!isNumber(aux)) {
if ((emptyAsNull) && (aux===''))
aux = null;
else {
aux = this.replace(/\"/g, "\\\"");
aux = '"'+aux+'"';
}
} else
aux=parseFloat(aux);
return aux;
};
}
if (!String.prototype.quote) {
String.prototype.quote=function()
{
var aux = this.replace(/\"/g, "\\\"");
return '"'+aux+'"';
};
}
if (!String.prototype.unquote) {
String.prototype.unquote = function() {
var firstChar='', lastChar='';
if (this.length>1) {
firstChar = this.substr(0,1);
lastChar = this.substr(this.length-1,1);
if (firstChar == lastChar) {
if ((lastChar == '"') || (lastChar == "'"))
return this.substr(1,this.length-2);
} else if (((firstChar=='(') && (lastChar==')')) ||
((firstChar=='[') && (lastChar==']')) ||
((firstChar=='{') && (lastChar=='}'))) {
return this.substr(1,this.length-2);
} else
return this.toString()+'';
} else
return this.toString()+'';
};
}
if (!String.prototype.format) {
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined' ? args[number] : match
;
});
};
}
if (!String.prototype.isCPF) {
//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/string/is-cpf [rev. #1]
String.prototype.isCPF = function(){
var s, c = this;
if((c = c.replace(/[^\d]/g,"").split("")).length != 11) return false;
if(new RegExp("^" + c[0] + "{11}$").test(c.join(""))) return false;
for(s = 10, n = 0, i = 0; s >= 2; n += c[i++] * s--){}
if(c[9] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
for(s = 11, n = 0, i = 0; s >= 2; n += c[i++] * s--){}
if(c[10] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
return true;
};
}
if (!String.prototype.isEmail) {
String.prototype.isEmail = function() {
return isEmail(this);
};
}
if (!String.prototype.isCNPJ) {
//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/string/is-cnpj [rev. #1]
String.prototype.isCNPJ = function(){
var i, b = [6,5,4,3,2,9,8,7,6,5,4,3,2], c = this;
if((c = c.replace(/[^\d]/g,"").split("")).length != 14) return false;
for(i = 0, n = 0; i < 12; n += c[i] * b[++i]){}
if(c[12] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
for(i = 0, n = 0; i <= 12; n += c[i] * b[i++]){}
if(c[13] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
return true;
};
}
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
Function.method('inherits', function (Parent) {
this.prototype = new Parent( );
return this;
});
if (typeof Object.create !== 'function') {
Object.create = function (o) {
var F = function () {};
F.prototype = o;
return new F();
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(elt /*, from*/) {
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0) ?
Math.ceil(from) :
Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++) {
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
/* as the array keys could be used with data camming from
* interbase (UPPERCASE) postgresql (lowercase most of the time)
* or mysql (mixed case when configured properly), we need
* to let the programmer use which one he wants in the data model
* while keep the array untoched.
* Not only that, the field names on client side can be prefixed and/or
* postfixed, so we need to chose the more adequated
* So this function guess which one is the best */
var suggestKeyName = function (aObj, aKeyName, fieldPrefix, fieldPostfix) {
var ret = null;
if (aKeyName) {
var aColList;
if (!isArray(aObj))
aColList = aObj;
else {
aColList = {};
for(var a=0; a<aObj.length; a++) {
aColName=aObj[a];
aColList[aColName]=aColName;
}
}
var UKey = aKeyName.toUpperCase();
for(var i in aColList) {
if (aColList.hasOwnProperty(i))
if (i.toUpperCase()==UKey)
ret = i;
}
if (fieldPrefix || fieldPostfix) {
if (ret===null) {
fieldPrefix = fieldPrefix || '';
fieldPostfix = fieldPostfix || '';
if ((UKey.substr(0,fieldPrefix.length))==fieldPrefix.toUpperCase()) {
aKeyName=aKeyName.substr(fieldPrefix.length);
ret=suggestKeyName(aColList, aKeyName);
}
if (ret===null) {
if (UKey.substr(UKey.length - fieldPostfix.length) == fieldPostfix.toUpperCase()) {
aKeyName = aKeyName.substr(0, aKeyName.length - fieldPostfix.length);
ret=suggestKeyName(aColList, aKeyName);
}
}
}
}
}
return ret;
};
/* date extensions */
if (typeof Date.prototype.nextMonth == 'undefined')
Date.prototype.nextMonth = function () {
var thisMonth = this.getMonth();
this.setMonth(thisMonth+1);
if(this.getMonth() != thisMonth+1 && this.getMonth() !== 0)
this.setDate(0);
};
if (typeof Date.prototype.prevMonth == 'undefined')
Date.prototype.prevMonth = function () {
var thisMonth = this.getMonth();
this.setMonth(thisMonth-1);
if(this.getMonth() != thisMonth-1 && (this.getMonth() != 11 || (thisMonth == 11 && this.getDate() == 1)))
this.setDate(0);
};
if (typeof Date.prototype.incMonth == 'undefined')
Date.prototype.incMonth = function (aInc)
{
var thisMonth = this.getMonth();
this.setMonth(thisMonth + aInc);
if(this.getMonth() != thisMonth + aInc && (this.getMonth() != 11 || (thisMonth == 11 && this.getDate() == 1)))
this.setDate(0);
};
if (typeof Date.prototype.nextDay == 'undefined')
Date.prototype.nextDay = function () {
this.setTime(this.getTime() + 24 * 60 * 60 * 1000);
};
if (typeof Date.prototype.prevDay == 'undefined')
Date.prototype.prevDay = function () {
this.setTime(this.getTime() - 24 * 60 * 60 * 1000);
};
if (typeof Date.prototype.nextWeek == 'undefined')
Date.prototype.nextWeek = function () {
this.setTime(this.getTime() + 24 * 60 * 60 * 1000 * 7);
};
if (typeof Date.prototype.prevWeek == 'undefined')
Date.prototype.prevWeek = function () {
this.setTime(this.getTime() - 24 * 60 * 60 * 1000 * 7);
};
if (typeof Date.prototype.daysInMonth == 'undefined')
Date.prototype.daysInMonth = function(iMonth, iYear) {
if (!iYear)
iYear = this.getFullYear();
if (!iMonth)
iMonth = this.getMonth() + 1;
return 32 - new Date(parseInt(iYear), parseInt(iMonth)-1, 32).getDate();
};
/* french style is dd/mm/yyyy */
if (typeof Date.prototype.toFrenchString == 'undefined')
Date.prototype.toFrenchString = function () {
return '' + this.getDate() + '/' +
(this.getMonth()+1) + '/' +
this.getFullYear();
};
/* UDate is like ISO8601 but with no separations and without milliseconds */
if (typeof Date.prototype.toUDate == 'undefined')
Date.prototype.toUDate = function () {
return '' + pad(this.getFullYear(),4) +
pad(this.getMonth()+1, 2) +
pad(this.getDate(), 2) +
pad(this.getHours(), 2) +
pad(this.getMinutes(), 2) +
pad(this.getSeconds(), 2);
};
if (typeof Date.prototype.toISOString =='undefined' ) {
Date.prototype.toISOString = function() {
return this.getUTCFullYear() +
'-' + pad( this.getUTCMonth() + 1, 2) +
'-' + pad( this.getUTCDate(), 2) +
'T' + pad( this.getUTCHours(), 2 ) +
':' + pad( this.getUTCMinutes(), 2 ) +
':' + pad( this.getUTCSeconds(), 2 ) +
'.' + String( (this.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 ) +
'Z';
};
}
if (typeof Date.prototype.frenchFormat == 'undefined')
Date.prototype.frenchFormat = function () {
return this.getDate()+'/'+(this.getMonth()+1)+'/'+this.getFullYear();
};
/*
* aStrDate: string
* aFormat: string where 'y' means year, 'm' month, 'd' day,
* 'H' hour, 'M': minutes and 'S' seconds
*
* It can understand yyyy-mm-dd HH:MM:SS or yy/m/dd H:MM:SS from
* the same format string and diferent dates
*/
var extractDateValues = function (aStrDate, aFormat, aDateMap) {
var getDateSplitter = function(aStr) {
var splitter1 = (aStr.match(/\//g)||[]).length;
var splitter2 = (aStr.match(/\-/g)||[]).length;
return ((splitter1>splitter2)?'/':((splitter2>0)?'-':''));
};
var dateSplitter = getDateSplitter(aFormat);
var dateSplitterInUse = getDateSplitter(aStrDate);
var i, dtSequence = null;
if (dateSplitter>'') {
dtSequence = [];
var dtFormat = aFormat.split(dateSplitter);
for(i=0; i<dtFormat.length; i++)
dtSequence[dtFormat[i].substr(0,1)]=i;
var aux=aStrDate.split(dateSplitter);
while (aux.length<dtFormat.length) {
aStrDate=aStrDate+dateSplitter+'01';
aux[aux.length]=0;
}
}
var getElementValue = function (aElementTag) {
var p = aFormat.indexOf(aElementTag);
var l = 0;
if (p>=0) {
var elementValue;
while ((p+l<aFormat.length) && (aFormat.substr(p+l,1)==aElementTag))
l++;
if (((aElementTag.match(/[y,m,d]/g) || []).length>0) && (dtSequence!==null)) {
elementValue = aStrDate.split(dateSplitter)[dtSequence[aElementTag]].split(' ')[0];
} else
elementValue = str2int(aStrDate.substr(p,l));
return [ p, elementValue, aElementTag, l ];
} else
return [ null, null, aElementTag ];
};
var parseDate = function() {
return aStrDate.match(/\b[\d]+\b/g);
};
var getReturn = function(aDateArray) {
var ret = [ ];
for(var i=0; i<aDateArray.length; i++) {
var auxValue=aDateArray[i][1];
if (auxValue !== null) {
auxValue=auxValue.toString();
if (auxValue.length==1)
auxValue=pad(auxValue,2);
else if (auxValue.length==3)
auxValue=pad(auxValue,4);
}
ret[aDateArray[i][2]]=auxValue;
}
return ret;
};
var ret;
if (aFormat === undefined)
aFormat='yyyy-mm-dd hh:mm:ss';
if (aStrDate === '') {
ret=[];
ret['y']='';
ret['d']='';
ret['m']='';
ret['H']='';
ret['M']='';
ret['S']='';
return ret;
}
if (aDateMap === undefined)
aDateMap = {};
aDateMap.elems = [ getElementValue('y'),
getElementValue('m'),
getElementValue('d'),
getElementValue('H'),
getElementValue('M'),
getElementValue('S')
];
/* first we try with fixed position analisis
* we test the minimum approach: month/day */
if ( (dateSplitterInUse==dateSplitter) &&
(((aDateMap.elems[1][1]>0) && (aDateMap.elems[1][1]<13)) &&
((aDateMap.elems[2][1]>=1) && (aDateMap.elems[2][1]<=31)))) {
ret = getReturn(aDateMap.elems);
} else {
/* secondly we try with relative position analisis
* so we have in sortedInfo the field as it comes
* from the user */
var sortedInfo = aDateMap.elems;
sortedInfo.sort(function(a,b) {
if (a[0]===b[0])
return 0;
else if ((a[0]<b[0]) || (b[0]===null))
return -1;
else if ((a[0]>b[0]) || (a[0]===null))
return 1;
});
/* we extract the date elements */
var auxDateInfo = parseDate();
for(i=0; i<sortedInfo.length && i<auxDateInfo.length; i++)
sortedInfo[i][1] = auxDateInfo[i];
if (sortedInfo[0][1] * sortedInfo[1][1] * sortedInfo[2][1] > 0 )
ret = getReturn(sortedInfo);
else {
ret=null;
}
}
return ret;
};
var array2date = function(aDate) {
return pad(aDate['d'],2)+'-'+pad(aDate['m'],2)+'-'+aDate['y'];
};
/* hh:mm (string) -> minutes (integer) */
function time2minutes(aTime) {
if ((aTime===undefined) || (aTime=='NaN'))
aTime=0;
var h=0;
var m=0;
if (aTime>'') {
var p=aTime.indexOf('h');
if (p<0)
p=aTime.indexOf(':');
if (p>=0) {
h=aTime.substring(0,p);
m=parseInt(aTime.substring(p+1));
if (isNaN(m))
m=0;
} else {
h=0;
m=parseInt(aTime);
}
aTime=h*60+m;
}
if (aTime<0)
aTime=0;
return aTime;
}
/* minutes (integer) -> hh:mm (string) */
function minutes2time(aMinutes) {
var h=Math.floor(aMinutes / 60);
var m=pad(aMinutes % 60,2);
return h+':'+m;
}
/* unix timestamp to day of week (0=sunday) */
function timestamp2dayOfWeek(aTimestamp) {
var aux=new Date();
aux.setTime(aTimestamp*1000);
return aux.getDay();
}
function TimezoneDetect() {
/*
* http://www.michaelapproved.com/articles/timezone-detect-and-ignore-daylight-saving-time-dst/
*/
var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());
var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt
var intMonth;
var intHoursUtc;
var intHours;
var intDaysMultiplyBy;
//go through each month to find the lowest offset to account for DST
for (intMonth=0;intMonth < 12;intMonth++){
//go to the next month
dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);
//To ignore daylight saving time look for the lowest offset.
//Since, during DST, the clock moves forward, it'll be a bigger number.
if (intOffset > (dtDate.getTimezoneOffset() * (-1))){
intOffset = (dtDate.getTimezoneOffset() * (-1));
}
}
return intOffset;
}
/* unix timestamp -> dd/mm/yyyy */
function timestamp2date(aTimestamp) {
if ((!isNaN(aTimestamp)) && (aTimestamp>'')) {
var aux=new Date();
aux.setTime(aTimestamp*1000 + (-TimezoneDetect() - aux.getTimezoneOffset()) * 60 * 1000);
return pad(aux.getDate(),2)+'/'+pad(aux.getMonth()+1,2)+'/'+pad(aux.getFullYear(),4);
} else
return '';
}
/* unix timestamp -> hh:mm */
function timestamp2time(aTimestamp, seconds) {
var ret;
if (aTimestamp===undefined)
ret='';
else if ((aTimestamp==='') || (isNaN(aTimestamp)))
ret='';
else {
if (seconds===undefined)
seconds=false;
var aux=new Date();
aux.setTime(aTimestamp*1000);
ret=pad(aux.getHours(),2)+':'+pad(aux.getMinutes(),2);
if (seconds)
ret = ret+':'+pad(aux.getSeconds(),2);
}
return ret;
}
/* dd/mm/yyyy hh:mm:ss -> yyyymmddhhmmss */
function FDate2UDate(a) {
if (a.indexOf('/')>0)
a=a.split('/');
else
a=a.split('-');
var h=a[2];
h=h.split(' ');
a[2]=h[0];
h=h[1];
if (h===undefined)
h='00:00:00';
h=h.split(':');
if (h[1]===undefined)
h[1]=0;
if (h[2]===undefined)
h[2]=0;
return pad(a[2],4)+'-'+pad(a[1],2)+'-'+pad(a[0],2)+' '+pad(h[0],2)+':'+pad(h[1],2)+':'+pad(h[2],2);
}
/* ISO8601 -> javascript date object */
function UDate2JSDate(aUDate) {
var aDate=extractDateValues(aUDate,'yyyymmddHHMMSS');
var d=new Date();
d.setFullYear(aDate['y']);
d.setMonth(aDate['m']-1);
d.setDate(aDate['d']);
d.setHours(aDate['H']);
d.setMinutes(aDate['M']);
return d;
}
/* ISO8601 -> french date dd/mm/yyyy */
function UDate2Date(aUDate, aFormat) {
if (typeof aFormat==='undefined')
aFormat="d/m/y";
var ret='';
var aDate=extractDateValues(aUDate,'yyyymmddHHMMSS');
if (aDate)
ret='';
for(var i=0; i<aFormat.length; i++)
if (/^[d,m,y]+$/.test(aFormat[i]))
ret+=aDate[aFormat[i]];
else
ret+=aFormat[i];
return ret;
}
/* ISO8601 -> french time hh:mm:ss */
function UDate2Time(aUDate, aFormat) {
if (typeof aFormat==='undefined')
aFormat="H:M:S";
var ret='';
var aDate=extractDateValues(aUDate,'yyyymmddHHMMSS');
if (aDate) {
ret='';
for(var i=0; i<aFormat.length; i++)
if (/^[H,M,S]+$/.test(aFormat[i]))
ret+=aDate[aFormat[i]];
else
ret+=aFormat[i];
}
return ret;
}
/* interbase (english) date mmddyyyy -> french date dd-mm-yyyy */
function IBDate2Date(aIBDate) {
var ret='';
var aDate=extractDateValues(aIBDate,'mmddyyyyHHMMSS');
if (aDate)
ret = aDate['d']+'-'+aDate['m']+'-'+aDate['y'];
return ret;
}
// french date dd-mm-yyyy -> english date mm-dd-yyyy
function date2IBDate(aFDate) {
var ret='';
var aDate=extractDateValues(aFDate,'ddmmyyyyHHMMSS');
if (aDate)
ret = pad(aDate['m'],2)+'-'+pad(aDate['d'],2)+'-'+aDate['y'];
return ret;
}
// french date dd-mm-yyyy -> ISO8601 date yyyy-mm-dd
function date2UDate(aFDate) {
var ret='';
var aDate=extractDateValues(aFDate,'ddmmyyyyHHMMSS');
if (aDate)
ret = pad(aDate['y'],4)+'-'+pad(aDate['m'],2)+'-'+pad(aDate['d'],2);
return ret;
}
function IBDate2timestamp(a) {
a = IBDate2Date(a);
a = date2timestamp(a);
return a;
}
function timestamp2IBDate(a) {
a = timestamp2date(a);
a = date2IBDate(a);
return a;
}
var dateTransform = function (aStrDate, srcFormat, destFormat) {
if (aStrDate) {
var tmpDate = extractDateValues(aStrDate, srcFormat);
var auxMap={};
var emptyDate = extractDateValues("111111111111", destFormat, auxMap);
var ret=destFormat;
for(var i=0; i<auxMap.elems.length; i++) {
/* e is a shortcut to the array map */
var e = auxMap.elems[i];
if (e[0] !== null) {
/* pos 2 is the date index (y,m,d,H,M,S)
* pos 3 is the target length */
var value = pad(tmpDate[e[2]],e[3]);
/* pos 0 is the start of the date element
* we expect to have enough space in date return */
while (ret.length < e[0] + e[3])
ret = ret+' ';
ret=ret.substr(0,e[0]) + value + ret.substr(e[0]+e[3], ret.length);
}
}
return ret;
} else
return null;
};
/* discover type of things */
function isInfinity(aValue) {
if (aValue!==undefined)
return (aValue.POSITIVE_INFINITY || aValue.NEGATIVE_INFINITY || aValue=='Infinity');
else
return true;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var isArray = function (value) {
/* by Douglas Crockford */
return value &&
typeof value === 'object' &&
typeof value.length === 'number' &&
typeof value.splice === 'function' &&
!(value.propertyIsEnumerable('length'));
};
/* regexp functions */
function isEmail(email) {
var aux=(email && email.unquote()) || '';
var re = /^(([^\*<>()[\]\\.,;:\s@\"]+(\.[^\*<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(aux);
}
/* miscellaneous functions */
function pad(number, length) {
var str = '' + number;
while (str.length < length)
str = '0' + str;
return str;
}
function unmaskHTML(auxLine) {
if (typeof auxLine == 'string') {
if (auxLine.length>0) {
var c=auxLine.substr(0,1);
if ((c=='"') || (c=="'")) {
var z=auxLine.substr(auxLine.length-1);
if (c==z)
auxLine=auxLine.substr(1,auxLine.length-2);
}
}
while (auxLine.indexOf('!!')>=0)
auxLine = auxLine.replace('!!', '&');
auxLine = auxLine.replace(/\&\#91\;/g, '<');
auxLine = auxLine.replace(/\&\#93\;/g, '>');
auxLine = auxLine.replace(/\[/g, '<');
auxLine = auxLine.replace(/\]/g, '>');
} else if (typeof auxLine=='number') {
auxLine = auxLine.toString();
} else
auxLine = '';
return auxLine;
}
function escapeRegExp(string) {
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
function maskHTML(auxLine) {
auxLine = auxLine || '';
if (typeof auxLine == 'string') {
while (auxLine.indexOf('<')>=0)
auxLine = auxLine.replace(/\</,'[');
while (auxLine.indexOf('>')>=0)
auxLine = auxLine.replace(/\>/,']');
while (auxLine.indexOf('&')>=0)
auxLine = auxLine.replace('&','!!');
}
return auxLine;
}
function trim(str) {
return str.replace(/^\s+|\s+$/g,"");
}
function unparentesis(v) {
if (v.length>1) {
if ((v.substring(0,1)=='(') || (v.substring(0,1)=='[') || (v.substring(0,1)=='{'))
v=v.substring(1,v.length-1);
}
return (v);
}
function wordwrap( str, width, brk, cut ) {
brk = brk || '\n';
width = width || 75;
cut = cut || false;
if (!str) { return str; }
var regex = '.{1,' +width+ '}(\\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\\S+?(\\s|$)');
return str.match( RegExp(regex, 'g') ).join( brk );
}
function nl2br(aString) {
var ret='';
if (aString!==undefined) {
ret = aString.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '<br>' + '$2');
}
return ret;
}
function str2double(aStr) {
if (aStr === undefined)
aStr = '0';
var a="";
if ((aStr.indexOf(',')>0) && (aStr.indexOf('.')>0))
a=aStr.replace('.','');
else
a=aStr;
a=a.replace(',','.');
if (a==='')
a='0.00';
a=parseFloat(a);
if (isNaN(a))
a=0;
var ret = parseFloat(a).toFixed(2);
ret = parseFloat(ret);
return ret;
}
function str2int(value) {
var n = parseInt(value);
return n === null || isNaN(n) ? 0 : n;
}
function str2bool(aStr, aDefaultValue) {
if (aDefaultValue===undefined)
aDefaultValue = false;
if (aStr===undefined)
aStr = aDefaultValue;
else
aStr = aStr.toUpperCase()=='TRUE';
return aStr;
}
function bool2str(aBool) {
return aBool ? 'TRUE' : 'FALSE';
}
function dec2hex(d) {
return d.toString(16);
}
function hex2dec(h) {
return parseInt(h,16);
}
/*
* interface routines
* in version 0.9.0 will be moved to yinterface.js
*/
var rowColorSpecBase = function () {
that = { };
that.cfgColors = [ '#F2F0F0', '#CFCFCF'] ;
that.suggestRowColor=function (curRow) {
return this.cfgColors[(curRow % 2)];
};
that.setRowColors = function (c1, c2) {
this.cfgColors[0]=c1 || this.cfgColors[0];
this.cfgColors[1]=c2 || this.cfgColors[1];
};
return that;
};
var rowColorSpec = rowColorSpecBase();
function decomposeColor(color) {
if (color.substr(0,1)=='#')
color=color.substr(1);
var r=hex2dec(color.substr(0,2));
var g=hex2dec(color.substr(2,2));
var b=hex2dec(color.substr(4,2));
return [r, g, b];
}
function complementaryColor(color) {
var xDiv = 32;
var xLimite = 250;
var xDivContraste = 3;
var dc = decomposeColor(color);
for (var n=0; n<3; n++) {
dc[n] = Math.floor(dc[n] / xDivContraste);
dc[n] = Math.floor(dc[n] / xDiv) * xDiv;
if (xLimite>0)
dc[n] = xLimite - Math.min(xLimite, dc[n]);
}
var res=dec2hex(dc[0])+dec2hex(dc[1])+dec2hex(dc[2]);
return '#'+res;
}
function grayColor(color) {
var xDiv=32;
var dc = decomposeColor(color);
var r=Math.floor(dc[0] / xDiv) * xDiv;
var g=Math.floor(dc[1] / xDiv) * xDiv;
var b=Math.floor(dc[2] / xDiv) * xDiv;
var gray=(r+g+b) / 3;
gray=dec2hex(gray);
var res=gray+gray+gray;
return res;
}
/*
* The original source code was picked from
* http://www.openjs.com/scripts/xml_parser/
* without copyright notes.
*
* The job here was to package the function inside a functional
* object oriented model
*/
var xml2array = function (xmlDoc) {
var key;
var that = {};
that.not_whitespace = new RegExp(/[^\s]/);
that.parent_count=null;
//Process the xml data
that.xml2array = function(xmlDoc,parent_count) {
var arr, temp_arr, temp, parent = "";
parent_count = parent_count || {};
var attribute_inside = 0; /*:CONFIG: Value - 1 or 0
* If 1, Value and Attribute will be shown inside the tag - like this...
* For the XML string...
* <guid isPermaLink="true">http://www.bin-co.com/</guid>
* The resulting array will be...
* array['guid']['value'] = "http://www.bin-co.com/";
* array['guid']['attribute_isPermaLink'] = "true";
*
* If 0, the value will be inside the tag but the attribute will be outside - like this...
* For the same XML String the resulting array will be...
* array['guid'] = "http://www.bin-co.com/";
* array['attribute_guid_isPermaLink'] = "true";
*/
if(xmlDoc.nodeName && xmlDoc.nodeName.charAt(0) != "#") {
if(xmlDoc.childNodes.length > 1) { //If its a parent
arr = {};
parent = xmlDoc.nodeName;
}
}
var value = xmlDoc.nodeValue;
if(xmlDoc.parentNode && xmlDoc.parentNode.nodeName && value) {
if(that.not_whitespace.test(value)) {//If its a child
arr = {};
arr[xmlDoc.parentNode.nodeName] = value;
}
}
if(xmlDoc.childNodes.length) {
if(xmlDoc.childNodes.length == 1) { //Just one item in this tag.
arr = that.xml2array(xmlDoc.childNodes[0],parent_count); //:RECURSION:
} else { //If there is more than one childNodes, go thru them one by one and get their results.
if (!arr)
arr=[];
var index = 0;
for(var i=0; i<xmlDoc.childNodes.length; i++) {//Go thru all the child nodes.
temp = that.xml2array(xmlDoc.childNodes[i],parent_count); //:RECURSION:
if(temp) {
var assoc = false;
var arr_count = 0;
var lastKey = null;
for(key in temp) {
if (temp.hasOwnProperty(key)) {
lastKey = key;
if(isNaN(key)) assoc = true;
arr_count++;
if(arr_count>2) break;//We just need to know wether it is a single value array or not
}
}
if(assoc && arr_count == 1) {
if(arr[lastKey]) { //If another element exists with the same tag name before,
// put it in a numeric array.
//Find out how many time this parent made its appearance
if(!parent_count || !parent_count[lastKey]) {
parent_count[lastKey] = 0;
temp_arr = arr[lastKey];
arr[lastKey] = {};
arr[lastKey][0] = temp_arr;
}
parent_count[lastKey]++;
arr[lastKey][parent_count[lastKey]] = temp[lastKey]; //Members of of a numeric array
} else {
parent_count[lastKey] = 0;
arr[lastKey] = temp[lastKey];
if(xmlDoc.childNodes[i].attributes && xmlDoc.childNodes[i].attributes.length) {
for(var j=0; j<xmlDoc.childNodes[i].attributes.length; j++) {
var nname = xmlDoc.childNodes[i].attributes[j].nodeName;
if(nname) {
/* Value and Attribute inside the tag */
if(attribute_inside) {
temp_arr = arr[lastKey];
arr[lastKey] = {};
arr[lastKey]['value'] = temp_arr;
arr[lastKey]['attribute_'+nname] = xmlDoc.childNodes[i].attributes[j].nodeValue;
} else {
/* Value in the tag and Attribute otside the tag(in parent) */
arr['attribute_' + lastKey + '_' + nname] = xmlDoc.childNodes[i].attributes[j].value;
}
}
} //End of 'for(var j=0; j<xmlDoc. ...'
} //End of 'if(xmlDoc.childNodes[i] ...'
}
} else {
arr[index] = temp;
index++;
}
} //End of 'if(temp) {'
temp=undefined;
} //End of 'for(var i=0; i<xmlDoc. ...'
}
}
if(parent && arr) {
temp = arr;
arr = {};
arr[parent] = temp;
}
return arr;
};
return that.xml2array(xmlDoc);
};
/*====================================================================
* HASH routines
* http://phpjs.org/functions/
*====================================================================*/
var utf8_decode = function(str_data) {
// discuss at: http://phpjs.org/functions/utf8_decode/
// original by: Webtoolkit.info (http://www.webtoolkit.info/)
// input by: Aman Gupta
// input by: Brett Zamir (http://brett-zamir.me)
// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: Norman "zEh" Fuchs
// bugfixed by: hitwork
// bugfixed by: Onno Marsman
// bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// bugfixed by: kirilloid
// example 1: utf8_decode('Kevin van Zonneveld');
// returns 1: 'Kevin van Zonneveld'
var tmp_arr = [],
i = 0,
ac = 0,
c1 = 0,
c2 = 0,
c3 = 0,
c4 = 0;
str_data += '';
while (i < str_data.length) {
c1 = str_data.charCodeAt(i);
if (c1 <= 191) {
tmp_arr[ac++] = String.fromCharCode(c1);
i++;
} else if (c1 <= 223) {
c2 = str_data.charCodeAt(i + 1);
tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
i += 2;
} else if (c1 <= 239) {
// http://en.wikipedia.org/wiki/UTF-8#Codepage_layout
c2 = str_data.charCodeAt(i + 1);
c3 = str_data.charCodeAt(i + 2);
tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
} else {
c2 = str_data.charCodeAt(i + 1);
c3 = str_data.charCodeAt(i + 2);
c4 = str_data.charCodeAt(i + 3);
c1 = ((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63);
c1 -= 0x10000;
tmp_arr[ac++] = String.fromCharCode(0xD800 | ((c1 >> 10) & 0x3FF));
tmp_arr[ac++] = String.fromCharCode(0xDC00 | (c1 & 0x3FF));
i += 4;
}
}
return tmp_arr.join('');
};
var utf8_encode = function (argString) {
// discuss at: http://phpjs.org/functions/utf8_encode/
// original by: Webtoolkit.info (http://www.webtoolkit.info/)
// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: sowberry
// improved by: Jack
// improved by: Yves Sucaet
// improved by: kirilloid
// bugfixed by: Onno Marsman
// bugfixed by: Onno Marsman
// bugfixed by: Ulrich
// bugfixed by: Rafal Kukawski
// bugfixed by: kirilloid
// example 1: utf8_encode('Kevin van Zonneveld');
// returns 1: 'Kevin van Zonneveld'
if (argString === null || typeof argString === 'undefined') {
return '';
}
var string = (argString + ''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
var utftext = '',
start, end, stringl = 0;
start = end = 0;
stringl = string.length;
for (var n = 0; n < stringl; n++) {
var c1 = string.charCodeAt(n);
var enc = null;
if (c1 < 128) {
end++;
} else if (c1 > 127 && c1 < 2048) {
enc = String.fromCharCode(
(c1 >> 6) | 192, (c1 & 63) | 128
);
} else if ((c1 & 0xF800) != 0xD800) {
enc = String.fromCharCode(
(c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128
);
} else { // surrogate pairs
if ((c1 & 0xFC00) != 0xD800) {
throw new RangeError('Unmatched trail surrogate at ' + n);
}
var c2 = string.charCodeAt(++n);
if ((c2 & 0xFC00) != 0xDC00) {
throw new RangeError('Unmatched lead surrogate at ' + (n - 1));
}
c1 = ((c1 & 0x3FF) << 10) + (c2 & 0x3FF) + 0x10000;
enc = String.fromCharCode(
(c1 >> 18) | 240, ((c1 >> 12) & 63) | 128, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128
);
}
if (enc !== null) {
if (end > start) {
utftext += string.slice(start, end);
}
utftext += enc;
start = end = n + 1;
}
}
if (end > start) {
utftext += string.slice(start, stringl);
}
return utftext;
};
/*=====================================================================
* http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
*=====================================================================*/
var generateUUID = function () {
var d = new Date().getTime();
if(window.performance && typeof window.performance.now === "function"){
d += performance.now(); //use high-precision timer if available
}
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x3|0x8)).toString(16);
});
return uuid;
}
var md5=function (str) {
// discuss at: http://phpjs.org/functions/md5/
// original by: Webtoolkit.info (http://www.webtoolkit.info/)
// improved by: Michael White (http://getsprink.com)
// improved by: Jack
// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// input by: Brett Zamir (http://brett-zamir.me)
// bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// depends on: utf8_encode
// example 1: md5('Kevin van Zonneveld');
// returns 1: '6e658d4bfcb59cc13f96c14450ac40b9'
var xl;
var rotateLeft = function(lValue, iShiftBits) {
return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
};
var addUnsigned = function(lX, lY) {
var lX4, lY4, lX8, lY8, lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
if (lX4 & lY4) {
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
}
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
} else {
return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
}
} else {
return (lResult ^ lX8 ^ lY8);
}
};
var _F = function(x, y, z) {
return (x & y) | ((~x) & z);
};
var _G = function(x, y, z) {
return (x & z) | (y & (~z));
};
var _H = function(x, y, z) {
return (x ^ y ^ z);
};
var _I = function(x, y, z) {
return (y ^ (x | (~z)));
};
var _FF = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(_F(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var _GG = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(_G(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var _HH = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(_H(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var _II = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(_I(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var convertToWordArray = function(str) {
var lWordCount;
var lMessageLength = str.length;
var lNumberOfWords_temp1 = lMessageLength + 8;
var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;
var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
var lWordArray = new Array(lNumberOfWords - 1);
var lBytePosition = 0;
var lByteCount = 0;
while (lByteCount < lMessageLength) {
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (str.charCodeAt(lByteCount) << lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
return lWordArray;
};
var wordToHex = function(lValue) {
var wordToHexValue = '',
wordToHexValue_temp = '',
lByte, lCount;
for (lCount = 0; lCount <= 3; lCount++) {
lByte = (lValue >>> (lCount * 8)) & 255;
wordToHexValue_temp = '0' + lByte.toString(16);
wordToHexValue = wordToHexValue + wordToHexValue_temp.substr(wordToHexValue_temp.length - 2, 2);
}
return wordToHexValue;
};
var x = [],
k, AA, BB, CC, DD, a, b, c, d, S11 = 7,
S12 = 12,
S13 = 17,
S14 = 22,
S21 = 5,
S22 = 9,
S23 = 14,
S24 = 20,
S31 = 4,
S32 = 11,
S33 = 16,
S34 = 23,
S41 = 6,
S42 = 10,
S43 = 15,
S44 = 21;
str = this.utf8_encode(str);
x = convertToWordArray(str);
a = 0x67452301;
b = 0xEFCDAB89;
c = 0x98BADCFE;
d = 0x10325476;
xl = x.length;
for (k = 0; k < xl; k += 16) {
AA = a;
BB = b;
CC = c;
DD = d;
a = _FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
d = _FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
c = _FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
b = _FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
a = _FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
d = _FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
c = _FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
b = _FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
a = _FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
d = _FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
c = _FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
b = _FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
a = _FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
d = _FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
c = _FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
b = _FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
a = _GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
d = _GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
c = _GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
b = _GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
a = _GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
d = _GG(d, a, b, c, x[k + 10], S22, 0x2441453);
c = _GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
b = _GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
a = _GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
d = _GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
c = _GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
b = _GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
a = _GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
d = _GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
c = _GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
b = _GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
a = _HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
d = _HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
c = _HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
b = _HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
a = _HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
d = _HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
c = _HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
b = _HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
a = _HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
d = _HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
c = _HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
b = _HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
a = _HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
d = _HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
c = _HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
b = _HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
a = _II(a, b, c, d, x[k + 0], S41, 0xF4292244);
d = _II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
c = _II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
b = _II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
a = _II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
d = _II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
c = _II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
b = _II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
a = _II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
d = _II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
c = _II(c, d, a, b, x[k + 6], S43, 0xA3014314);
b = _II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
a = _II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
d = _II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
c = _II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
b = _II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
a = addUnsigned(a, AA);
b = addUnsigned(b, BB);
c = addUnsigned(c, CC);
d = addUnsigned(d, DD);
}
var temp = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d);
return temp.toLowerCase();
};
/*==================================================
* USER INTERFACE ROUTINES
*==================================================*/
if ((typeof window=='object') && (typeof _onLoadMethods == 'undefined')) {
var _onLoadMethods = [];
window.addOnLoadManager=function(aFunc)
{
var i=_onLoadMethods.length;
_onLoadMethods[i]=aFunc;
};
document.addEventListener(
"DOMContentLoaded",
function(event) {
if (mTabNav) mTabNav.init();
}
);
window.addEventListener("load", function() {
for(var i=0; i<_onLoadMethods.length; i++)
if (_onLoadMethods.hasOwnProperty(i))
if (_onLoadMethods[i]!==undefined)
_onLoadMethods[i]();
}, false);
var addEvent = function(elem, eventName, eventHandler) {
if (typeof elem == 'string') elem=y$(elem);
if ((elem === null) || (typeof elem === 'undefined')) return;
var i;
if (isArray(elem)) {
for(i=0; i<elem.length; i++)
addEvent(elem[i], eventName, eventHandler);
} else {
var eventList=eventName.split(" "), aEventName;
for(i=0; i<eventList.length; i++) {
aEventName=eventList[i];
if ( elem.addEventListener ) {
elem.addEventListener( aEventName, eventHandler, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + aEventName, eventHandler );
} else {
elem["on"+aEventName]=eventHandler;
}
}
}
};
}
/* END ymisc.js */
_dump("ymisc");
/* START yanalise.js */
/*********************************************
* First Version (C) 2014 - esteban daniel dortta - dortta@yahoo.com
**********************************************/
// ==== YeAPF - Javascript implementation
function yAnalise(aLine, aStack)
{
if (aLine!=undefined) {
aLine = unmaskHTML(aLine);
var yPattern = /%[+(\w)]|[]\(/gi;
var yFunctions = ',int,integer,intz,intn,decimal,ibdate,tsdate,tstime,date,time,words,image,nl2br,quoted,condLabel';
var p;
var aValue='';
while ((p = aLine.search(yPattern)) >=0 ) {
var p1 = aLine.slice(p).search(/\(/);
var c1 = aLine.slice(p + p1 + 1, p + p1 + 2);
if ((c1=='"') || (c1=="'")) {
var c2;
var p3 = p + p1 + 1 ;
do {
p3++;
c2 = aLine.slice(p3, p3 + 1);
} while ((c2!=c1) && (p3<aLine.length));
var p2 = p3 + aLine.slice(p3).search(/\)/) - p;
} else
var p2 = aLine.slice(p).search(/\)/);
var funcName = aLine.slice(p+1, p+p1);
var funcParams = aLine.slice(p + p1 + 1, p + p2);
var parametros = funcParams;
funcParams = funcParams.split(',');
for (var n=0; n<funcParams.length; n++)
funcParams[n] = yAnalise(funcParams[n], aStack);
aValue = undefined;
var fParamU = funcParams[0].toUpperCase();
var fParamN = funcParams[0];
if (aStack!=undefined) {
// can come a stack or a simple unidimensional array
if (aStack[0]==undefined) {
if (aStack[fParamU])
aValue = yAnalise(aStack[fParamU], aStack);
else
aValue = yAnalise(aStack[fParamN], aStack);
} else {
for(var sNdx=aStack.length -1 ; (sNdx>=0) && (aValue==undefined); sNdx--)
if (aStack[sNdx][fParamU] != undefined)
aValue = yAnalise(aStack[sNdx][fParamU], aStack);
else if (aStack[sNdx][fParamN] != undefined)
aValue = yAnalise(aStack[sNdx][fParamN], aStack);
}
} else {
if (eval('typeof '+fParamN)=='string')
aValue=eval(fParamN);
else
aValue=yAnalise(fParamN);
}
if (aValue==undefined)
aValue = '';
funcParams[0] = aValue;
switch (funcName)
{
case 'integer':
case 'int':
case 'intz':
case 'intn':
aValue = str2int(aValue);
if (aValue==0) {
if (funcName=='intz')
aValue='-';
else if (funcName=='intn')
aValue='';
}
break;
case 'decimal':
var aDecimals = Math.max(0,parseInt(funcParams[1]));
aValue = parseFloat(aValue);
aValue = aValue.toFixed(aDecimals);
break;
case 'ibdate':
aValue = IBDate2Date(aValue);
break;
case 'tsdate':
aValue = timestamp2date(aValue);
break;
case 'tstime':
aValue = timestamp2time(aValue);
break;
case 'date':
if (funcParams[1])
aValue = UDate2Date(aValue, funcParams[1]);
else
aValue = UDate2Date(aValue);
break;
case 'time':
if (funcParams[1])
aValue = UDate2Time(aValue, funcParams[1]);
else
aValue = UDate2Time(aValue);
break;
case 'nl2br':
aValue = aValue.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '<br>' + '$2');
break;
case 'words':
var auxValue = aValue.split(' ');
var aStart = Math.max(0,str2int(funcParams[1]));
var aCount = Math.max(auxValue.length - 1 ,str2int(funcParams[2]));
var aWrap = Math.max(0,str2int(funcParams[3]));
aValue='';
for (var n=aStart; n<aStart+aCount; n++) {
var tmpValue = onlyDefinedValue(auxValue[n]);
if (tmpValue>'')
aValue+=' '+tmpValue;
}
if (aWrap>0)
aValue = wordwrap(aValue, aWrap, '<br>', true);
break;
case 'quoted':
aValue = '"'+aValue+'"';
break;
case 'condLabel':
break;
default:
if (funcName>'') {
if (eval('typeof '+funcName) == 'function') {
var parametros='';
for (var n=0; n<funcParams.length; n++) {
if (parametros>'')
parametros += ','
parametros += "'"+funcParams[n]+"'";
}
var chamada = '<script>'+funcName+'('+parametros+');</'+'script>';
aValue = chamada.evalScripts();
}
}
break;
}
aLine = aLine.slice(0,p) + aValue + aLine.slice(p + p2 + 1);
}
} else
aLine='';
return aLine;
}
/* END yanalise.js */
_dump("yanalise");
/* START ycfgdb.js */
/*********************************************
* First Version (C) 2014 - esteban daniel dortta - dortta@yahoo.com
**********************************************/
var cfgDBbase = function () {
that = {};
that.getConnParams = function () {
var ret = [];
ret['server'] = ystorage.getItem('server');
ret['user'] = ystorage.getItem('user');
ret['password'] = ystorage.getItem('password');
ret['token'] = ystorage.getItem('token');
return ret;
}
that.setConnParams = function (aParams) {
ystorage.setItem('server' , aParams['server']);
ystorage.setItem('user' , aParams['user']);
ystorage.setItem('password', aParams['password']);
ystorage.setItem('token' , aParams['token']);
}
return that;
}
var cfgDB = cfgDBbase();
/* END ycfgdb.js */
_dump("ycfgdb");
/* START ydragdrop.js */
/********************************************************************
*
* Drag and Drop functions were modified from luke beuer ideas at
* http://luke.breuer.com/tutorial/javascript-drag-and-drop-tutorial.aspx
* Available cursors can be catched here:
* http://help.dottoro.com/ljbknbcd.php
********************************************************************/
var ydragdropBase = function() {
var that = { };
that.info = {
startX: 0,
startY: 0,
offsetX: 0,
offsetY: 0,
dragElement: null,
overElement: null,
oldZIndex: 0,
lastHighLight: null
};
that.highlight = function(e) {
if (that.info.lastHighLight!=null)
that.info.lastHighLight.deleteClass('highlight');
that.info.lastHighLight = e;
if (e) {
that.info.lastHighLight.addClass('highlight');
}
}
that.getTarget = function (e) {
if (!e)
var e = window.event;
// IE uses srcElement, others use target
if (e.target) return e.target;
else if (e.srcElement) return e.srcElement
else return window.event;
}
that.onMouseDown = function(e) {
// IE is retarded and doesn't pass the event object
if (e == null)
e = window.event;
var target = that.getTarget(e);
if (target.className == 'caption')
target = target.parentNode;
if (target.className == 'title')
target = target.parentNode;
/*
* _dumpy(2,1,target.getAttribute('draggable') == 'yes' ? 'draggable element clicked' : 'NON-draggable element clicked');
*/
// for IE, left click == 1
// for Firefox, left click == 0
if ((e.button == 1 && window.event != null || e.button == 0) && target.getAttribute('draggable') == 'yes') {
document.body.style.cursor = "move";
// grab the mouse position
that.info.startX = e.clientX;
that.info.startY = e.clientY;
// grab the clicked element's position
that.info.offsetX = str2int(target.style.left);
that.info.offsetY = str2int(target.style.top);
// bring the clicked element to the front while it is being dragged
that.info.oldZIndex = target.style.zIndex;
var maxZ = 0;
var divList = document.getElementsByTagName('div');
for (var i = 0; i < divList.length; i++) {
var aDiv = divList[i];
if ((aDiv.getAttribute('draggable') == 'yes') && (aDiv != target)) {
if (parseInt(aDiv.style.zIndex) > maxZ)
maxZ = parseInt(aDiv.style.zIndex);
}
}
for (var i = 0; i < divList.length; i++) {
var aDiv = divList[i];
if (aDiv.getAttribute('draggable') == 'yes')
aDiv.style.zIndex = parseInt(aDiv.style.zIndex) - 1;
}
target.style.zIndex = maxZ + 2;
// we need to access the element in OnMouseMove
that.info.dragElement = target;
// cancel out any text selections
document.body.focus();
// prevent text selection in IE
document.onselectstart = function () {
return false;
};
// prevent IE from trying to drag an image
target.ondragstart = function () {
return false;
};
// prevent text selection (except IE)
return false;
}
};
that.onMouseMove = function(e) {
if (!e)
var e = window.event;
var x = e.clientX,
y = e.clientY,
overElement = document.elementFromPoint(x, y);
if (e == null)
var e = window.event;
if (that.info.dragElement != null) {
that.info.overElement = overElement;
// this is the actual "drag code"
that.info.dragElement.style.left = (that.info.offsetX + x - that.info.startX) + 'px';
that.info.dragElement.style.top = (that.info.offsetY + y - that.info.startY) + 'px';
/*
* _dumpy(2,1,'(' + that.info.dragElement.style.left + ', ' + that.info.dragElement.style.top + that.info.dragElement.style.zIndex + ')');
*/
var canDo = true;
if (overElement) {
canDo = overElement.getAttribute('droppable')=='yes';
if (typeof overElement.ondragover == 'function') {
canDo = overElement.ondragover(that.info.dragElement);
}
if (canDo)
that.highlight(overElement);
else
that.highlight(null);
}
if (canDo)
document.body.style.cursor = "crosshair";
else
document.body.style.cursor = "move";
} else {
if (overElement) {
if (document.body) {
if (overElement.getAttribute('draggable') == 'yes') {
document.body.style.cursor = "pointer";
} else
document.body.style.cursor = "default";
}
}
}
}
that.onMouseUp = function(e) {
if (!e)
var e = window.event;
if (that.info.dragElement != null) {
document.body.style.cursor = "default";
that.info.dragElement.style.zIndex = parseInt(that.info.dragElement.style.zIndex)-1;
// we're done with these events until the next OnMouseDown
document.onselectstart = null;
that.info.dragElement.ondragstart = null;
that.highlight(null);
var aux = that.info.dragElement;
// this is how we know we're not dragging
that.info.dragElement = null;
_dumpy(2,1,'mouse up over'+that.info.overElement.id);
var canDo = that.info.overElement.getAttribute('droppable') == 'yes';
if (canDo) {
if (typeof that.info.overElement.ondragover == 'function') {
canDo = that.info.overElement.ondragover(aux);
}
if (typeof that.info.overElement.ondrop == 'function') {
if (canDo)
that.info.overElement.ondrop(aux);
}
}
}
};
if (typeof document=='object') {
document.onmousedown = that.onMouseDown;
document.onmouseup = that.onMouseUp;
document.onmousemove = that.onMouseMove;
}
return that;
}
var ydragdrop = ydragdropBase();
/* END ydragdrop.js */
_dump("ydragdrop");
/* START ytabnav.js */
/*********************************************
* First Version (C) 2012 - esteban daniel dortta - dortta@yahoo.com
* Purpose: to control multiple tabs in a only-one-page application
* this is specially useful when building web mobile applications
**********************************************/
var tabNavBase = function () {
var that = {};
if (isOnMobile()) {
var tabchangeEvent = document.createEvent('Events');
tabchangeEvent.initEvent('tabchange');
var tabblurEvent = document.createEvent('Events');
tabblurEvent.initEvent('tabblur');
var tabfocusEvent = document.createEvent('Events');
tabfocusEvent.initEvent('tabfocus');
} else {
if (typeof Event=='function') {
var tabchangeEvent = new Event('tabchange');
var tabblurEvent = new Event('tabblur');
var tabfocusEvent = new Event('tabfocus');
}
}
that.currentTabNdx = -1;
that.currentContainerNdx = -1;
that.containerList = [];
that.tabList = [];
that.storage = null;
that.initialized = -1;
that.lock = {
returnTabId: null,
locked: false
};
that.isContainer = function (aDiv) {
var ret = false;
if (aDiv) {
ret = aDiv.hasClass('tnContainer');
}
return ret;
};
that.isTab = function (aDiv) {
var ret = false;
if (aDiv) {
ret = aDiv.hasClass('tnTab');
}
return ret;
};
that.getContainer = function (aContainerNdx) {
return that.containerList[aContainerNdx];
}
that.getCurrentContainer = function () {
return that.getContainer(that.currentContainerNdx);
}
that.getContainerById = function (aContainerId) {
var ret=null;
for(var i=0; i < that.containerList.length; i++) {
if (that.containerList[i].element.id==aContainerId)
ret = that.containerList[i];
}
return ret;
}
that.getTabContainer = function (aTabId) {
var ret=null;
if (aTabId) {
for(var i=0; (i < that.containerList.length) && (ret==null); i++) {
for(var n=0; (n < that.containerList[i].childs.length) && (ret==null); n++) {
if (typeof aTabId=='string') {
if (that.containerList[i].childs[n].id == aTabId) {
ret = that.containerList[i];
}
} else {
if (that.containerList[i].childs[n] == aTabId) {
ret = that.containerList[i];
}
}
}
}
}
return ret;
}
that.getFirstTabInContainer = function(aContainer) {
var ret=null, myContainer;
if (typeof aContainer == 'string')
aContainer=y$(aContainer);
if (that.isTab(aContainer))
myContainer=that.getTabContainer(aContainer);
else {
var containerNdx=that.getContainerNdx(aContainer);
if (containerNdx>=0)
myContainer=that.containerList[containerNdx];
}
if (myContainer)
ret=myContainer.childs[0];
return ret;
}
that.getFirstChildTab = function(aTab) {
var ret=null, myContainer;
if (typeof aTab == 'string')
aTab=y$(aTab);
if (that.isTab(aTab)) {
var aContainerList=aTab.getElementsByClassName('tnContainer');
if (aContainerList.hasOwnProperty('0')) {
var containerNdx=that.getContainerNdx(aContainerList[0]);
if (containerNdx>=0)
ret=that.containerList[containerNdx].childs[0];
} else
ret=aTab;
}
return ret;
}
that.getContainerFromParam = function (aContainer, aTabId) {
if (aContainer==undefined) {
if (aTabId==undefined)
aContainer = that.getCurrentContainer();
else
aContainer = that.getTabContainer(aTabId);
} else if (typeof aContainer == 'string') {
aContainer = that.getContainerById(aContainer);
} else if (isNumber(aContainer)) {
aContainer = that.getContainer(aContainer);
} else if (typeof aContainer != 'object') {
_dump("getContainerFromParam() parameter is not null, valid string, object nor a number");
aContainer = null;
}
return aContainer;
}
that.getCurrentTabNdx = function(aContainer) {
var ret = -1;
aContainer = that.getContainerFromParam(aContainer);
if (aContainer) {
ret = aContainer.currentTabNdx;
}
return ret;
}
that.setCurrentContainer = function (aNewContainerNdx) {
if (that.initialized < 0)
that.init();
that.currentContainerNdx = aNewContainerNdx % that.containerList.length;
}
that.getContainerNdx = function (aTab) {
var ret=-1;
for (var i=0; i<that.containerList.length; i++) {
if (that.containerList[i].element==aTab)
ret=i;
}
return ret;
}
that.addContainer = function (aTab) {
if (that.initialized < 0)
that.init();
if (aTab) {
if (that.getContainerNdx(aTab)<0) {
that.currentContainerNdx = that.containerList.length;
that.containerList[that.currentContainerNdx] = {
childs: [],
element: aTab,
currentTabNdx: -1
}
var auxTabList=aTab.getElementsByClassName('tnTab');
for(var i in auxTabList)
if (auxTabList.hasOwnProperty(i)) {
if (typeof auxTabList[i]=='object') {
var l=that.containerList[that.currentContainerNdx].childs.length;
that.containerList[that.currentContainerNdx].childs[l]=auxTabList[i];
}
}
}
}
};
that.addTab = function (aTab) {
if (that.initialized < 0)
that.init();
if (aTab) {
var aux = that.getCurrentContainer().childs;
if (aux.indexOf(aTab)<0)
aux[aux.length] = aTab;
}
};
that.init = function (aDivContainer) {
if (that.initialized < 0) {
that.initialized = 0;
var allContainers = y$('.tnContainer'),
firstTab = null, aDiv = null,
i = 0;
if (allContainers) {
for (i=0; i<allContainers.length; i++) {
aDiv=allContainers[i];
that.addContainer(aDiv);
}
}
var allTabs = y$('.tnTab');
if (allTabs) {
for(var i=0; i<allTabs.length; i++)
that.hideTab(allTabs[i]);
}
if (that.containerList.length>0) {
firstTab=that.containerList[0].childs[0];
that.displayTab(that.getFirstChildTab(firstTab));
}
that.currentContainerNdx = 0;
that.initialized = 1;
}
if (ycomm)
ycomm.setWaitIconControl(that.waitIconControl);
return that;
};
that.currentTab = function (aDiv) {
var theContainer = that.getCurrentContainer();
if (theContainer.currentTabNdx>-1) {
return theContainer.childs[theContainer.currentTabNdx];
} else
return null;
};
that.createTab = function (aDivContainer, aNewTabId) {
var aDiv = null;
if (y$(aNewTabId)==undefined) {
aDiv = document.createElement('div');
aDiv.className='tnTab';
aDiv.style.display='none';
aDiv.id=aNewTabId;
aDivContainer.appendChild(aDiv);
/* criar sob containerList */
that.addTab(aDiv);
that.hideTab(aDiv);
}
return aDiv;
}
that.delTab = function (aTab) {
};
that.displayTab = function (aTab, aContainer) {
if (!that.changingView) {
that.changingView=true;
try {
if (!that.locked()) {
if (aTab) {
if (that.initialized < 0)
that.init();
_dumpy(64,1,"displayTab "+aTab.id);
var canChange = true,
i = 0;
canChange = aTab.dispatchEvent(tabchangeEvent) || canChange;
/*
if (that.ontabchange != undefined)
canChange = that.ontabchange(aTab);
*/
if (canChange) {
var theContainer = that.getContainerFromParam(aContainer);
if (theContainer) {
_dumpy(64,1,"canchange");
var aNdx = -1;
var freeze = false;
for(i = 0; i < theContainer.childs.length; i++) {
if (theContainer.childs[i] != aTab)
freeze |= !(that.hideTab(theContainer.childs[i], aTab, theContainer));
else
aNdx = i;
}
_dumpy(64,1,"readytochange "+!freeze);
if (!freeze) {
that.setCurrentContainer(that.getContainerNdx(theContainer));
theContainer.currentTabNdx = aNdx;
aTab.dispatchEvent(tabfocusEvent);
/*
if (that.ontabfocus != undefined)
that.ontabfocus(aTab);
*/
aTab.style.display = 'block';
var auxNode=aTab;
while ((auxNode) && (auxNode!=document.body)) {
auxNode.style.display = 'block';
auxNode=auxNode.parentNode;
}
var elems=aTab.getElementsByTagName('*');;
i=0;
while (i<elems.length) {
if ((elems[i].type=='checkbox') || (elems[i].type=='radio') || (elems[i].type=='password') || (elems[i].type=='hidden') || (elems[i].type=='text') || (elems[i].type=='select-one') || (elems[i].type=='textarea')) {
elems[i].focus();
break;
}
i++;
}
} else {
_dumpy(64,1,"freeze");
}
}
}
_dumpy(64,1,"return");
}
}
} finally {
that.changingView=false;
}
}
};
that.showWaitIcon = function () {
if (y$('waitIcon')) {
y$('waitIcon').style.display='block';
}
};
that.hideWaitIcon = function () {
if (y$('waitIcon')) {
y$('waitIcon').style.display='none';
}
};
that.waitIconControl = function (display) {
if (display!=undefined) {
if (display)
that.showWaitIcon();
else
that.hideWaitIcon();
}
}
that.isInnerTab = function(aTabToBeShowed, aCurrentTab) {
var ret = false;
if (aTabToBeShowed) {
var aTab = aTabToBeShowed;
while ( (aTab) && (aTab.parent != aTab) ) {
if (aCurrentTab == aTab)
ret = true;
aTab = aTab.parentNode;
}
}
return ret;
}
that.hideTab = function (aTab, aTabToBeShowed, aContainer) {
if (!that.locked()) {
_dumpy(64,1,"hideTab "+aTab.id);
var ret = true;
var theContainer = that.getContainerFromParam(aContainer);
if (theContainer) {
if (theContainer.childs.indexOf(aTab) == theContainer.currentTabNdx) {
ret = aTab.dispatchEvent(tabblurEvent) || ret;
/*
if (that.ontabblur != undefined)
ret = that.ontabblur(aTab, aTabToBeShowed);
*/
if (ret)
theContainer.currentTabNdx = -1;
} else
ret = true;
}
if (ret) {
if (typeof aTab=='object')
if (!that.isInnerTab(aTabToBeShowed, aTab))
aTab.style.display = 'none';
}
return ret;
}
};
that.showNext = function (aContainer) {
aContainer = that.getContainerFromParam(aContainer);
if (aContainer) {
var currentTabNdx = aContainer.currentTabNdx;
if (currentTabNdx<aContainer.childs.length-1)
that.displayTab(aContainer.childs[currentTabNdx+1], aContainer);
else
that.displayTab(aContainer.childs[0], aContainer);
}
};
that.showPrior = function (aContainer) {
aContainer = that.getContainerFromParam(aContainer);
if (aContainer) {
var currentTabNdx = aContainer.currentTabNdx;
if (currentTabNdx>0)
that.displayTab(aContainer.childs[currentTabNdx-1], aContainer);
else
that.displayTab(aContainer.childs[aContainer.childs.length-1], aContainer);
}
};
that.getCurrentTabId = function (aContainer) {
var ret = null;
aContainer = that.getContainerFromParam(aContainer);
if (aContainer) {
var currentTabNdx = aContainer.currentTabNdx;
if (currentTabNdx>-1)
ret = aContainer.childs[currentTabNdx].id;
}
return ret;
}
that.showTab = function (aTabId, aLockTabAfterShow, aContainer) {
if (!that.locked()) {
var theContainer = that.getContainerFromParam(aContainer, aTabId);
if (aTabId == undefined) {
aTabId = theContainer.childs[0].id;
}
if (aLockTabAfterShow==undefined)
aLockTabAfterShow=false;
var aTab = document.getElementById(aTabId);
var priorTabId = '';
if (aTab) {
if (aLockTabAfterShow) {
priorTabId = that.getCurrentTabId(theContainer);
}
that.displayTab(aTab, theContainer);
if (aLockTabAfterShow)
that.lockTab(aTabId, priorTabId);
} else
alert(aTabId+" not found");
}
};
that.locked = function () {
return that.lock.locked;
}
that.releaseLockedTabs = function () {
for(var i=0; i<that.getCurrentContainer().childs.length; i++) {
if (that.getCurrentContainer().childs[i].locked)
that.getCurrentContainer().childs[i].locked=false;
}
that.lock.locked=false;
that.lock.returnTabId=null;
}
that.lockTab = function (aTabId, aReturnTabId) {
if (that.locked())
that.releaseLockedTabs();
if (y$(aTabId)) {
that.lock.locked = true;
y$(aTabId).locked = true;
that.lock.returnTabId = y$(aReturnTabId)?aReturnTabId:null;
}
}
that.unlockTab = function (aTabId) {
if (that.locked()) {
if (y$(aTabId)) {
if (y$(aTabId).locked) {
var nextTabId = that.lock.returnTabId;
that.releaseLockedTabs();
if (nextTabId!=null)
that.showTab(nextTabId);
}
}
}
}
return that;
}
var mTabNav = tabNavBase();
/* END ytabnav.js */
_dump("ytabnav");
/* START ycomm.js */
/*********************************************
* First Version (C) 2010 - esteban daniel dortta - dortta@yahoo.com
**********************************************/
function processError(xError)
{
var errNo=xError.errNo;
var errMsg=xError.errMsg;
var errDetail=xError.errDetail;
if (typeof errDetail != 'string') {
var d1=array2text(errDetail['sys.stack'],false);
if (d1 !== undefined)
d1='\n==[stack]===================================\n'+d1;
var d2=errDetail['sys.sqlTrace'];
if (d2 !== undefined)
d2='\n==[sql]===================================\n'+d2;
var d3=errDetail['sys.sqlError'];
errDetail=d3+d2+d1;
}
return 'Err #'+errNo+'\n-------- '+errMsg+'\n-------- '+errDetail;
}
var ycommBase = function () {
var that = {};
/*http://www.blooberry.com/indexdot/html/topics/urlencoding.htm*/
that.urlCodification = {
'%20' : ' ',
'%21' : '!',
'%2A' : '*',
'%27' : "'",
'%28' : '(',
'%29' : ')',
'%3B' : ';',
'%3A' : ':',
'%40' : '@',
'%26' : '&',
'%3D' : '=',
'%2B' : '+',
'%24' : '$',
/* '%25' : '%', cannot be at list as it corrupts the process */
'%2C' : ',',
'%2F' : '/',
'%3F' : '?',
'%23' : '#',
'%5B' : '[' ,
'%5D' : ']' };
that._AsyncMode=true;
that._dummyWaitIconControl = function () {};
// sets async mode. defaults to true
that.setAsyncMode = function (aAsyncMode) {
if (aAsyncMode === undefined)
aAsyncMode=true;
_AsyncMode=aAsyncMode;
};
that.xq_urlEncode = function(aURL, aQuoted) {
if (typeof aQuoted=='undefined')
aQuoted=true;
if ((typeof aURL=='string') && (aURL>'')) {
/* '%' need to be changed first */
aURL=aURL.replace(/%/g,'%25');
/* ',' must be escaped */
aURL=aURL.replace(/,/g,'\\,');
for(var n in that.urlCodification)
if (that.urlCodification.hasOwnProperty(n)) {
var re = new RegExp(escapeRegExp(that.urlCodification[n]), 'g');
aURL = aURL.replace(re, n);
}
if (!((aURL.substring(0,1)=="'") || (aURL.substring(0,1)=='"')))
if (!isNumber(aURL))
if (aQuoted)
aURL='"'+aURL+'"';
}
return aURL;
};
that.urlJsonAsParams = function(jsonParams) {
var fieldName='';
var fieldValue='';
var auxFieldValue='';
for(var jNdx in jsonParams) {
if (jsonParams.hasOwnProperty(jNdx)) {
if (fieldName>'') {
fieldName+=',';
fieldValue+=',';
}
fieldName += jNdx;
auxFieldValue = maskHTML(that.xq_urlEncode(jsonParams[jNdx], false));
fieldValue += auxFieldValue;
}
}
fieldName='('+fieldName+')';
fieldValue='('+fieldValue+')';
return [fieldName, fieldValue];
};
that.buildCommonURL = function (s, a, jsonParams, u) {
if (typeof jsonParams == 'undefined')
jsonParams = {};
var jsonAsParams=that.urlJsonAsParams(jsonParams);
var fieldName=jsonAsParams[0];
var fieldValue=jsonAsParams[1];
if (u===undefined)
u='';
var aURL="s={0}&a={1}&u={2}&fieldName={3}&fieldValue={4}".format(s, a, u || '', fieldName, fieldValue);
var ts=new Date();
aURL+='&ts='+ts.getTime();
// aURL=aURL.replace('%','%25');
return aURL;
};
that.setWaitIconControl = function (aFunction) {
that.waitIconControl = aFunction || that._dummyWaitIconControl;
};
that.pinger = {
canPing: false,
pingerWatchdog: null,
pingCount: 0,
pingTimeout: 5 * 1000,
pingInterleave: 1500,
onSuccess: null,
onError: null,
pong : function(aStatus, aError, aData) {
if (that.pinger.pingerWatchdog) clearTimeout(that.pinger.pingerWatchdog);
_dumpy(4,1,"pong answer");
if (that.pinger.pingCount<=aData.pingCount) {
that.pinger.pingCount=0;
// sayStatusBar("Servidor ativo");
if (that.pinger.onSuccess !== null)
that.pinger.onSuccess();
}
if (that.pinger.canPing)
that.pinger.pingerWatchdog = setTimeout(that.pinger.ping, that.pinger.pingInterleave);
},
/*
* após um tempo de 60 segundos (pingTimeout)
* sem resposta, ele cai nesta função e
* volta a tentar em 1/2 pingInterleave
*/
notAnswer: function () {
if (that.pinger.pingerWatchdog) clearTimeout(that.pinger.pingerWatchdog);
_dumpy(4,1,"Not pong answer");
if (that.pinger.onError !== null)
that.pinger.onError();
else
_dumpy(4,1,"Not 'onError' event");
// sayStatusBar("Servidor não localizado "+that.pinger.pingCount+'...<br>Tentando novamente');
if (that.pinger.canPing)
that.pinger.pingerWatchdog=setTimeout(that.pinger.ping, that.pinger.pingInterleave / 2);
},
/*
* tenta localizar o servidor. manda um numero.
* ele retorna o mesmo numero mais um timestamp
*/
ping: function (aOnSuccess, aOnError) {
if (that.pinger.pingerWatchdog) clearTimeout(that.pinger.pingerWatchdog);
_dumpy(4,1,"Prepare to ping");
that.pinger.canPing = true;
that.pinger.onSuccess = aOnSuccess || that.pinger.onSuccess;
that.pinger.onError = aOnError || that.pinger.onError;
that.pinger.pingCount++;
ycomm.crave('yeapf','ping',{ "pingCount": that.pinger.pingCount },'ycomm.pinger.pong');
that.pinger.pingerWatchdog=setTimeout(that.pinger.notAnswer, that.pinger.pingTimeout);
},
stopPing: function () {
if (that.pinger.pingerWatchdog) clearTimeout(that.pinger.pingerWatchdog);
_dumpy(4,1,"stop pinging");
that.pinger.canPing = false;
}
};
that.setWaitIconControl();
return that;
};
var ycomm = ycommBase();
/* END ycomm.js */
_dump("ycomm");
/* START ycomm-ajax.js */
/********************************************************************
*
* Com o advento do WebSocket, precisamos de novas formas para
* provocar o servidor.
* Este primeiro passo pretende melhorar o Ajax
* Depois, virão funções genericas
* Caso esteja usando prototype, ele usará o mesmo, se não se virará
* para criar uma interface
*
* verificar ServerSentEvents
* 2013-08-31
* https://developer.mozilla.org/en-US/docs/Server-sent_events/Using_server-sent_events
*
* requires ycomm.js to be loaded
* the callback function will recive: (status, xError, xData, xUserMsg, xDataContext, xGeometry)
********************************************************************/
if (typeof xAjax=='undefined') {
console.log("Using own xAjax() implementation");
/*
* 1) implementar um xAjax simples
* 2) depois deixar de depender do prototype (107K)
*/
var xAjax = function() {
var that = {};
if (typeof XMLHttpRequest !== 'undefined') {// code for IE7+, Firefox, Chrome, Opera, Safari
that.xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
that.xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
that.Request=function (script, options) {
// recognized options:
// method, asynchronous, parameters, onComplete
that.xmlhttp.onreadystatechange = function() {
if (that.xmlhttp.readyState>0) {
if (typeof options.onProgress != 'undefined') {
options.onProgress(that.xmlhttp);
}
}
if (that.xmlhttp.readyState==4) {
if (typeof options.onComplete != 'undefined') {
options.onComplete(that.xmlhttp);
}
}
};
that.xmlhttp.ontimeout = function() {
};
if (yloader.isWorker) {
options.asynchronous = false;
} else {
if (options.multipart)
options.asynchronous = true;
}
if ((options.method || 'POST').toUpperCase()=='POST') {
that.xmlhttp.open((options.method || 'POST'), script, options.asynchronous);
that.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
that.xmlhttp.send(options.parameters);
} else {
var sep;
if (script.indexOf('?')!==-1)
sep='&';
else
sep='?';
that.xmlhttp.open(options.method, script+sep+options.parameters, options.asynchronous);
that.xmlhttp.send();
}
};
return that;
};
}
ycomm.scriptName = yloader.isWorker?'../query.php':'query.php';
ycomm.defaultMethod = 'post';
ycomm.canReceiveMessages = true;
/* receive the xml envelope and split it in parts in order
* to feed ycomm-dom functions */
ycomm.explodeData = function(xmlDoc) {
var xmlArray = xml2array(xmlDoc);
var xCallBackFunction,
xData,
xRoot = xmlArray['root'] || {},
xDataContext = xRoot['dataContext'] || {},
xError = xRoot['error'] ||
xDataContext['error'] ||
xDataContext['lastError'],
xCallBackFunction = xmlArray['root']['callBackFunction'],
xGeometry = null,
xUserMsg = xDataContext['userMsg'],
xSysMsg = xDataContext['sysMsg'];
/* sysMsg has higher priority, so it is processed prior to user application
*
* sysMsg.msg = ( logoff, alert )
*
* 'logoff' message block all sucessive requests and redirect main URL to 'body.php?s=yeapf&a=logoff'
*/
if (xSysMsg) {
if (xSysMsg.msg) {
if (xSysMsg.msg=='logoff') {
ycomm.canReceiveMessages = false;
/* If I'm on a windows, I need to close the opener */
var wOpener=window, wAux;
while (wOpener.opener) {
wAux=wOpener;
wOpener=wOpener.opener;
wAux.close();
}
while (wOpener.parent != wOpener)
wOpener = wOpener.parent;
if (xSysMsg.banner) {
_dumpy(4,1,xSysMsg.banner);
alert(xSysMsg.banner);
}
wOpener.document.location='body.php?s=yeapf&a=logoff';
}
}
}
/* only continue if the user is logged */
if (ycomm.canReceiveMessages) {
if (xDataContext) {
var i;
if (xDataContext.requiredFields) {
var reqFields = xDataContext.requiredFields.split(',');
for(i = 0; i<reqFields.length; i++) {
fieldName=reqFields[i];
if (y$(fieldName))
y$(fieldName).addClass('fieldWarning');
}
}
if (xDataContext.formError) {
var auxFormError = '';
for(i in xDataContext.formError)
if (xDataContext.formError.hasOwnProperty(i)) {
if (auxFormError>'')
auxFormError+="\n";
auxFormError = auxFormError+xDataContext.formError[i];
}
alert(auxFormError);
}
}
if (xRoot) {
if (xDataContext['formID']!=undefined) {
if (formID=='') {
formID=xDataContext['formID'];
// alert("FORMID: "+formID);
}
}
xDataContext['firstRow'] = parseInt(xDataContext['firstRow']);
xDataContext['rowCount'] = parseInt(xDataContext['rowCount']);
xDataContext['requestedRows'] = parseInt(xDataContext['requestedRows']);
var auxRowCount = xDataContext['rowCount'];
if (xRoot['data'])
xData=xRoot['data']['row'];
else
xData=xRoot['row'];
if (auxRowCount==1) {
xData=new Array(xData);
}
if (xData) {
for(var n in xData)
if (xData.hasOwnProperty(n)) {
for(var j in xData[n])
if (xData[n].hasOwnProperty(j))
xData[n][j]=unmaskHTML(xData[n][j]);
}
}
if (xRoot['data']!==undefined)
xGeometry = xRoot['data']['geometry'];
}
} /* end of (ycomm.canReceiveMessages==true) */
var ret = {
data: xData,
geometry: xGeometry,
dataContext: xDataContext,
error: xError,
userMsg: xUserMsg
};
return ret;
};
ycomm.text2data = function (aResponseText) {
var ret={};
if (typeof DOMParser == 'function') {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(aResponseText, "application/xml");
ret=ycomm.explodeData(xmlDoc);
}
return ret;
};
/*
* https://developer.mozilla.org/en-US/docs/Web/API/FormData
* https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
* https://developer.mozilla.org/en-US/docs/Web/API/FileReader#readAsArrayBuffer%28%29
*/
ycomm.invoke = function(s, a, limits, callbackFunction, async) {
if (typeof async=='undefined')
async = true;
/* if the first parameter is an object, then
* all the others parameters are expected to be into that object */
if (typeof s =='object') {
var auxObj = s;
var s = auxObj.s;
var a = auxObj.a;
var limits = auxObj.limits;
var callbackFunction = auxObj.callbackFunction;
}
var localU = (typeof u == 'undefined')?'':u;
ycomm.waitIconControl(true);
var aURL=this.buildCommonURL(s || '', a || '', limits || {}, localU);
if (typeof xAjax!='undefined') {
var aux=xAjax();
aux.Request(
this.scriptName,
{
method: ycomm.defaultMethod,
asynchronous: yloader.isWorker?false:async,
parameters: aURL,
onTimeout: function() {
console.log('XMLHttpRequest timeout');
},
onComplete: function(r) {
var retData = {
data: null,
geometry: null,
dataContext: null,
error: null,
userMsg: null
},
xmlDoc=null;
if (r.status==200) {
if (typeof('ycomm.msg.notifyServerOnline')=='function')
ycomm.msg.notifyServerOnline();
if (r.responseXML) {
xmlDoc = r.responseXML;
} else {
if (typeof DOMparser == 'function') {
var parser = new DOMParser();
xmlDoc = parser.parseFromString(r.responseText, "application/xml");
}
}
if (xmlDoc!==null)
retData = ycomm.explodeData(xmlDoc);
} else {
console.log(r.statusText);
if (typeof('_notifyServerOffline')=='function')
setTimeout(_notifyServerOffline,500);
}
ycomm.waitIconControl(false);
if (retData.error) {
for(var k in retData.error) {
if (retData.error.hasOwnProperty(k))
console.error(retData.error[k]);
}
}
if (typeof callbackFunction=='function') {
if (yloader.isWorker)
callbackFunction(r.responseText);
else
callbackFunction(r.status, retData.error, retData.data, retData.userMsg, retData.dataContext, retData.geometry);
}
}
}
);
} else {
console.log("Not ready to call "+aURL);
console.log("prototype library not loaded");
}
};
/* END ycomm-ajax.js */
_dump("ycomm-ajax");
/* START ycomm-rest.js */
/*********************************************
*
* ycomm-rest.js is a set of prototyped functions
* build in order to use REST protocol
*
*********************************************/
ycomm.setDataLocation = function(dataLocation) {
this._dataLocation_=dataLocation;
};
ycomm.getDataLocation = function () {
return this._dataLocation_;
};
ycomm._scriptSequence = 0;
ycomm._maxScriptSequenceReceived = 0;
ycomm._CBSeq = 1000;
ycomm._CBControl = {};
ycomm._load = 0;
ycomm._queue = 0;
ycomm._maxDirectCall = 10;
ycomm._dataLocation_ = (
function() {
var a = (typeof document=='object' && document.location && document.location.href)?document.location.href:'';
var b=a.lastIndexOf('/');
return a.substr(0,b+1)+'rest.php';
}
)();
ycomm.getLoad = function () {
return this._load;
};
ycomm._removeJSONP = function (scriptSequence, callback) {
var head = document.head;
var scriptID = "rest_"+scriptSequence;
var script = document.getElementById(scriptID);
if ((head!==undefined) && (script!==undefined)) {
head.removeChild(script);
_dumpy(4,1,'Clean '+scriptID+' after call to '+callback+'()');
} else
_dumpy(4,1,'Script not found: '+scriptID+' adressed to '+callback+'()');
_dumpy(4,1,ycomm.getStatus());
};
ycomm.rest_timeout = 3500;
ycomm.bring = function (url) {
var head = document.head;
var script = document.createElement("script");
_dumpy(4,1,url);
// extrair o scriptSequence e o callback para depuracao
var scriptSequence=null;
var callback=null;
var aux = url.substr(url.indexOf('?')+1).split('&');
for(var i in aux) {
if (aux.hasOwnProperty(i)) {
var v = aux[i].split('=');
if (v[0]=='scriptSequence')
scriptSequence=v[1];
if (v[0]=='callback')
callback=v[1];
}
}
ycomm._maxScriptSequenceReceived = Math.max(ycomm._maxScriptSequenceReceived, scriptSequence);
script.onload=function() {
if (ycomm._load>0)
ycomm._load--;
};
script.setAttribute("src", url);
script.id='rest_'+scriptSequence;
head.appendChild(script);
setTimeout("ycomm._removeJSONP("+scriptSequence+",'"+callback+"');", ycomm.rest_timeout);
};
ycomm.crave = function (s, a, limits, callbackFunction, callbackId) {
var localU = (typeof u == 'undefined')?'':u;
if (typeof callbackId == 'undefined')
callbackId = 0;
/* sequence number for script garbage collect */
ycomm._scriptSequence++;
if (!this.getDataLocation())
console.error("You need to define dataLocation before 'crave' it");
else {
var callbackFunctionName;
if (typeof callbackFunction=='function') {
/* the user has passed an annon function
* CallBack sequencer */
ycomm._CBSeq++;
/* name for the callback function */
callbackFunctionName="ycb"+ycomm._CBSeq;
/* callback control... for garbage collect */
ycomm._CBControl[callbackFunctionName]={ready: false};
window[callbackFunctionName]=function(status, error, data, userMsg, context, geometry) {
callbackFunction(status, error, data, userMsg, context, geometry);
console.log(callbackFunctionName);
};
} else if (typeof callbackFunction=='string') {
callbackFunctionName=callbackFunction;
} else
console.error("param callBackFunction need to be function or string");
if (callbackFunctionName>'') {
/* number of concurrent calls */
ycomm._load++;
var aURL=this.buildCommonURL(s || '', a || '', limits || {}, localU);
aURL="{0}?{1}&callback={2}&callbackId={3}&scriptSequence={4}".format(this._dataLocation_, aURL, callbackFunctionName, callbackId, ycomm._scriptSequence);
if (ycomm.getLoad()<=ycomm._maxDirectCall)
ycomm.bring(aURL);
else
setTimeout("ycomm.bring('"+aURL+"');", 250 + (ycomm.getLoad() - ycomm._maxDirectCall) * 500);
}
}
};
ycomm.isIdle = function () {
return (ycomm._maxScriptSequenceReceived == ycomm._scriptSequence);
};
ycomm.getStatus = function () {
return "isIdle() = {0} getLoad() = {1}".format(this.isIdle(), this.getLoad());
};
/* END ycomm-rest.js */
_dump("ycomm-rest");
/* START ycomm-dom.js */
/*********************************************
* First Version (C) 2014 - esteban daniel dortta - dortta@yahoo.com
**********************************************/
ycomm.dom = {};
/*
* aElementID - ID do elemento (SELECT ou TABLE)
* xData - vetor bidimensional associativo que vem do ajax/rest/...
* aLineSpec - formatacao de cada linha em JSON conforme a seguinte descricao
* -- vars --
* idFieldName - string containing ID field name on xData
* columns: { - json describing each column as next:
* columnName: { - maybe an existing column in xdata or a new alias just for show
* title - column title
* width - string. prefer px
* visible - boolean
* html - optional html format string that can use %() functions (yAnalise() function)
* align - left, center, right
* type - (int,integer,intz,intn,decimal,ibdate,tsdate,tstime,date,time)
* editMask - 'dd/mm/yyy HH:MM:SS', '#,99', '#.###,##'
* storageMask - 'yyyymmddHHMMSS', '#.99'
* }
* }
* rows: [] - string array with complete "<td>%(fieldName)</td>..." definition
* html - string using postprocess yeapf tags as in prior html
* inplaceData: [] - string array with the columns that need to be placed
* inside de TR definition. ie. the id is the user code
* and the inplaceData are the name and email.
* elementPrefixName - string to be added before each target (element) form fields
* elementPostfixName - string to be added after each target (element) form fields
*
* beforeElement - string with LI element id indicating new elements will be added before it
*
* -- events -- (READY)
* onNewItem(aElementID, aNewElement, aRowData)
* onNewRowReady(aElementID, aRow)
* onSelect(aElementID, id) ou onClick(aElementID, id)
* -- events -- (PLANNED)
* onBeforeItemAdd(aElementID, id, dataLine)
* onItemAdd(aElementID, id)
* onReady(aElementID)
*/
ycomm.dom.fillElement = function(aElementID, xData, aLineSpec, aDeleteRows) {
if (aLineSpec === undefined)
aLineSpec = {};
if (aDeleteRows === undefined)
aDeleteRows = true;
var idFieldName, colName, newRow, canCreateRow,
aElement = y$(aElementID),
rowIdOffset=0;
idFieldName = aLineSpec.idFieldName || 'id';
var setNewRowAttributes = function (aNewRow) {
var auxIdSequence,
auxInplaceData;
cNdx = 0;
if (aNewRow.nodeName=='TR')
aNewRow.style.backgroundColor=rowColorSpec.suggestRowColor(rowGroup);
if (xData[j][idFieldName]) {
if (y$(xData[j][idFieldName])) {
auxIdSequence = 0;
while (y$(xData[j][idFieldName]+'_'+auxIdSequence))
auxIdSequence++;
aNewRow.id = xData[j][idFieldName]+'_'+auxIdSequence;
} else
aNewRow.id = xData[j][idFieldName];
}
if (typeof aLineSpec.inplaceData != 'undefined') {
for(var i=0; i<aLineSpec.inplaceData.length; i++) {
colName = aLineSpec.inplaceData[i];
auxInplaceData = xData[j][colName] || '';
aNewRow.setAttribute('data_'+colName, auxInplaceData);
}
}
if ((aLineSpec.onClick) || (aLineSpec.onSelect)) {
aNewRow.addEventListener('click', ((aLineSpec.onClick) || (aLineSpec.onSelect)), false);
}
};
var addCell = function(colName) {
if (colName != idFieldName) {
var newCell = newRow.insertCell(cNdx),
aNewCellValue = colName!==null?unmaskHTML(xData[j][colName]):unmaskHTML(xData[j]);
if ((aLineSpec.columns) && (aLineSpec.columns[colName])) {
if (aLineSpec.columns[colName].align)
newCell.style.textAlign=aLineSpec.columns[colName].align;
if (aLineSpec.columns[colName].type) {
aNewCellValue = yAnalise('%'+aLineSpec.columns[colName].type+'('+aNewCellValue+')');
}
}
if (!canCreateRow) {
newCell.addClass('warning');
/* newCell.style.borderLeft = 'solid 1px red'; */
}
newCell.innerHTML = aNewCellValue.length===0?' ':aNewCellValue;
newCell.style.verticalAlign='top';
newCell.id=aElementID+'_'+cNdx+'_'+oTable.rows.length;
newCell.setAttribute('colName', colName);
if (typeof aLineSpec.onNewItem == 'function')
aLineSpec.onNewItem(aElementID, newCell, xData[j]);
cNdx = cNdx + 1;
}
};
var oTable, auxHTML, j, c, cNdx, i, newCell, internalRowId=(new Date()).getTime()-1447265735470;
if (aElement) {
if (aElement.nodeName=='TABLE') {
if (aElement.getElementsByTagName('tbody').length>0)
oTable = aElement.getElementsByTagName('tbody')[0];
else
oTable = aElement;
if (oTable.getElementsByTagName('tbody').length>0)
oTable = oTable.getElementsByTagName('tbody')[0];
if (aDeleteRows) {
while(oTable.rows.length>0)
oTable.deleteRow(oTable.rows.length-1);
} else {
rowIdOffset=oTable.rows.length;
}
var rowGroup = oTable.rows.length % 2;
cNdx = null;
for (j in xData) {
if (xData.hasOwnProperty(j)) {
rowGroup++;
canCreateRow = true;
if (!aDeleteRows) {
if (xData[j][idFieldName]) {
for(i=0; ((canCreateRow) && (i<oTable.rows.length)); i++) {
if (oTable.rows[i].id == xData[j][idFieldName]) {
newRow = oTable.rows[i];
while (newRow.cells.length>0)
newRow.deleteCell(0);
canCreateRow = false;
xData[j].rowid = i;
}
}
}
}
if (canCreateRow) {
newRow = oTable.insertRow(oTable.rows.length);
}
// xData[j]['rowid'] = parseInt(xData[j]['rowid']) + rowIdOffset + '';
internalRowId++;
xData[j].rowid = newRow.rowIndex || internalRowId + '';
xData[j]._elementid_ = aElementID;
setNewRowAttributes(newRow);
/* default action when neither columns nor html are defined */
if ((typeof aLineSpec.html == 'undefined') &&
(typeof aLineSpec.rows == 'undefined') &&
(typeof aLineSpec.columns == 'undefined')) {
if (typeof xData[j]=='string') {
addCell(null);
} else {
for(colName in xData[j]) {
if ((xData[j].hasOwnProperty(colName)) &&
(colName!=idFieldName) &&
(colName!='rowid') &&
(colName!='_elementid_')) {
addCell(colName);
}
}
}
} else {
/* columns order are defined */
if (typeof aLineSpec.columns != 'undefined') {
if (isArray(aLineSpec.columns)) {
for (c=0; c<aLineSpec.columns.length; c++) {
addCell(aLineSpec.columns[c]);
}
} else {
for(c in aLineSpec.columns) {
if (aLineSpec.columns.hasOwnProperty(c))
addCell(c);
}
}
} else if (typeof aLineSpec.html != 'undefined'){
/* html parser is enabled */
newCell = newRow.insertCell(0);
newCell.innerHTML = yAnalise(aLineSpec.html,xData[j]);
newCell.style.verticalAlign='top';
newCell.id=aElementID+'_'+cNdx+'_'+oTable.rows.length;
if (typeof aLineSpec.onNewItem == 'function')
aLineSpec.onNewItem(aElementID, newCell, xData[j]);
} else if (typeof aLineSpec.rows != 'undefined') {
var firstRow = true;
for(r=0; r < aLineSpec.rows.length; r++) {
if (!firstRow) {
newRow = oTable.insertRow(oTable.rows.length);
setNewRowAttributes(newRow);
}
newRow.innerHTML = yAnalise(aLineSpec.rows[r],xData[j]);
if (!canCreateRow) {
for(c=0; c<newRow.cells.length; c++)
newRow.cells[c].style.borderLeft = 'solid 1px red';
}
if (typeof aLineSpec.onNewItem == 'function')
aLineSpec.onNewItem(aElementID, newRow, xData[j]);
firstRow = false;
}
}
}
if (typeof aLineSpec.onNewRowReady == 'function') {
aLineSpec.onNewRowReady(aElementID, newRow);
}
}
}
} else if (aElement.nodeName=='UL') {
var oUL = aElement;
if (aDeleteRows) {
while (oUL.firstChild) {
oUL.removeChild(oUL.firstChild);
}
}
for (j in xData) {
if (xData.hasOwnProperty(j)) {
var entry = document.createElement('li');
var innerText = '',
asHTML=false;
if (typeof aLineSpec.rows=='object') {
for(r=0; r < aLineSpec.rows.length; r++) {
innerText=innerText+yAnalise(aLineSpec.rows[r],xData[j])+"";
}
asHTML=true;
} else if (typeof aLineSpec.html=='string') {
innerText=innerText+yAnalise(aLineSpec.html,xData[j])+"";
asHTML=true;
} else {
for(colName in xData[j]) {
if (innerText==='') {
if ((xData[j].hasOwnProperty(colName)) &&
(colName!=idFieldName) &&
(colName!='rowid') &&
(colName!='_elementid_')) {
innerText=innerText+xData[j][colName];
}
}
}
}
setNewRowAttributes(entry);
if (asHTML)
entry.innerHTML=innerText;
else
entry.appendChild(document.createTextNode(innerText));
if (typeof aLineSpec.beforeElement=='string') {
var item=y$(aLineSpec.beforeElement);
oUL.insertBefore(entry, item);
} else
oUL.appendChild(entry);
if (typeof aLineSpec.onNewItem == 'function')
aLineSpec.onNewItem(aElementID, entry, xData[j]);
}
}
} else if (aElement.nodeName=='LISTBOX') {
var oListBox = aElement;
if (aDeleteRows) {
while(oListBox.childElementCount>0)
oListBox.childNodes[0].remove();
}
var cRow = 0;
for (j in xData) {
if (xData.hasOwnProperty(j)) {
xData[j]._elementid_ = aElementID;
newRow = document.createElement('listitem');
cNdx = 0;
if (typeof aLineSpec.columns == 'undefined') {
if (typeof xData[j] == 'string') {
_dumpy(2,1,"ERRO: yeapf-dom.js - string cell not implemented");
} else {
for(colName in xData[j]) {
if ((xData[j].hasOwnProperty(colName)) &&
(colName!=idFieldName) &&
(colName!='rowid') &&
(colName!='_elementid_')) {
newCell = document.createElement('listcell');
newCell.innerHTML = xData[j][colName];
newCell.id=aElementID+'_'+cNdx+'_'+cRow;
if (typeof aLineSpec.onNewItem == 'function')
aLineSpec.onNewItem(aElementID, newCell, xData[j]);
cNdx = cNdx + 1;
newRow.appendChild(newCell);
}
}
}
} else {
for(colName in aLineSpec.columns) {
if (colName != idFieldName) {
newCell = document.createElement('listcell');
newCell.innerHTML = xData[j][colName];
newCell.id=aElementID+'_'+cNdx+'_'+cRow;
if (typeof aLineSpec.onNewItem == 'function')
aLineSpec.onNewItem(aElementID, newCell, xData[j]);
cNdx = cNdx + 1;
newRow.appendChild(newCell);
}
}
}
oListBox.appendChild(newRow);
cRow++;
}
}
} else if ((aElement.nodeName=='SELECT') || (aElement.nodeName=='DATALIST')) {
/* Clean options */
if (aDeleteRows){
while (aElement.options.length>0)
aElement.options.remove(0);
}
cNdx = 0;
/* data */
for (j in xData) {
if (xData.hasOwnProperty(j)) {
xData[j]._elementid_ = aElementID;
auxHTML = '';
if (typeof aLineSpec.columns == 'undefined') {
if (typeof xData[j] == 'string') {
_dumpy(2,1,"ERRO: yeapf-dom.js - string cell not implemented");
} else {
for(colName in xData[j]) {
if ((xData[j].hasOwnProperty(colName)) &&
(colName!=idFieldName) &&
(colName!='rowid') &&
(colName!='_elementid_')) {
auxHTML = auxHTML + xData[j][colName];
}
}
}
} else {
if (isArray(aLineSpec.columns)) {
for (c=0; c<aLineSpec.columns.length; c++) {
auxHTML = auxHTML + xData[j][aLineSpec.columns[c]] + ' ';
}
} else {
if (typeof xData[j] == 'string') {
_dumpy(2,1,"ERRO: yeapf-dom.js - string cell not implemented");
} else {
for(colName in aLineSpec.columns) {
if (colName != idFieldName)
auxHTML = auxHTML + xData[j][colName];
}
}
}
}
var opt = document.createElement('option');
if (typeof xData[j][idFieldName] != 'undefined')
opt.value = xData[j][idFieldName];
opt.innerHTML = auxHTML;
opt.id=aElementID+'_'+cNdx;
if (typeof aLineSpec.onNewItem == 'function')
aLineSpec.onNewItem(aElementID, opt, xData[j]);
aElement.appendChild(opt);
cNdx++;
}
}
if (aElement.onclick)
aElement.onclick();
} else if (aElement.nodeName=='FORM') {
var fieldType,
valueType,
editMask,
storageMask,
fieldValue,
fieldName,
fieldPrefix, fieldPostfix,
aElements;
if (aDeleteRows)
aElements = this.cleanForm(aElementID);
else
aElements = this.selectElements(aElementID);
if (xData)
if ((typeof xData=='object') || (xData.length === 1)) {
var yData=xData[0] || xData;
fieldPrefix = aLineSpec.elementPrefixName || '';
fieldPostfix = aLineSpec.elementPostixName || '';
for (i=0; i < aElements.length; i++) {
/* the less prioritary MASK comes from the html form */
editMask = aElements[i].getAttribute('editMask');
storageMask = aElements[i].getAttribute('storageMask');
valueType = aElements[i].getAttribute('valueType') || 'text';
/* data comming from the server */
fieldName = suggestKeyName(yData, aElements[i].name || aElements[i].id, fieldPrefix, fieldPostfix);
/* column name defined by the programmer on client side */
colName = (aLineSpec.columns && suggestKeyName(aLineSpec.columns, aElements[i].id)) || null;
if (typeof yData[fieldName] != 'undefined') {
fieldValue = unmaskHTML(yData[fieldName]);
fieldType = aElements[i].type.toLowerCase();
/* only fill field if there is not column definition
* or if the colName is defined */
if ((!aLineSpec.columns) || (colName>'')) {
/* if thete is a colName, pick type and mask from aLineSpec */
if (colName>'') {
if (!isArray(aLineSpec.columns)) {
valueType = aLineSpec.columns[colName].type;
editMask = (aLineSpec.columns[colName].editMask) || editMask;
storageMask = (aLineSpec.columns[colName].storageMask) || storageMask;
}
}
if (valueType!='text') {
if ((editMask>'') && (storageMask>'')) {
if (valueType.indexOf('date')>=0) {
fieldValue = dateTransform(fieldValue, storageMask, editMask);
}
} else
fieldValue = yAnalise("%"+valueType+"("+fieldValue+")");
}
switch(fieldType) {
case "text":
case "password":
case "textarea":
case "email":
case "hidden":
aElements[i].value = fieldValue;
break;
case "radio":
case "checkbox":
/*
var options=document.getElementsByName(fieldName);
for (var j=0; j<options.length; j++)
if (options[j].value==fieldValue)
options[j].checked=true;
*/
if (aElements[i].value==fieldValue)
aElements[i].checked = (aElements[i].value === fieldValue);
break;
case "select-one":
case "select-multi":
for(j=0; j < aElements[i].options.length; j++)
if (aElements[i].options[j].value==fieldValue)
aElements[i].selectedIndex = j;
break;
}
if (typeof aLineSpec.onNewItem == 'function')
aLineSpec.onNewItem(aElementID, aElements[i], yData);
}
}
}
} else if (xData.length > 1)
console.log("There are more than one record returning from the server");
} else if (aElement.nodeName=='DIV') {
if (xData)
if (xData.length === 1) {
auxHTML='';
if (aDeleteRows)
aElement.innerHTML='';
else
auxHTML=aElement.innerHTML;
for(colName in xData[0])
if (xData[0].hasOwnProperty(colName)) {
auxHTML+='<div><div class=tnFieldName><b><small>{0}</small></b></div>{1}'.format(colName, xData[0][colName]);
}
aElement.innerHTML=auxHTML;
}
}
}
};
/*
* search for the first container from the element
* The container could be: a table row, a select option, a listbox item
* i.e. if the container is a row, aContainerID is the table which
* contains the ROW and the aElement is a button into the row
*/
ycomm.dom.getRowId = function(aElement, aContainerID) {
if (aElement) {
while ((aElement) && (aElement.parentNode)) {
aElement = aElement.parentNode;
}
}
};
ycomm.dom.getRowByRowNo = function(tableId, aRowNo) {
var table = document.getElementById(tableId);
if (table) {
var row = table.rows[aRowNo];
return row;
} else
return null;
};
ycomm.dom.getTableRowId = function(tableId, aRowNo) {
var row = ycomm.dom.getRowByRowNo(tableId, aRowNo);
return row?row.id:null;
};
ycomm.dom.highlightRow = function(tableId, aRowId, highlightClass) {
highlightClass = highlightClass || '';
var c;
aRowId = typeof aRowId=='undefined'?-1:aRowId;
var table = document.getElementById(tableId);
if (table) {
for(var i=0; i<table.rows.length; i++) {
if (i==aRowId) {
table.rows[i].addClass(highlightClass);
for(c=0; c<table.rows[i].cells.length; c++)
table.rows[i].cells[c].addClass(highlightClass);
} else {
table.rows[i].removeClass(highlightClass);
for(c=0; c<table.rows[i].cells.length; c++)
table.rows[i].cells[c].removeClass(highlightClass);
}
}
}
};
ycomm.dom.getTableRowInplaceData = function(aRow, fieldName) {
if (aRow)
return aRow.getAttribute('data_'+fieldName);
else
return null;
};
ycomm.dom.getTableInplaceData = function(tableId, y, fieldName) {
var table = document.getElementById(tableId);
if (table) {
var row = table.rows[y];
return ycomm.dom.getTableRowInplaceData(row, fieldName);
} else
return null;
};
ycomm.dom.deleteElement = function(aElementId) {
var aElement = y$(aElementId);
if (aElement)
aElement.parentNode.removeChild(aElement);
};
ycomm.dom.selectElements = function (aElementId, aFieldListFilter) {
var aElements = [], knownField, allElements, i, fieldType;
var aForm = y$(aElementId);
if (aForm) {
allElements=aForm.getElementsByTagName('*');
for (i=0; i<allElements.length; i++) {
if (allElements[i].type) {
fieldType = allElements[i].type.toLowerCase();
knownFieldType = false;
if (aFieldListFilter) {
if (aFieldListFilter.indexOf(allElements[i].name || allElements[i].id)<0)
fieldType='--AVOID--';
}
switch(fieldType) {
case "text":
case "password":
case "textarea":
case "hidden":
case "email":
case "radio":
case "checkbox":
case "select-one":
case "select-multi":
knownFieldType = true;
}
if (knownFieldType)
aElements[aElements.length] = allElements[i];
}
}
}
return aElements;
};
ycomm.dom.cleanElement = function(aElement) {
if (typeof aElement == 'string')
aElement = y$(aElement);
if (aElement) {
var reservedFields = ['__cmd5p__'],
fieldModified,
fieldType, aux;
fieldType = aElement.type?aElement.type.toLowerCase():aElement.nodeName?aElement.nodeName.toLowerCase():'UNKNOWN';
fieldModified = false;
if (reservedFields.indexOf(aElement.id)<0) {
switch(fieldType) {
case "text":
case "password":
case "textarea":
case "hidden":
fieldModified = (aElement.value>'');
aElement.value = "";
break;
case "radio":
case "checkbox":
fieldModified = (aElement.checked !== false);
aElement.checked = false;
break;
case "select-one":
case "select-multi":
fieldModified = (aElement.selectedIndex>-1);
aElement.selectedIndex = -1;
break;
case "table":
if (aElement.getElementsByTagName('tbody').length>0)
aElement = aElement.getElementsByTagName('tbody')[0];
while(aElement.rows.length>0)
aElement.deleteRow(aElement.rows.length-1);
break;
case "ul":
while (aElement.firstChild) {
aElement.removeChild(aElement.firstChild);
}
break;
}
}
} else
_dumpy(2,1,"null element when calling cleanElement()");
};
ycomm.dom.cleanForm = function (aFormId, aFieldList) {
/*
<button>
<datalist>
<fieldset>
<form>
<input>
<keygen>
<label>
<legend>
<meter>
<optgroup>
<option>
<output>
<progress>
<select>
<textarea>
*/
var i, aElements;
aElements = this.selectElements(aFormId, aFieldList);
for (i=0; i<aElements.length; i++) {
ycomm.dom.cleanElement(aElements[i]);
}
return aElements;
};
/*
* get all the elements of the form and returns a JSON
*/
ycomm.dom.getFormElements = function (aFormId) {
var ret = {},
aElements = this.selectElements(aFormId),
fieldName, fieldType, fieldValue,
editMask,
storageMask,
valueType,
canChangeRetValue;
for (var i=0; i<aElements.length; i++) {
editMask = aElements[i].getAttribute('editMask') || '';
storageMask = aElements[i].getAttribute('storageMask') || '';
valueType = aElements[i].getAttribute('valueType') || 'text';
canChangeRetValue = true;
fieldType = aElements[i].type.toLowerCase();
fieldName = aElements[i].name || aElements[i].id;
if (fieldName>'') {
fieldValue = '';
if ( (fieldType=='radio') ||
(fieldType=='checkbox') ) {
canChangeRetValue = false;
if (typeof ret[fieldName] == 'undefined')
ret[fieldName]='';
}
switch(fieldType) {
case "text":
case "password":
case "textarea":
case "email":
case "hidden":
fieldValue = aElements[i].value.quoteString(true);
if (fieldValue !== null)
if ((editMask>'') && (storageMask>'')) {
if (valueType.indexOf('date')>=0) {
fieldValue = dateTransform(fieldValue.unquote(), editMask, storageMask);
if (fieldValue)
fieldValue = fieldValue.quoteString();
}
}
break;
case "radio":
case "checkbox":
fieldValue = aElements[i].checked?aElements[i].value.quoteString(true):'';
canChangeRetValue=(fieldValue!=='');
break;
case "select-one":
case "select-multi":
fieldValue = aElements[i].selectedIndex;
if (aElements[i].options[fieldValue])
fieldValue = aElements[i].options[fieldValue].value;
break;
}
if (canChangeRetValue)
ret[fieldName] = fieldValue;
}
}
return ret;
};
/* add an element to an existent form */
ycomm.dom.addFormElement = function (aForm, aTagName, aElementAttributes) {
var aNewElement = document.createElement(aTagName);
for(var i in aElementAttributes)
if (aElementAttributes.hasOwnProperty(i))
aNewElement.setAttribute(i,aElementAttributes[i]);
aForm.appendChild(aNewElement);
return aNewElement;
};
ycomm.dom.URL2post = function (aURL, aTarget, aWindow) {
if (aURL !== undefined) {
setTimeout(function () {
/* if no target was defined, use _self */
if (aTarget === undefined)
aTarget = '_self';
/* if no window was defined, use current */
if (aWindow === undefined)
aWindow = window;
/* default action is 'body.php' */
var aAction = 'body.php';
/* get the method */
aURL = aURL.split('?');
if (aURL.length==2) {
aAction = aURL[0];
aURL = aURL[1];
} else
aURL = aURL[0];
/* get the parameters */
aURL = aURL.split('&');
/* create the temporary form */
aWindow.auxForm = aWindow.document.createElement("form");
aWindow.document.body.appendChild(aWindow.auxForm);
aWindow.auxForm.setAttribute('method','post');
aWindow.auxForm.setAttribute('action',aAction);
aWindow.auxForm.setAttribute('target',aTarget);
for(var i=0; i<aURL.length; i++) {
var value = aURL[i].split('=');
if (value.length==1)
value[1]='';
ycomm.dom.addFormElement(aWindow.auxForm, 'input', {
'type': 'hidden',
'id': value[0],
'name': value[0],
'value': value[1] });
}
aWindow.auxForm.submit();
}, 1000);
}
};
ycomm.dom.deleteFieldClass = function (aElementList, aClassName) {
for(var i in aElementList)
if (aElementList.hasOwnProperty(i)) {
y$(i).deleteClass(aClassName);
}
};
ycomm.dom.viewport = function () {
var e = window,
a = 'inner';
while (e.parent != e)
e = e.parent;
if ( !( 'innerWidth' in window ) ) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
};
ycomm.dom.getLeft = function( oElement ) {
var iReturnValue = 0;
while( oElement!==null ) {
iReturnValue += oElement.offsetLeft;
oElement = oElement.offsetParent;
}
return iReturnValue;
};
ycomm.dom.getTop = function( oElement ) {
var iReturnValue = 0;
while( oElement !== null ) {
iReturnValue += oElement.offsetTop;
oElement = oElement.offsetParent;
}
return iReturnValue;
};
/* END ycomm-dom.js */
_dump("ycomm-dom");
/* START ycomm-msg.js */
/*********************************************
* First Version (C) 2014 - esteban daniel dortta - dortta@yahoo.com
* These routines were written in order to help interprocess process messages
* but as an remote process messages implementation.
* Or, IPC over RPC as you like.
* In Windows(TM) and Linux you would send a message to an application
* meanwhile, with YeAPF you will send messages to connected users.
* As this was not inteded to send chat messages, is correct to
* send messages to and only to connected users.
**********************************************/
var ycommMsgBase = function() {
that = {
messagePeekerTimer: null,
messageStack: [],
msgProcs: [],
_dbgFlag_noMessageProcessorPresent:false,
msgCount:0,
serverOfflineFlag:0
};
that.grantMsgProc = function(aInterval)
{
/* caso venha sem parámtros, calcular um tempo prudente de no máximo 20 segs
* Isso acontece quando o servidor devolveu uma resposta errada
* e queremos que o sistema de mensagens continue em operação. */
if ((aInterval===undefined) || (aInterval<=0))
aInterval = Math.min(20000,messagePeekerInterval * 2);
if (that.messagePeekerTimer === undefined) {
if (that.msgCount===0)
_dumpy(4,1,"Configuring receivers interval to "+aInterval+'ms');
that.messagePeekerTimer = setTimeout(ycomm.msg.peek, aInterval);
} else
_dumpy(4,1,"Receivers interval already defined");
};
that.feedBack= function ()
{
if (dRowCount>0) {
that.msgCount++;
for (var j in xData) {
if (!isNaN(parseInt(j))) {
var aux=xData[j];
that.messageStack.push(new Array(aux['sourceUserId'],
aux['message'],
aux['wParam'],
aux['lParam'])
);
}
}
if (that.messageStack.length>0) {
if (that.msgProcs.length==0) {
if (!that._dbgFlag_noMessageProcessorPresent)
if (jsDumpEnabled)
window.alert("Messages arriving at '"+_CurrentFileName+"' but there is not\na registered message processor in order to receive it.\nUse _registerMsgProc() to register it");
that._dbgFlag_noMessageProcessorPresent=true;
} else {
while (that.messageStack.length>0) {
var oldLen=that.messageStack.length;
for (var i=0; i<that.msgProcs.length; i++) {
// _dumpy(4,1,"Calling: "+that.msgProcs[i]);
var auxCallFunction='<script>'+that.msgProcs[i]+'();</'+'script>';
auxCallFunction.evalScripts();
}
if (oldLen==that.messageStack.length)
that.messageStack.shift();
}
}
}
}
grantMsgProc(messagePeekerInterval);
};
that.peek = function()
{
clearTimeout(that.messagePeekerTimer);
that.messagePeekerTimer=null;
var ts=new Date();
var auxParameters='s=y_msg&u='+u+'&a=peekMessage&formID='+formID+'&ts='+
ts.getTime()+'&callBackFunction=ycomm.msg.feedBack&messagePeekerInterval='+messagePeekerInterval;
var aux=new Ajax.Request(
'query.php',
{
method: 'get',
asynchronous: true,
parameters: auxParameters,
onComplete: function (transport) {
if (transport.status==200)
_QUERY_RETURN(transport);
else {
_dumpy(4,1,"*** XMLHttpRequest call failure");
setTimeout('_notifyServerOffline()',500);
}
}
}
);
};
that.postMessage = function(aTargetUserID, aMessage, aWParam, aLParam, aBroadcastCondition)
{
var ts=new Date();
if (aBroadcastCondition!=undefined)
var aux='&targetUser=*&broadcastCondition="'+aBroadcastCondition+'"';
else
var aux='&broadcastCondition=&targetUser='+aTargetUserID;
var auxParameters='s=y_msg&u='+u+'&a=postMessage'+aux+'&formID='+formID+
'&message='+aMessage+'&wParam='+aWParam+'&lParam='+aLParam+
'&ts='+ts.getTime()+'&callBackFunction=ycomm.msg.feedBack';
var aux=new Ajax.Request(
'query.php',
{
method: 'get',
asynchronous: false,
parameters: auxParameters,
onComplete: _QUERY_RETURN
}
);
};
that.cleanMsgQueue = function()
{
that.msgProcs.length=0;
};
that.notifyServerOnline = function()
{
if (that.serverOfflineFlag>0) {
that.serverOfflineFlag = 0;
var mainBody=__getMainBody();
var isReady = (typeof mainBody.$ == 'function') && (mainBody.document.body != null);
if (isReady) {
var notificationArea = mainBody.y$('notificationArea');
if (notificationArea)
notificationArea.style.display='none';
}
}
};
that.notifyServerOffline = function()
{
that.serverOfflineFlag++;
var mainBody=__getMainBody();
var isReady = (typeof mainBody.$ == 'function') && (mainBody.document.body != null);
if (isReady) {
var notificationArea = mainBody.y$('notificationArea');
if (!notificationArea) {
notificationArea = mainBody.document.createElement('div');
notificationArea.id='notificationArea';
setOpacity(notificationArea,90);
mainBody.document.body.appendChild(notificationArea);
if (!existsCSS('notificationArea')) {
notificationArea.style.zIndex=1000;
notificationArea.style.position='absolute';
notificationArea.style.left='0px';
notificationArea.style.top='0px';
notificationArea.style.border='1px #900 solid';
notificationArea.style.backgroundColor='#fefefe';
} else
notificationArea.className='notificationArea';
}
notificationArea.style.width=mainBody.innerWidth+'px';
notificationArea.style.height=mainBody.innerHeight+'px';
notificationArea.style.display='block';
notificationArea.innerHTML="<div style='padding: 32px'><big><b>Server Offline</b></big><hr>Your server has become offline or is mispeling answers when requested.<br>Wait a few minutes and try again later, or wait while YeAPF try again by itself</div> ";
}
grantMsgProc();
};
that.registerMsgProc = function(aFunctionName)
{
var canAdd=true;
_dumpy(4,1,"Registering message receiver: "+aFunctionName);
for (var i=0; i<that.msgProcs.length; i++)
if (that.msgProcs[i]==aFunctionName)
canAdd=false;
if (canAdd)
that.msgProcs[that.msgProcs.length]=aFunctionName;
grantMsgProc(messagePeekerInterval);
};
that.stopMsgProc = function()
{
clearTimeout(that.messagePeekerTimer);
}
return that;
}
ycomm.msg = ycommMsgBase();
/* END ycomm-msg.js */
_dump("ycomm-msg");
/* START ycalendar.js */
/*********************************************
* First Version (C) August 2013 - esteban daniel dortta - dortta@yahoo.com
**********************************************/
/*
* cfg elements
* view: 0 || 1 || 2
* orientation: 0 (landscape) || 1 (portrait)
* date: Date()
* dateScope { first: YYMMDDhhmmss, last: YYMMDDhhmmss}
* dayEntryDivision: 20 (minutes)
* cellSize { width: integer(px), height: integer (px) }
* divContainerName: string
*/
var yCalendar = function (cfg) {
var that = { };
that.cfg = cfg || { };
/*
0-month
1-week
2-day
*/
that.cfg.view = +(that.cfg.view || 0);
/*
* 0 - landscape
* 1 - portrait
*/
that.cfg.orientation = +(that.cfg.orientation || 0);
/*
* highlight date (or today as default)
*/
that.cfg.date = (that.cfg.date || new Date());
/*
* common division for day visualization (minutes)
*/
that.cfg.dayEntryDivision = that.cfg.dayEntryDivision || 20;
/*
* cell size in pixels
*/
if (that.cfg.cellSize) {
that.cfg.cellSize.width = that.cfg.cellSize.width || null;
that.cfg.cellSize.height = that.cfg.cellSize.height || null;
} else
that.cfg.cellSize = { width: null , height: null};
/*
* div container where to place the calendar
*/
that.cfg.divContainerName = that.cfg.divContainerName || '';
/*
* callback function to be called on different moments
*/
that.cfg.callback = that.cfg.callback || null;
that.context = { };
that.context.dateScope = { first: '', last: '' };
that.context.nCols = 0;
that.context.nRows = 0;
/*
* configuration functions
*/
/*
* set the container (div) to place the calendar
*/
that.setDivContainerName = function(aDivName) {
that.cfg.divContainerName = aDivName;
return that;
}
/*
* set cell size (width x height) in pixels
*/
that.setCellSize = function(aCellWidth, aCellHeight) {
that.cfg.cellSize.width = that.cfg.cellSize.width || aCellWidth;
that.cfg.cellSize.height = that.cfg.cellSize.height || aCellHeight;
return that;
}
that.setView = function(aView) {
that.cfg.view = +(aView) % 3;
return that;
}
that.setCallback = function(aCallback) {
that.cfg.callback = aCallback;
return that;
}
that.setDate = function(aDate) {
that.cfg.date = aDate || that.cfg.date;
return that;
}
that.getDate = function() {
return that.cfg.date;
}
/*
* set calendar orientation (0-landscape 1-portrait)
*/
that.setOrientation = function(aOrientation) {
that.cfg.orientation = (+(aOrientation) % 2);
return that;
}
/*
style that will be used
calBand,
calDayLCell, calWeekLCell, calMonthLCell
calDayPCell, calWeekPCell, calMonthPCell
calEmptyDayCel, calEmptyWeekCell, calEmptyMonthCell
*/
that.draw = function(aCaller) {
var orientationTag = ['L', 'P'];
var theDiv = y$(that.cfg.divContainerName);
if (theDiv) {
try {
/* status = 0. DOM BEING CREATED */
that.cfg.status = 0;
if (that.cfg.callback != null)
that.cfg.callback(that, 'DOMLocked', theDiv);
var aTag = null,
aCellID = null,
aTagClass = null,
aCellContent = null,
aAuxTag = null,
aDiv = null,
aSpan = null,
aText = null;
/* month ans week views increments in day chunks */
if (that.cfg.view<2)
var inc = 24 * 60 * 60 * 1000;
else
var inc = that.cfg.dayEntryDivision * 60 * 1000;
var colNumber = 0, rowNumber=0;
/*
* create a class base name to be used with all the elements
* that is: calDay followed by L(landscape) or P (portrait)
*/
var classBaseName = 'calDay'+orientationTag[that.cfg.view % 2];
/* remove all children nodes */
while (theDiv.hasChildNodes()) {
theDiv.removeChild(theDiv.lastChild);
}
/* create the calendar table */
that.context.oCalTable = document.createElement('table');
that.context.oCalTable.cellPadding=0;
that.context.oCalTable.cellSpacing=0;
var oTR = that.context.oCalTable.insertRow(-1);
var oTD = oTR.insertCell();
oTD.className = 'calBand';
var openRow = true;
var emptyCellCount = 0;
var extraStyle = { };
if (that.cfg.cellSize.height != null)
extraStyle.height = parseInt(that.cfg.cellSize.height) + 'px';
if (that.cfg.cellSize.width != null)
extraStyle.width = parseInt(that.cfg.cellSize.width) + 'px';
var d1 = that.context.dateScope.first;
var d2 = that.context.dateScope.last;
d1.setHours(12);
d2.setHours(12);
var createEmptyCell = function() {
/* create an unique ID for the empty day */
aCellID = that.cfg.divContainerName+"_empty_"+emptyCellCount;
/* create an empty day */
var aDiv = document.createElement('div');
mergeObject(extraStyle, aDiv.style);
aDiv.id = aCellID;
aDiv.className = classBaseName+"Cell "+classBaseName+"EmptyCell";
oTD.appendChild(aDiv);
if (that.cfg.orientation==0)
colNumber++;
emptyCellCount++;
/* call callback function */
if (that.cfg.callback!= null)
that.cfg.callback(that, 'getEmptyDayContent', aDiv);
}
var createFilledCell = function (aTagType) {
if (aTagType==0) {
aCellID = that.cfg.divContainerName+'_day_'+d.toUDate().substring(0,8);
aTag = d.getDate();
} else {
aTag = d.getHours()+':'+d.getMinutes();
aCellID = that.cfg.divContainerName+'_day_'+d.toUDate().substring(0, 12);
}
}
var d = new Date(d1);
var interactions = (d2 - d) / inc + 1;
if (that.cfg.view === 0) {
if (that.cfg.orientation==0) {
for(n = 0; n < d1.getDay(); n++) {
createEmptyCell();
}
} else {
d.setDate( d.getDate() - d1.getDay() );
var dOffset = [];
var dAux = new Date(d);
for(n = 0; n < that.context.nRows; n++) {
dOffset[n] = new Date(dAux);
dAux.setDate(dAux.getDate()+1);
}
}
}
while (interactions>0) {
if (!openRow) {
oTR = that.context.oCalTable.insertRow(-1);
oTD = oTR.insertCell();
oTD.className = 'calBand';
openRow = true;
}
aTag = '';
if (that.cfg.orientation==1) {
if ((d<d1) || (d>d2))
createEmptyCell();
else {
if ((that.cfg.view === 0) || (that.cfg.view === 1)) {
createFilledCell(0);
} else if (that.cfg.view === 2){
createFilledCell(1);
} else
_dumpy(8,1,"Not implemented");
}
} else if (that.cfg.orientation==0) {
if ((that.cfg.view === 0) || (that.cfg.view === 1)) {
createFilledCell(0);
} else if (that.cfg.view === 2) {
createFilledCell(1);
} else
_dumpy(8,1,"Not implemented");
}
if (aTag>'') {
aTagClass = classBaseName+'Cell';
if (d.getDay() === 0)
aTagClass += ' '+classBaseName+'FreeCell';
if (d.getDate()==that.cfg.date.getDate())
aTagClass += ' '+classBaseName+'Highlight';
/* create a day container */
aDiv = document.createElement('div');
mergeObject(extraStyle, aDiv.style);
aDiv.id = aCellID;
aDiv.className = aTagClass;
mergeObject(extraStyle, aDiv.style);
aDiv.date = d;
/* create a day tag */
aSpan = document.createElement('span');
aSpan.id = aCellID+"_tag";
aSpan.className = 'calTag';
if (that.cfg.callback!= null) {
aAuxTag = that.cfg.callback(that, 'getTagContent', aSpan) || '';
if (aAuxTag>'')
aTag = aAuxTag;
}
aSpan.innerHTML = aTag;
aDiv.appendChild(aSpan);
if (that.cfg.callback!= null) {
aText = that.cfg.callback(that, 'getCellContent', aDiv) || '';
if (aText>'') {
aDiv.innerHTML += aText;
}
}
oTD.appendChild(aDiv);
}
if (that.cfg.orientation==1) {
d.setTime(d.getTime()+inc * that.context.nRows);
} else
d.setTime(d.getTime()+inc);
colNumber++;
if(colNumber>=that.context.nCols) {
colNumber = 0;
rowNumber++;
openRow = false;
if (that.cfg.orientation==1)
d=dOffset[rowNumber];
}
interactions--;
}
if (openRow) {
while (colNumber<that.context.nCols) {
createEmptyCell();
}
colNumber = 0;
openRow = false;
}
theDiv.appendChild(that.context.oCalTable);
} catch(err) {
_dumpy(8,1,'ERROR: '+err.message);
}
// status = 1. DOM READY
that.cfg.status = 1;
if (that.cfg.callback!= null)
that.cfg.callback(that, 'DOMReleased', theDiv);
}
return that;
}
that.build = function(aDate, aView, aOrientation) {
that.cfg.orientation = aOrientation || that.cfg.orientation;
that.cfg.view = aView || that.cfg.view;
that.cfg.date = aDate || that.cfg.date;
var theDiv = y$(that.cfg.divContainerName);
if (theDiv) {
var d1 = new Date(that.cfg.date),
d2 = null,
secondsPerDay = 24 * 60 * 60 * 1000,
nCols = 0,
nRows = 0;
switch (that.cfg.view) {
case 0:
// month view.
nCols = 7;
nRows = 5;
// Recalculate dateScope
d1.setDate(1);
var d2 = new Date(d1);
d2.setDate(d1.daysInMonth());
break;
case 1:
// week view.
nCols = 1;
nRows = 7;
// Recalculate dateScope
var d1 = new Date(that.cfg.date);
while (d1.getDay()>0)
d1.setTime(d1.getTime()-secondsPerDay)
var d2 = new Date(d1);
d2.setTime(d1.getTime()+secondsPerDay * 6);
break;
case 2:
// day view
nCols = 1;
nRows = Math.round(24 * 60 / that.cfg.dayEntryDivision);
// Recalculate dateScope
d1.setHours(6); // <--- Need more config there
d1.setMinutes(0); // <--- Need more config there
var d2 = new Date(d1);
d2.setHours(21); // <--- Need more config there
d2.setMinutes(60-that.cfg.dayEntryDivision);
break;
default:
_dumpy(8,1,"Not implemented");
}
that.context.dateScope.first = d1;
that.context.dateScope.last = d2;
if (that.cfg.orientation === 1) {
that.context.nCols = nRows;
that.context.nRows = nCols;
} else {
that.context.nCols = nCols;
that.context.nRows = nRows;
}
that.draw(that);
_dumpy(8,1,"Build calendar on "+that.cfg.date.toUDate()+" View: "+that.cfg.view+" Orientation: "+that.cfg.orientation+" cols: "+nCols+" rows: "+nRows);
} else
_dumpy(8,1,"ERROR: "+that.cfg.divContainerName+" not found on that page");
return that;
}
that.each = function(aFunction) {
if (typeof aFunction == 'function') {
if (that.context.oCalTable) {
var idSeed = that.cfg.divContainerName+"_day_";
var processElement = function (aTagSpec) {
var elements = that.context.oCalTable.getElementsByTagName(aTagSpec);
for (var i=0; i<elements.length; i++)
if (elements[i].id.substr(0,idSeed.length)==idSeed)
aFunction(elements[i]);
}
processElement('div');
processElement('span');
}
}
return that;
};
return that;
};
/* END ycalendar.js */
_dump("ycalendar");
/* START ydyntable.js */
/*********************************************
* First Version (C) 2009 - esteban daniel dortta - dortta@yahoo.com
**********************************************/
function _dynCheckChilds(aStack, aField)
{
var childOpenCondition=aField.childOpenCondition;
if (childOpenCondition>'') {
var aResult = Parser.evaluate(childOpenCondition, aStack);
var childsContainer=y$(aField.name+'_childs');
if (childsContainer) {
if (aResult)
childsContainer.style.display='block';
else
childsContainer.style.display='none';
}
}
}
function dynCheckChids(aFieldList, e)
{
if (e==undefined)
var e = window.event || arguments.callee.caller.arguments[0];
if (e.target)
e = e.target;
// temporary stack to call Parser
var aStack=new Array();
for(var f in aFieldList)
if ((aFieldList.hasOwnProperty(f)) && (y$(f)))
aStack[f]=y$(f).value;
// check if it is entering from a form field
if (aFieldList[e.id])
_dynCheckChilds(aStack, aFieldList[e.id]);
else {
for(var f in aFieldList)
if (aFieldList.hasOwnProperty(f))
_dynCheckChilds(aStack, aFieldList[f]);
}
}
function _dynConfigOnChange(aElement, onChange)
{
if (aElement) {
if (aElement.onchange != __cbOnChange__) {
aElement.dynOnChange=aElement.onchange;
if (onChange==undefined)
aElement.onchange=__dynOnChange__;
else
aElement.onchange=onChange;
}
}
}
function dynConfigOnchange(aElementList, onChange)
{
if (typeof(aElementList) != 'object')
var aList = aElementList.split(',');
else
var aList=aElementList;
if (aList.length>0) {
for(var i=0; i<aList.length; i++)
_dynConfigOnChange(y$(aList[i]), onChange);
} else
for(var i in aList)
if (aList.hasOwnProperty(i))
_dynConfigOnChange(y$(i), onChange);
}
/*
* Sometimes you need to attach some fields display to a checkbox situation
* This function set onChange event of all the aElementSet
*/
function dynConfigCheckBoxChilds(aSaveOnChange, aElementSet)
{
if (aElementSet==undefined)
var aElementSet = document.getElementsByTagName('input');
if (aSaveOnChange==undefined)
var aSaveOnChange=false;
var auxID;
var ccDependents;
var allElements=document.getElementsByTagName('*');
for(var i=0; i<aElementSet.length; i++)
{
var canModifyEvents=false;
if (aElementSet[i].type=='checkbox') {
auxID = aElementSet[i].id+'.';
ccDependents=0;
for (var n=i+1; n<allElements.length; n++) {
var aID=allElements[n].id;
if (typeof aID == "string")
if (aID.substr(0,auxID.length)==auxID) {
dynSetElementDisplay(allElements[n].id, aElementSet[i].id, aElementSet[i].value);
// aElementSet[n].style.visibility=aElementSet[i].checked?'visible':'hidden';
ccDependents++;
}
}
canModifyEvents=true;
} else if (aElementSet[i].type=='text') {
canModifyEvents=true;
}
if (canModifyEvents) {
if (aElementSet[i].onchange != __cbOnChange__) {
aElementSet[i].dynOnChange=aElementSet[i].onchange;
aElementSet[i].onchange=__cbOnChange__;
aElementSet[i].dynSaveOnChange=aSaveOnChange;
}
}
}
}
function dynTableEnumerateCellElements(aTable, aFunction, aFirstRow)
{
if (aFirstRow==undefined)
aFirstRow=2;
for(var r=aFirstRow; r<aTable.rows.length; r++)
for (var c=0; c<aTable.rows[r].cells.length; c++) {
aCell=aTable.rows[r].cells[c];
var cellElements = aCell.getElementsByTagName('*');
for(var e in cellElements)
if (cellElements.hasOwnProperty(e))
aFunction(cellElements[e]);
}
}
function dynRenumberElements(e, aTable, aElementsSeed)
{
var aLines= new Array();
var aSequence=0;
dynTableEnumerateCellElements(aTable, function (aElement) {
if (typeof aElement.id != 'undefined') {
var idInfo=aElement.id.split('.');
if (aElementsSeed.indexOf(idInfo[0])>0) {
var aNdx=str2int(idInfo[1]);
if (aLines.indexOf(aNdx)<0)
aLines[aSequence++]=aNdx;
}
}
}, 1);
for(var i in aLines)
if (aLines.hasOwnProperty(i)) {
var aNdx=aLines[i];
for(var n in aElementsSeed)
if (aElementsSeed.hasOwnProperty(n)) {
document.getElementById(aElementsSeed[n]+'.'+zeroPad(aNdx,2)).id = aElementsSeed[n]+'.'+zeroPad(i,2);
}
}
}
function _dynCleanTableRow(e, aTable, aRowNdx)
{
for(var n=0; n<aTable.rows[aRowNdx].childNodes.length; n++)
dynCleanChilds(e, aTable.rows[aRowNdx].childNodes[n], true);
}
function dynCleanChilds(e, aDOMObject, aCleanAll, aChangeVisibility)
{
if (aDOMObject instanceof Text)
aDOMObject = aDOMObject.nextSibling;
if (aDOMObject!=undefined) {
if (aCleanAll==undefined)
aCleanAll=false;
if (aChangeVisibility==undefined)
aChangeVisibility=true;
var auxID;
if (!((e==undefined) ||(e==null)))
auxID = e.id+'.';
else
auxID = '*.';
var allElements=aDOMObject.getElementsByTagName('*');
for (var i=0; i<allElements.length; i++)
{
var aID=allElements[i].id;
if (typeof aID == 'string')
if ((aID.substr(0,auxID.length)==auxID) || (aCleanAll) || (auxID=='*.')) {
if ((aChangeVisibility) && (auxID!='*.'))
dynSetElementDisplay(allElements[i].id, e.id, e.value);
if ((auxID=='*.') || (!e.checked)) {
// limpar conteúdo dos campos dependentes
// caso esteja ocultando
if (allElements[i].type=='checkbox')
allElements[i].checked=false;
if (allElements[i].type=='radio')
allElements[i].checked=false;
if (allElements[i].type=='text')
allElements[i].value='';
if (allElements[i].type=='number')
allElements[i].value='';
if (allElements[i].rows != undefined) {
// keeps the first two lines of the table and eliminates the rest
// the first contains the titles
// the second contains the fields template and buttons
while (allElements[i].rows.length>2) {
_dynCleanTableRow(e, allElements[i],2);
allElements[i].deleteRow(2);
}
// clean the contents of the second row
if (allElements[i].rows.length>1)
for(var n=0; n<allElements[i].rows[1].childNodes.length; n++)
dynCleanChilds(e, allElements[i].rows[1].childNodes[n], true, false);
} else if (allElements[i].cells != undefined) {
for(var c=0; c<allElements[i].cells.length; c++)
dynCleanChilds(e, allElements[i].cells[c], true, aChangeVisibility);
} else
if (allElements[i].type!=undefined)
__cbOnChange__(allElements[i]);
}
}
}
}
}
function dynTableDelRow(e, aHeaderRowCount)
{
if (aHeaderRowCount==undefined)
aHeaderRowCount=2;
while ((e!=undefined) && (!(e instanceof HTMLTableRowElement)))
e=e.parentNode;
if (e) {
var table = e.parentNode;
if (table.rows.length>aHeaderRowCount) {
_dynCleanTableRow(e, table, e.rowIndex);
table.deleteRow(e.rowIndex);
} else {
_dynCleanTableRow(e, table, e.rowIndex);
/*
for (var c=0; c<e.cells.length; c++) {
var aCell=e.cells[c];
for (var i=0; i<aCell.childNodes.length; i++) {
var el=aCell.childNodes[i];
el.value=null;
}
}
*/
}
} else
alert("Your button is outside a table");
}
function dynTableDelAllRows(aTable)
{
while(aTable.rows.length>0)
dynTableDelRow(aTable.rows[0],0);
}
function _dynExplodeTag(aTag)
{
var sequence = aTag.match(/\d+$/)[0];
var name = aTag.substr(0,aTag.length-sequence.length);
return [name, sequence];
}
function dynTableCloneRow(e, onchange)
{
while ((e!=undefined) && (!(e instanceof HTMLTableRowElement)))
e=e.parentNode;
if (e) {
var table = e.parentNode;
var obj = e.cloneNode(true);
// Find a special object inside cells like INPUT elements
// so we can pick the name and use it as base for next name
// A name or id is composed of 'name' followed by 'sequence'
// for example: 'product01' is a valid tag
for (var c=0; c<obj.cells.length; c++) {
var aCell=obj.cells[c];
for (var i=0; i<aCell.childNodes.length; i++) {
var el=aCell.childNodes[i];
if (el.id>'') {
var elID = _dynExplodeTag(el.id);
var curSeq=elID[1];
curSeq=0;
while (y$(elID[0]+zeroPad(curSeq,2)))
curSeq++;
el.id=elID[0]+zeroPad(curSeq,2);
el.name=el.id;
el.onchange=onchange;
}
el.value=null;
}
}
var newRow=table.insertBefore(obj,e.nextSibling);
return newRow;
} else {
alert("Your button is outside a table");
return null;
}
}
function dynTableCloneLastRow(aTableId)
{
var oTable=y$(aTableId);
if (oTable.rows.length>0) {
var r=oTable.rows[oTable.rows.length-1];
dynTableCloneRow(r);
}
}
function dynSetElementDisplay(aElementID, aMasterFieldName, aMasterFieldValue)
{
var element=y$(aElementID);
if (element) {
var field=y$(aMasterFieldName);
if (field) {
var theFieldValue;
if (field.type=='radio') {
var auxRadio=document.getElementsByName(aMasterFieldName);
// if not master value defined, we assume the last one of the series is the desired trigger value
if (aMasterFieldValue==undefined)
if (auxRadio.length>0)
aMasterFieldValue=auxRadio[auxRadio.length-1].value;
for(var i=0; i<auxRadio.length; i++)
if (auxRadio[i].checked)
theFieldValue=auxRadio[i].value;
} else if (field.type=='checkbox') {
if (field.checked)
theFieldValue=field.value;
} else
theFieldValue=field.value;
if (aMasterFieldValue==undefined)
aMasterFieldValue=theFieldValue;
if (aMasterFieldValue==theFieldValue)
var aDisplay='';
else
var aDisplay='none';
if (element.type=='table') {
for (var r=0; r<element.rows.length; r++)
element.rows[r].style.display=aDisplay;
} else
element.style.display=aDisplay;
}
}
}
function dynSetDisplay(aElementSet, aDisplayStyle)
{
for(var i=0; i<aElementSet.length; i++) {
aElementSet[i].style.display=aDisplayStyle;
_dumpy(2,1,aElementSet[i].id, aElementSet[i].style.display);
}
}
function dynSetVisibility(aElementSet, aVisibility)
{
for(var i=0; i<aElementSet.length; i++) {
aElementSet[i].style.visibility=aVisibility;
_dumpy(2,1,aElementSet[i].id, aElementSet[i].style.visibility);
}
}
function dynRemoveElements(aElementSet)
{
for(var i=aElementSet.length-1; i>=0; i--) {
var pai = aElementSet[i].parentNode;
pai.removeChild(aElementSet[i]);
}
}
function dynTablePrint(aTable, aWidth, aHeight)
{
}
function calcGridAddItem(aCalcGrid, aFieldValues, aNewFieldName, aTitle, aFieldList, aCalcExpr, aResultCellPostfix, aForce, aUnits, aDecimalPlaces)
{
if (aForce==undefined)
aForce=false;
if (aUnits==undefined)
aUnits='';
if (aDecimalPlaces==undefined)
aDecimalPlaces='2';
var canAdd = true;
var aFields = aFieldList.split(',');
if (!aForce) {
for(var i in aFields)
if (aFields.hasOwnProperty(i))
if (aFieldValues[aFields[i]]==undefined)
canAdd = false;
}
if (canAdd) {
if (aCalcGrid[aNewFieldName]==undefined) {
aCalcGrid[aNewFieldName]=new Array();
aCalcGrid[aNewFieldName]['title']=aTitle;
aCalcGrid[aNewFieldName]['fieldList']=aFieldList;
aCalcGrid[aNewFieldName]['calcExpr']=aCalcExpr;
aCalcGrid[aNewFieldName]['resultCellPostfix']=aResultCellPostfix;
aCalcGrid[aNewFieldName]['units']=aUnits;
aCalcGrid[aNewFieldName]['decimalPlaces']=aDecimalPlaces;
} else
console.log("Field '"+aNewFieldName+"' already exists in calcGrid");
} else
console.log("Some fields does not exists in ("+aFieldValues+") list");
}
var _cg_rules = new Array();
function calcGridSetRules(aCalcGrid, aFieldList, aOnColumns)
{
if (_cg_rules[aCalcGrid.id]==undefined)
_cg_rules[aCalcGrid.id] = new Array();
_cg_rules[aCalcGrid.id]['rules']=aFieldList;
_cg_rules[aCalcGrid.id]['onColumns']=aOnColumns;
}
function calcGridSetCellsGuides(aCalcGrid, aColSet, aRowSet)
{
if (_cg_rules[aCalcGrid.id]==undefined)
_cg_rules[aCalcGrid.id] = new Array();
_cg_rules[aCalcGrid.id]['area']=new Array();
_cg_rules[aCalcGrid.id]['area']['colSet']=aColSet;
_cg_rules[aCalcGrid.id]['area']['rowSet']=aRowSet;
}
function calcGridGetColsGuide(aCalcGrid)
{
var ret=null;
if (aCalcGrid!=undefined) {
if (_cg_rules[aCalcGrid.id]!=undefined) {
ret = _cg_rules[aCalcGrid.id]['area']['colSet']
}
}
return ret;
}
function calcGridGetRowsGuide(aCalcGrid)
{
var ret=null;
if (aCalcGrid!=undefined) {
if (_cg_rules[aCalcGrid.id]!=undefined) {
ret = _cg_rules[aCalcGrid.id]['area']['rowSet']
}
}
return ret;
}
function calcGridEnumerateCells(aCalcGrid, aFunction, aSchema)
{
var ok=false;
var aRules = _cg_rules[aCalcGrid.id];
if (aRules) {
var aColSet=aRules['area']['colSet'];
var aRowSet=aRules['area']['rowSet'];
for(var r in aRowSet) {
if (aRowSet.hasOwnProperty(r)) {
for(var c in aColSet)
if (aColSet.hasOwnProperty(c)) {
var aCell=y$(r+'_'+aColSet[c].name);
if (aCell) {
if (aSchema!=undefined) {
ok=false;
if (aSchema.editable)
ok=(aColSet[c].editable && aRowSet[r].editable);
if (aSchema.name)
ok=ok || (aColSet[c].name==aSchema.name) || (aRowSet[r].name==aSchema.name);
} else
ok=true;
if (ok)
aFunction(aCell);
}
}
}
}
}
}
function calcGridCleanContent(aCalcGrid)
{
var aFields=new Array();
aFields['value']='';
aFields['calcGridSet']=aCalcGrid.id;
calcGridEnumerateCells(aCalcGrid,
function(a)
{
dynSetCellValue(a.id, aFields);
}
);
}
function calcGridCleanColumn(aCalcGrid, aColKey)
{
var aRules = _cg_rules[aCalcGrid.id];
if (aRules) {
var aColSet=aRules['area']['colSet'];
var aRowSet=aRules['area']['rowSet'];
var aCol = aColSet[aColKey];
var aCell;
if (aCol) {
for(var r in aRowSet) {
if (aRowSet.hasOwnProperty(r)) {
aCell=y$(r+'_'+aCol.name);
if (aCell)
dynSetCellValue(aCell.id,'');
}
}
}
}
}
function calcGridGetRules(aCalcGrid)
{
var aRules = _cg_rules[aCalcGrid.id];
if (aRules)
return aRules['rules'];
else
return {};
}
function calcGridGetAssociatedRule(aCalcGrid, aFieldName)
{
var ret=null;
var aRules = calcGridGetRules(aCalcGrid);
for(var f in aRules) {
if (ret==null) {
if (aRules.hasOwnProperty(f)) {
if (aFieldName==f)
ret=aRules[f];
}
}
}
return ret;
}
function calcGridGetRuleTitle(aCalcGrid, aFieldName)
{
var ret=null;
var theRule=calcGridGetAssociatedRule(aCalcGrid, aFieldName);
if (theRule!=null)
ret=theRule['title'];
return ret;
}
function calcGridGetNextFieldName(aCalcGrid, aFieldName)
{
var ret=null;
var aRules = calcGridGetRules(aCalcGrid);
var nextIsField=false;
for(var f in aRules) {
if (ret==null) {
if (aRules.hasOwnProperty(f)) {
if (nextIsField)
ret=f;
nextIsField=(f==aFieldName);
}
}
}
return ret;
}
function calcGridRecalc(aCalcGrid, aCellName)
{
var aRules=_cg_rules[aCalcGrid.id];
if (aRules) {
aRules = aRules['rules'];
for(var r in aRules)
if (aRules.hasOwnProperty(r)) {
var rule=aRules[r];
if (rule['fieldList']) {
if (rule['fieldList'].indexOf(aCellName) >= 0 ) {
var aFieldList=rule['fieldList'].split(',');
var aStack=new Array();
for(var f in aFieldList)
if (aFieldList.hasOwnProperty(f)) {
aStack[aFieldList[f]]=y$(aFieldList[f]).innerHTML;
}
var aResultCellName;
if (rule['resultCellPrefix']>'')
aResultCellName=rule['resultCellPrefix']+'_'+r;
else if (rule['resultCellPostfix']>'')
aResultCellName=r+'_'+rule['resultCellPostfix'];
else
aResultCellName=r;
var aResult = Parser.evaluate(rule['calcExpr'], aStack);
var aZero=0.00;
aZero = aZero.toFixed(rule['decimalPlaces']);
aResult=aResult.toFixed(rule['decimalPlaces']);
aResult = (isNaN(aResult)) ? aZero : (isInfinity(aResult) ? aZero : aResult+rule['units']);
y$(aResultCellName).innerHTML=aResult;
y$(aResultCellName).style.border='solid 1px #96CBFF';
}
}
}
}
}
function dynTableGetCellParentGrid(aCellId)
{
var aCell=y$(aCellId);
var aParent=aCell.parentNode;
while (aParent.tagName!='TABLE')
aParent=aParent.parentNode;
if (aParent.tagName=='TABLE')
return aParent;
else
return null;
}
function dynTableCreate(aTableContainer, aTableID)
{
if (aTableContainer) {
var fTable = document.createElement('table');
fTable.id=aTableID;
fTable.name=aTableID;
aTableContainer.appendChild(fTable);
} else
console.log('Error: You cannot create a dynTable without a div to contain it');
return fTable;
}
function dynTableSetRowTitles(aTable, aFirstRow, aFieldList, aGraphFunctionName)
{
for(var k in aFieldList)
if ((aFieldList.hasOwnProperty(k)) && (k!='_context_')) {
while (aTable.rows.length<aFirstRow) {
var aRow=aTable.insertRow(aTable.rows.length);
var aCell=aRow.insertCell(0);
}
var aRow = aTable.insertRow(aTable.rows.length);
var aCell = aRow.insertCell(0);
aCell.id=k;
if (aFieldList[k].parent>'') {
aCell.style.paddingLeft='18px';
aCell.style.fontSize='80%';
}
var aTitle=aFieldList[k].title;
if (undefined != aGraphFunctionName)
if (aFieldList[k].graph)
aTitle='<a href="javascript:'+aGraphFunctionName+'(\''+aTable.id+'\',\''+k+'\')">'+aTitle+'</a>';
aCell.innerHTML=aTitle;
}
}
function dynTableSetColTitles(aTable, aFirstCol, aSequence)
{
var aRow, aCell;
var i=aFirstCol;
for(var k in aSequence) {
if (aSequence.hasOwnProperty(k)) {
for(var r=0; r<aTable.rows.length; r++) {
aRow=aTable.rows[r];
while (aRow.cells.length<aFirstCol)
aCell=aRow.insertCell(aRow.cells.length);
aCell=aRow.insertCell(i);
if (r==0)
aCell.innerHTML=aSequence[k].title;
aCell.id=aTable.rows[r].cells[0].id+'_'+aSequence[k].name;
aCell.style.textAlign='center';
}
i++;
}
}
}
function dynTableSetColWidth(aTable, aWidth,aStart,aFinish)
{
if (aStart==undefined)
var aStart=0;
if (aFinish==undefined)
var aFinish=aTable.rows[aTable.rows.length-1].cells.length;
for(var c=aStart; c<=aFinish; c++)
for (var r=0; r<aTable.rows.length; r++)
if (aTable.rows[r].cells[c] != undefined)
aTable.rows[r].cells[c].style.minWidth=aWidth+'px';
}
function dynTableSetRowHeight(aTable, aHeight, aStart, aFinish)
{
if (aStart==undefined)
var aStart=0;
if (aFinish==undefined)
var aFinish=aTable.rows.length-1;
for (var r=aStart; r<=aFinish; r++)
aTable.rows[r].style.height=aHeight+'px';
}
function dynSetCellValue(aCellName, aCellValue)
{
if (y$(aCellName)) {
var aCoordinates=aCellName.split('_');
var aCalcGrid=dynTableGetCellParentGrid(aCellName);
var aRule = calcGridGetAssociatedRule(aCalcGrid, aCoordinates[0]);
if (aStack==undefined) {
var aFieldList = calcGridGetRules(aCalcGrid);
var aStack=new Array();
for (var f in aFieldList)
if ((f!=undefined) && (f!='_context_'))
if (aFieldList.hasOwnProperty(f)) {
aStack[f]=y$(f+'_'+aCoordinates[1]).innerHTML;
}
}
var canChangeCellValue=true;
if (y$(aCellName).innerHTML!='') {
if ((aRule.minVal!=undefined) && (aRule.minVal>'')) {
var checkMinVal = str2int(aCellValue.value)+' >= '+aRule.minVal;
var canChangeCellValue=Parser.evaluate(checkMinVal, aStack);
console.log(checkMinVal+' = '+canChangeCellValue);
}
if (canChangeCellValue) {
if ((aRule.maxVal!=undefined) && (aRule.maxVal!='')) {
var checkMaxVal = aRule.maxVal+' >= '+str2int(aCellValue.value);
var canChangeCellValue=Parser.evaluate(checkMaxVal, aStack);
console.log(checkMaxVal+' = '+canChangeCellValue);
}
}
}
if (canChangeCellValue) {
var aTotal=aCoordinates[0]+'_total';
var priorValue=str2int(y$(aCellName).innerHTML);
y$(aCellName).innerHTML=aCellValue.value;
if (y$(aTotal)) {
var vTotal=str2int(y$(aTotal).innerHTML);
vTotal=vTotal-priorValue+str2int(aCellValue.value);
y$(aTotal).innerHTML=vTotal;
var calcGridList = aCellValue.calcGridSet.split(',');
for (var aCG in calcGridList)
if (calcGridList.hasOwnProperty(aCG)) {
if (calcGridList[aCG]>'') {
var auxCalcGrid=y$(calcGridList[aCG]);
calcGridRecalc(auxCalcGrid, aTotal);
}
}
}
// table -> tr -> td
//var aCalcGrid=y$(aCellName).parentNode.parentNode.parentNode;
if (aRule!=undefined) {
var notificationFormId=aRule.notificationFormId;
if (notificationFormId>'') {
var fl='fl_'+notificationFormId;
var aFields = this[fl];
if (aFields) {
aFields['_position']=new Array();
aFields['_position']['name']='_position';
aFields['_position']['type']='hidden';
aFields['_position']['value']={ 'x': 100, 'y': 0};
askValue('/','javascript:dynSaveForm()',aFields);
}
}
}
if (aCellValue.openNextField) {
var nextField=calcGridGetNextFieldName(aCalcGrid, aCoordinates[0]);
var nextCellName=nextField+'_'+aCoordinates[1];
if (y$(nextCellName))
y$(nextCellName).click();
}
} else {
console.log("O Valor não pode ser lançado por não cumprir condições de existência");
window.alert("O valor não é consistente.\nRevise valores do campo pai e o próprio valor lançado\nTente novamente");
y$(aCellName).click();
}
}
}
function showCellInfo(aElement, show, aEditableFlag)
{
var aMessage = '';
if (aElement)
aMessage = aElement.parentElement.firstChild.innerHTML+'<br><small>Dia: '+aElement.cellIndex+'</small>';
if (!aEditableFlag)
var aStyle='color:#aaa';
else
var aStyle='font-weight: 800; color:black';
aMessage="<div style='"+aStyle+"'>"+aMessage+"</div>";
var tip=document.getElementById('tipDiv');
if (tip) {
if (show) {
tip.style.display='block';
var aTargetX = getX(aElement) + aElement.offsetWidth;
var aTargetY = getY(aElement) + aElement.offsetHeight;
new Effect.Move('tipDiv', { x: aTargetX, y: aTargetY, mode: 'absolute', duration: .3});
}
tip.innerHTML = aMessage;
}
}
function dynSetEditableCell(aTable, aColName, aRowName, aCalcGridSet, aEditable, aOnChangesFuncName)
{
var aCellName=aRowName+'_'+aColName;
var aCell=y$(aCellName);
if (aCell) {
// aCell.contentEditable=aEditableFlag;
aCell.onmouseover=function() {
//alert(this.parentElement.firstChild.innerHTML + this.cellIndex);
showCellInfo(this, true, aEditable);
}
aCell.onmouseout=function() {
//alert(this.parentElement.firstChild.innerHTML + this.cellIndex);
showCellInfo(this, false, aEditable);
}
if (aEditable) {
aCell.onclick=function() {
// var aRowName=this.id.split('_')[0];
var aFieldTitle = calcGridGetRuleTitle(this.parentNode.parentNode.parentNode, aRowName);
if (aFieldTitle==null)
aFieldTitle='Valor';
var aFields=new Array();
aFields['valor']=new Array();
aFields['valor']['title']=aFieldTitle+' / '+aColName;
aFields['valor']['name']='value';
aFields['valor']['type']='integer';
aFields['valor']['width']='4';
aFields['valor']['value']=aCell.innerHTML;
aFields['calcGridSet']=new Array();
aFields['calcGridSet']['name']='calcGridSet';
aFields['calcGridSet']['type']='hidden';
aFields['calcGridSet']['value']=aCalcGridSet;
aFields['openNextField']=new Array();
aFields['openNextField']['name']='openNextField';
aFields['openNextField']['type']='hidden';
aFields['openNextField']['value']=1;
var x=getX(aCell) + parseInt(aCell.offsetWidth);
var y=getY(aCell) + parseInt(aCell.offsetHeight);
aFields['_position']=new Array();
aFields['_position']['name']='_position';
aFields['_position']['type']='hidden';
aFields['_position']['value']={ 'x': x, 'y': y};
aFields['_position']['onChangesFuncName']=aOnChangesFuncName;
askValue('/','javascript:dynSetCellValue("'+aRowName+'_'+aColName+'")',aFields); ;
};
} else
aCell.onclick=null;
}
}
function dynSetEditableCells(aTable, aRowFields, aColFields, aOnChangesFuncName)
{
for(var r in aRowFields)
if (aRowFields.hasOwnProperty(r))
for(var c in aColFields) {
if (aColFields.hasOwnProperty(c)) {
dynSetEditableCell(aTable,
aColFields[c].name, aRowFields[r].name,
[aColFields[c]['calcGridAssoc'], aRowFields[r]['calcGridAssoc']],
(aColFields[c].editable) && (aRowFields[r].editable),
aOnChangesFuncName);
}
}
}
function dynSetClickableHeaders(aTable, aRowFields, aColFields, aOnClick)
{
for(var c in aColFields)
if (aColFields.hasOwnProperty(c)) {
var aCell=y$('_'+aColFields[c].name);
if (aCell) {
aCell.onclick=aOnClick;
}
}
}
function dynSetClickableRowHeaders(aTable, aRowFields, aColFields, aOnClick)
{
for(var r in aRowFields)
if (aRowFields.hasOwnProperty(r)) {
var aCell=y$(aRowFields[r].name);
if (aCell) {
aCell.onclick=aOnClick;
}
}
}
function sequenceSetValue(aSequence, aKey, aValue)
{
for (var n in aSequence)
if (aSequence.hasOwnProperty(n)) {
aSequence[n][aKey]=aValue;
}
}
function sequenceAdd(aSequence, aValue)
{
/*
var n=aSequence.length;
aSequence[n]=new Array();
aSequence[n]=aValue;
*/
aSequence[aValue.name]=aValue;
}
function sequenceProducer(aFirstValue, aLastValue, aInc)
{
var ret=new Array();
if (aInc>0) {
for(var n=aFirstValue; n<=aLastValue; n+=aInc) {
var aValue=new Array();
aValue.title=n;
aValue.name=n;
sequenceAdd(ret, aValue);
}
} else if (aInc<0) {
} else
console.log("You cannot create a non increment sequence");
return ret;
}
function fillTable(aTableId, aSQL, aFieldOrder, aLink, aFieldIdName, aOnData, aOnReady, aOnSelect, aFlags)
{
ycomm.invoke('yeapfDB',
'doSQL',
{ 'sql': '"'+aSQL+'"' },
function(status, xError, xData) {
/*@20150330 hideWaitIcon();*/
console.log(status, aTableId);
var aFieldList = aFieldOrder.split(',');
var aRows = '';
for(var i=0; i<aFieldList.length; i++)
aRows=aRows+'<td><a href="{1}">%({0})</a></td>'.format(aFieldList[i], aLink);
ycomm.dom.fillElement(
aTableId,
xData,
{ 'onNewItem': aOnData,
'rows': [aRows],
'inplaceData': [aFieldIdName],
'onNewItem': aOnData,
'onReady': aOnReady }
);
/*
var oTable = y$(aTableId);
if (oTable) {
var aContainer=oTable.parentNode;
if (aContainer)
aContainer.style.display='block';
var aHeaderLines=1;
var aBtnFlags=0;
if (aFlags) {
if (aFlags.headerLines!=undefined)
aHeaderLines = parseInt(aFlags.headerLines);
if (aFlags.btnFlags!=undefined)
aBtnFlags=parseInt(aFlags.btnFlags);
}
while(oTable.rows.length>aHeaderLines)
oTable.deleteRow(oTable.rows.length-1);
console.log(aFieldOrder);
var aFieldList=aFieldOrder.split(',');
for (var j in xData) {
if (xData.hasOwnProperty(j)) {
var aux=new Array();
var ndx=0;
var rowId='';
for (var col in aFieldList) {
if (aFieldList.hasOwnProperty(col)) {
var aColData=xData[j][trim(aFieldList[col])] || '';
if (aOnData!=undefined)
aColData=aOnData(aColData, trim(aFieldList[col]), aTableId, j);
aux[ndx++]=aColData;
if (trim(aFieldList[col])==aFieldIdName)
rowId=aColData;
}
}
if (rowId=='') {
for(var col in xData[j])
if (xData[j].hasOwnProperty(col)) {
if ((col==aFieldIdName) && (col>'')) {
aColData=xData[j][col];
if (aOnData!=undefined)
aColData=aOnData(aColData, trim(col), aTableId, j);
rowId=aColData;
}
}
}
if (rowId=='')
rowId=aTableId+'_'+j;
addRow(aTableId, aux, aLink, aBtnFlags, 0, -1, aOnSelect).id=rowId;
}
}
}
if (aOnReady!=undefined)
aOnReady(aTableId);
*/
});
}
function getCheckboxTable(aCheckboxID)
{
if (y$(aCheckboxID).parentElement)
return y$(aCheckboxID).parentElement.parentElement
else
return null;
}
function getAllCheckboxInTable(aTable)
{
var ret={};
var chk = aTable.getElementsByTagName('input');
var len = chk.length;
var n=0;
for (var i = 0; i < len; i++) {
if (chk[i].type === 'checkbox') {
ret[n++]=chk[i];
}
}
return ret;
}
function getFormSelectOptions(aArray, aFormName, aFormField, aOnReady)
{
aArray.length=0;
ycomm.invoke('yeapfDB',
'getFormSelectOptions',
{ 'formName': '"'+aFormName+'"',
'formField': '"'+aFormField+'"' },
function(status, xError, xData) {
/*@20150330 hideWaitIcon();*/
console.log(status, aFormName+'.'+aFormField);
for (var j in xData) {
if (xData.hasOwnProperty(j)) {
for(var k in xData[j])
if ((xData[j].hasOwnProperty(k)) && (k!='rowid'))
aArray[k]=xData[j][k];
}
}
if (aOnReady!=undefined)
aOnReady(aArray, aFormName, aFormField);
});
}
function $value(aID, aDefaultValue)
{
var a=y$(aID);
if (a)
return a.value;
else
return aDefaultValue;
}
function __saveFormInfo(e)
{
var s=$value('s','');
var a=$value('a','');
a = 'save'+a.ucFirst();
var id=$value('id','');
var v;
if (e.type=='checkbox')
v=e.checked?e.value:'';
else if (e.type=='text')
v=e.value;
var jFieldName = e.id;
jFieldName = jFieldName.replace('.','_');
_dumpy(2,1,'u',u,'s',s,'a',a,'id',id,'eID',e.id,'v',v);
_DO(s,a,'(id,'+jFieldName+')','('+id+','+v+')');
}
function __dynOnChange__(e)
{
if (e==undefined)
var e = window.event || arguments.callee.caller.arguments[0];
if (e.target)
e = e.target;
if (e.childOpenCondition)
console.log(e.childOpenCondition);
}
function __cbOnChange__(e, saving)
{
// procurar elemento que chamou esta função
if (e==undefined)
var e = window.event || arguments.callee.caller.arguments[0];
if (e.target)
e = e.target;
if (saving==undefined)
saving=e.dynSaveOnChange;
_dumpy(2,1,'check ',e.id,e.checked);
if (e.dynOnChange != undefined)
e.dynOnChange();
// salvar informação
if (saving)
__saveFormInfo(e);
/*
for (var n=i+1; n<allElements.length; n++)
if (allElements[n].id.substr(0,auxID.length)==auxID) {
dynSetElementDisplay(allElements[n].id, aElementSet[i].id, aElementSet[i].value);
// aElementSet[n].style.visibility=aElementSet[i].checked?'visible':'hidden';
ccDependents++;
}
*/
// corrigir visualização dos elementos dependentes do clicado
dynCleanChilds(e, document);
}
/* END ydyntable.js */
_dump("ydyntable");
|
var express = require('express');
var app = express();
var port = 4000;
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
app.listen(port, function(req, res) {
console.log("Listening to: " + port);
});
|
const path = require('path');
const fs = require("fs");
const copy = require('fs-extra').copySync;
const Handlebars = require('handlebars');
const j = require('jscodeshift');
const transform = require('./transform');
const ora = require('ora');
const chalk = require('chalk');
let spinner;
module.exports = function add(routeName) {
spinner = ora(chalk.green('Create route <' + routeName + '> ...')).start();
const cwd = process.cwd();
checkCurrentPath(cwd);
const componentName = routeName.replace(/^\w/, m => m.toUpperCase());
const tplPath = path.join(__dirname, '../boilerplates/template');
const from = {
rc: path.join(tplPath, 'routeComponent'),
route: path.join(tplPath, 'route.tpl'),
}
const to = {
rc: path.join(cwd, `src/containers/${componentName}`),
route: path.join(cwd, 'src/routes.js')
}
const data = {
componentName,
key: routeName.toLowerCase()
};
checkRoute(to.rc, to.route, data.key);
try {
createRouteCompoent(from.rc, to.rc, data);
appendRoute(from.route, to.route, data);
} catch(err) {
spinner.fail(chalk.red('Failed to create route'));
console.error(err);
}
spinner.succeed(`Success: created route at ${to.rc}`);
}
function checkCurrentPath(cwd) {
const r = fs.existsSync(path.join(cwd, 'src/routes.js')) && fs.existsSync(path.join(cwd, 'src/containers'));
if(!r) {
spinner.warn(chalk.yellow('Please switch to the root of the current project.'));
process.exit(1);
}
}
function checkRoute(dest, routes, key) {
if(fs.existsSync(dest)) {
spinner.warn(chalk.yellow(`The directory already exists: ${dest}`));
process.exit(1);
}
const r = j(fs.readFileSync(routes, 'utf-8'))
.find(j.Property, { key: { type: 'Identifier', name: 'childRoutes' } })
.find(j.Property, { key: { type: 'Identifier', name: 'path' }, value: { type: 'Literal', value: `/${key}` } }).size();
if(r != 0) {
spinner.warn(chalk.yellow(`the route <${key}> already exists: ${routes}`));
process.exit(1);
}
}
function createRouteCompoent(src, dest, data) {
fs.mkdirSync(dest);
(function run(src, dest) {
let dir = fs.readdirSync(src);
dir.forEach(file => {
let _src = path.join(src, file);
let _dest = path.join(dest, file);
if(fs.statSync(_src).isDirectory()) {
fs.mkdirSync(_dest);
run(_src, _dest);
} else {
if(path.extname(file) === '.tpl') {
let template = Handlebars.compile(fs.readFileSync(_src, 'utf-8'));
fs.writeFileSync(_dest.replace(/.tpl$/, '.js'), template(data));
} else {
copy(_src, _dest);
}
}
});
})(src, dest);
}
function appendRoute(src, dest, data) {
let template = Handlebars.compile(fs.readFileSync(src, 'utf-8'));
let route = template(data);
let routes = fs.readFileSync(dest, 'utf-8');
let code = transform(routes, route);
fs.writeFileSync(dest, code);
}
|
var app = require('./app')
, repl = require('repl')
, context = repl.start('blog> ').context
context.app = app
context.db = app.db
|
define("ace/ext/menu_tools/overlay_page",["require","exports","module","ace/lib/dom"], function(require, exports, module) {
'use strict';
var dom = require("../../lib/dom");
var cssText = "#ace_settingsmenu, #kbshortcutmenu {\
background-color: #F7F7F7;\
color: black;\
box-shadow: -5px 4px 5px rgba(126, 126, 126, 0.55);\
padding: 1em 0.5em 2em 1em;\
overflow: auto;\
position: absolute;\
margin: 0;\
bottom: 0;\
right: 0;\
top: 0;\
z-index: 9991;\
cursor: default;\
}\
.ace_dark #ace_settingsmenu, .ace_dark #kbshortcutmenu {\
box-shadow: -20px 10px 25px rgba(126, 126, 126, 0.25);\
background-color: rgba(255, 255, 255, 0.6);\
color: black;\
}\
.ace_optionsMenuEntry:hover {\
background-color: rgba(100, 100, 100, 0.1);\
transition: all 0.3s\
}\
.ace_closeButton {\
background: rgba(245, 146, 146, 0.5);\
border: 1px solid #F48A8A;\
border-radius: 50%;\
padding: 7px;\
position: absolute;\
right: -8px;\
top: -8px;\
z-index: 100000;\
}\
.ace_closeButton{\
background: rgba(245, 146, 146, 0.9);\
}\
.ace_optionsMenuKey {\
color: darkslateblue;\
font-weight: bold;\
}\
.ace_optionsMenuCommand {\
color: darkcyan;\
font-weight: normal;\
}\
.ace_optionsMenuEntry input, .ace_optionsMenuEntry button {\
vertical-align: middle;\
}\
.ace_optionsMenuEntry button[ace_selected_button=true] {\
background: #e7e7e7;\
box-shadow: 1px 0px 2px 0px #adadad inset;\
border-color: #adadad;\
}\
.ace_optionsMenuEntry button {\
background: white;\
border: 1px solid lightgray;\
margin: 0px;\
}\
.ace_optionsMenuEntry button:hover{\
background: #f0f0f0;\
}";
dom.importCssString(cssText);
module.exports.overlayPage = function overlayPage(editor, contentElement, callback) {
var closer = document.createElement('div');
function documentEscListener(e) {
if (e.keyCode === 27) {
close();
}
}
function close() {
if (!closer) return;
document.removeEventListener('keydown', documentEscListener);
closer.parentNode.removeChild(closer);
editor.focus();
closer = null;
callback && callback();
}
closer.style.cssText = 'margin: 0; padding: 0; ' +
'position: fixed; top:0; bottom:0; left:0; right:0;' +
'z-index: 9990; ' +
'background-color: rgba(0, 0, 0, 0.3);';
closer.addEventListener('click', function() {
close();
});
document.addEventListener('keydown', documentEscListener);
contentElement.addEventListener('click', function (e) {
e.stopPropagation();
});
closer.appendChild(contentElement);
document.body.appendChild(closer);
editor.blur();
return {
close: close
};
};
});
define("ace/ext/modelist",["require","exports","module"], function(require, exports, module) {
"use strict";
var modes = [];
function getModeForPath(path) {
var mode = modesByName.text;
var fileName = path.split(/[\/\\]/).pop();
for (var i = 0; i < modes.length; i++) {
if (modes[i].supportsFile(fileName)) {
mode = modes[i];
break;
}
}
return mode;
}
var Mode = function(name, caption, extensions) {
this.name = name;
this.caption = caption;
this.mode = "ace/mode/" + name;
this.extensions = extensions;
var re;
if (/\^/.test(extensions)) {
re = extensions.replace(/\|(\^)?/g, function(a, b){
return "$|" + (b ? "^" : "^.*\\.");
}) + "$";
} else {
re = "^.*\\.(" + extensions + ")$";
}
this.extRe = new RegExp(re, "gi");
};
Mode.prototype.supportsFile = function(filename) {
return filename.match(this.extRe);
};
var supportedModes = {
ABAP: ["abap"],
ABC: ["abc"],
ActionScript:["as"],
ADA: ["ada|adb"],
Apache_Conf: ["^htaccess|^htgroups|^htpasswd|^conf|htaccess|htgroups|htpasswd"],
AsciiDoc: ["asciidoc|adoc"],
ASL: ["dsl|asl"],
Assembly_x86:["asm|a"],
AutoHotKey: ["ahk"],
Apex: ["apex|cls|trigger|tgr"],
AQL: ["aql"],
BatchFile: ["bat|cmd"],
Bro: ["bro"],
C_Cpp: ["cpp|c|cc|cxx|h|hh|hpp|ino"],
C9Search: ["c9search_results"],
Crystal: ["cr"],
Cirru: ["cirru|cr"],
Clojure: ["clj|cljs"],
Cobol: ["CBL|COB"],
coffee: ["coffee|cf|cson|^Cakefile"],
ColdFusion: ["cfm"],
CSharp: ["cs"],
Csound_Document: ["csd"],
Csound_Orchestra: ["orc"],
Csound_Score: ["sco"],
CSS: ["css"],
Curly: ["curly"],
D: ["d|di"],
Dart: ["dart"],
Diff: ["diff|patch"],
Dockerfile: ["^Dockerfile"],
Dot: ["dot"],
Drools: ["drl"],
Edifact: ["edi"],
Eiffel: ["e|ge"],
EJS: ["ejs"],
Elixir: ["ex|exs"],
Elm: ["elm"],
Erlang: ["erl|hrl"],
Forth: ["frt|fs|ldr|fth|4th"],
Fortran: ["f|f90"],
FSharp: ["fsi|fs|ml|mli|fsx|fsscript"],
FSL: ["fsl"],
FTL: ["ftl"],
Gcode: ["gcode"],
Gherkin: ["feature"],
Gitignore: ["^.gitignore"],
Glsl: ["glsl|frag|vert"],
Gobstones: ["gbs"],
golang: ["go"],
GraphQLSchema: ["gql"],
Groovy: ["groovy"],
HAML: ["haml"],
Handlebars: ["hbs|handlebars|tpl|mustache"],
Haskell: ["hs"],
Haskell_Cabal: ["cabal"],
haXe: ["hx"],
Hjson: ["hjson"],
HTML: ["html|htm|xhtml|vue|we|wpy"],
HTML_Elixir: ["eex|html.eex"],
HTML_Ruby: ["erb|rhtml|html.erb"],
INI: ["ini|conf|cfg|prefs"],
Io: ["io"],
Jack: ["jack"],
Jade: ["jade|pug"],
Java: ["java"],
JavaScript: ["js|jsm|jsx"],
JSON: ["json"],
JSONiq: ["jq"],
JSP: ["jsp"],
JSSM: ["jssm|jssm_state"],
JSX: ["jsx"],
Julia: ["jl"],
Kotlin: ["kt|kts"],
LaTeX: ["tex|latex|ltx|bib"],
LESS: ["less"],
Liquid: ["liquid"],
Lisp: ["lisp"],
LiveScript: ["ls"],
LogiQL: ["logic|lql"],
LSL: ["lsl"],
Lua: ["lua"],
LuaPage: ["lp"],
Lucene: ["lucene"],
Makefile: ["^Makefile|^GNUmakefile|^makefile|^OCamlMakefile|make"],
Markdown: ["md|markdown"],
Mask: ["mask"],
MATLAB: ["matlab"],
Maze: ["mz"],
MEL: ["mel"],
MIXAL: ["mixal"],
MUSHCode: ["mc|mush"],
MySQL: ["mysql"],
Nginx: ["nginx|conf"],
Nix: ["nix"],
Nim: ["nim"],
NSIS: ["nsi|nsh"],
ObjectiveC: ["m|mm"],
OCaml: ["ml|mli"],
Pascal: ["pas|p"],
Perl: ["pl|pm"],
Perl6: ["p6|pl6|pm6"],
pgSQL: ["pgsql"],
PHP_Laravel_blade: ["blade.php"],
PHP: ["php|inc|phtml|shtml|php3|php4|php5|phps|phpt|aw|ctp|module"],
Puppet: ["epp|pp"],
Pig: ["pig"],
Powershell: ["ps1"],
Praat: ["praat|praatscript|psc|proc"],
Prolog: ["plg|prolog"],
Properties: ["properties"],
Protobuf: ["proto"],
Python: ["py"],
R: ["r"],
Razor: ["cshtml|asp"],
RDoc: ["Rd"],
Red: ["red|reds"],
RHTML: ["Rhtml"],
RST: ["rst"],
Ruby: ["rb|ru|gemspec|rake|^Guardfile|^Rakefile|^Gemfile"],
Rust: ["rs"],
SASS: ["sass"],
SCAD: ["scad"],
Scala: ["scala|sbt"],
Scheme: ["scm|sm|rkt|oak|scheme"],
SCSS: ["scss"],
SH: ["sh|bash|^.bashrc"],
SJS: ["sjs"],
Slim: ["slim|skim"],
Smarty: ["smarty|tpl"],
snippets: ["snippets"],
Soy_Template:["soy"],
Space: ["space"],
SQL: ["sql"],
SQLServer: ["sqlserver"],
Stylus: ["styl|stylus"],
SVG: ["svg"],
Swift: ["swift"],
Tcl: ["tcl"],
Terraform: ["tf", "tfvars", "terragrunt"],
Tex: ["tex"],
Text: ["txt"],
Textile: ["textile"],
Toml: ["toml"],
TSX: ["tsx"],
Twig: ["latte|twig|swig"],
Typescript: ["ts|typescript|str"],
Vala: ["vala"],
VBScript: ["vbs|vb"],
Velocity: ["vm"],
Verilog: ["v|vh|sv|svh"],
VHDL: ["vhd|vhdl"],
Visualforce: ["vfp|component|page"],
Wollok: ["wlk|wpgm|wtest"],
XML: ["xml|rdf|rss|wsdl|xslt|atom|mathml|mml|xul|xbl|xaml"],
XQuery: ["xq"],
YAML: ["yaml|yml"],
Django: ["html"]
};
var nameOverrides = {
ObjectiveC: "Objective-C",
CSharp: "C#",
golang: "Go",
C_Cpp: "C and C++",
Csound_Document: "Csound Document",
Csound_Orchestra: "Csound",
Csound_Score: "Csound Score",
coffee: "CoffeeScript",
HTML_Ruby: "HTML (Ruby)",
HTML_Elixir: "HTML (Elixir)",
FTL: "FreeMarker",
PHP_Laravel_blade: "PHP (Blade Template)",
Perl6: "Perl 6",
AutoHotKey: "AutoHotkey / AutoIt"
};
var modesByName = {};
for (var name in supportedModes) {
var data = supportedModes[name];
var displayName = (nameOverrides[name] || name).replace(/_/g, " ");
var filename = name.toLowerCase();
var mode = new Mode(filename, displayName, data[0]);
modesByName[filename] = mode;
modes.push(mode);
}
module.exports = {
getModeForPath: getModeForPath,
modes: modes,
modesByName: modesByName
};
});
define("ace/ext/themelist",["require","exports","module"], function(require, exports, module) {
"use strict";
var themeData = [
["Chrome" ],
["Clouds" ],
["Crimson Editor" ],
["Dawn" ],
["Dreamweaver" ],
["Eclipse" ],
["GitHub" ],
["IPlastic" ],
["Solarized Light"],
["TextMate" ],
["Tomorrow" ],
["XCode" ],
["Kuroir"],
["KatzenMilch"],
["SQL Server" ,"sqlserver" , "light"],
["Ambiance" ,"ambiance" , "dark"],
["Chaos" ,"chaos" , "dark"],
["Clouds Midnight" ,"clouds_midnight" , "dark"],
["Dracula" ,"" , "dark"],
["Cobalt" ,"cobalt" , "dark"],
["Gruvbox" ,"gruvbox" , "dark"],
["Green on Black" ,"gob" , "dark"],
["idle Fingers" ,"idle_fingers" , "dark"],
["krTheme" ,"kr_theme" , "dark"],
["Merbivore" ,"merbivore" , "dark"],
["Merbivore Soft" ,"merbivore_soft" , "dark"],
["Mono Industrial" ,"mono_industrial" , "dark"],
["Monokai" ,"monokai" , "dark"],
["Pastel on dark" ,"pastel_on_dark" , "dark"],
["Solarized Dark" ,"solarized_dark" , "dark"],
["Terminal" ,"terminal" , "dark"],
["Tomorrow Night" ,"tomorrow_night" , "dark"],
["Tomorrow Night Blue" ,"tomorrow_night_blue" , "dark"],
["Tomorrow Night Bright","tomorrow_night_bright" , "dark"],
["Tomorrow Night 80s" ,"tomorrow_night_eighties" , "dark"],
["Twilight" ,"twilight" , "dark"],
["Vibrant Ink" ,"vibrant_ink" , "dark"]
];
exports.themesByName = {};
exports.themes = themeData.map(function(data) {
var name = data[1] || data[0].replace(/ /g, "_").toLowerCase();
var theme = {
caption: data[0],
theme: "ace/theme/" + name,
isDark: data[2] == "dark",
name: name
};
exports.themesByName[name] = theme;
return theme;
});
});
define("ace/ext/options",["require","exports","module","ace/ext/menu_tools/overlay_page","ace/lib/dom","ace/lib/oop","ace/lib/event_emitter","ace/ext/modelist","ace/ext/themelist"], function(require, exports, module) {
"use strict";
var overlayPage = require('./menu_tools/overlay_page').overlayPage;
var dom = require("../lib/dom");
var oop = require("../lib/oop");
var EventEmitter = require("../lib/event_emitter").EventEmitter;
var buildDom = dom.buildDom;
var modelist = require("./modelist");
var themelist = require("./themelist");
var themes = { Bright: [], Dark: [] };
themelist.themes.forEach(function(x) {
themes[x.isDark ? "Dark" : "Bright"].push({ caption: x.caption, value: x.theme });
});
var modes = modelist.modes.map(function(x){
return { caption: x.caption, value: x.mode };
});
var optionGroups = {
Main: {
Mode: {
path: "mode",
type: "select",
items: modes
},
Theme: {
path: "theme",
type: "select",
items: themes
},
"Keybinding": {
type: "buttonBar",
path: "keyboardHandler",
items: [
{ caption : "Ace", value : null },
{ caption : "Vim", value : "ace/keyboard/vim" },
{ caption : "Emacs", value : "ace/keyboard/emacs" },
{ caption : "Sublime", value : "ace/keyboard/sublime" }
]
},
"Font Size": {
path: "fontSize",
type: "number",
defaultValue: 12,
defaults: [
{caption: "12px", value: 12},
{caption: "24px", value: 24}
]
},
"Soft Wrap": {
type: "buttonBar",
path: "wrap",
items: [
{ caption : "Off", value : "off" },
{ caption : "View", value : "free" },
{ caption : "margin", value : "printMargin" },
{ caption : "40", value : "40" }
]
},
"Cursor Style": {
path: "cursorStyle",
items: [
{ caption : "Ace", value : "ace" },
{ caption : "Slim", value : "slim" },
{ caption : "Smooth", value : "smooth" },
{ caption : "Smooth And Slim", value : "smooth slim" },
{ caption : "Wide", value : "wide" }
]
},
"Folding": {
path: "foldStyle",
items: [
{ caption : "Manual", value : "manual" },
{ caption : "Mark begin", value : "markbegin" },
{ caption : "Mark begin and end", value : "markbeginend" }
]
},
"Soft Tabs": [{
path: "useSoftTabs"
}, {
path: "tabSize",
type: "number",
values: [2, 3, 4, 8, 16]
}],
"Overscroll": {
type: "buttonBar",
path: "scrollPastEnd",
items: [
{ caption : "None", value : 0 },
{ caption : "Half", value : 0.5 },
{ caption : "Full", value : 1 }
]
}
},
More: {
"Atomic soft tabs": {
path: "navigateWithinSoftTabs"
},
"Enable Behaviours": {
path: "behavioursEnabled"
},
"Full Line Selection": {
type: "checkbox",
values: "text|line",
path: "selectionStyle"
},
"Highlight Active Line": {
path: "highlightActiveLine"
},
"Show Invisibles": {
path: "showInvisibles"
},
"Show Indent Guides": {
path: "displayIndentGuides"
},
"Persistent Scrollbar": [{
path: "hScrollBarAlwaysVisible"
}, {
path: "vScrollBarAlwaysVisible"
}],
"Animate scrolling": {
path: "animatedScroll"
},
"Show Gutter": {
path: "showGutter"
},
"Show Line Numbers": {
path: "showLineNumbers"
},
"Relative Line Numbers": {
path: "relativeLineNumbers"
},
"Fixed Gutter Width": {
path: "fixedWidthGutter"
},
"Show Print Margin": [{
path: "showPrintMargin"
}, {
type: "number",
path: "printMarginColumn"
}],
"Indented Soft Wrap": {
path: "indentedSoftWrap"
},
"Highlight selected word": {
path: "highlightSelectedWord"
},
"Fade Fold Widgets": {
path: "fadeFoldWidgets"
},
"Use textarea for IME": {
path: "useTextareaForIME"
},
"Merge Undo Deltas": {
path: "mergeUndoDeltas",
items: [
{ caption : "Always", value : "always" },
{ caption : "Never", value : "false" },
{ caption : "Timed", value : "true" }
]
},
"Elastic Tabstops": {
path: "useElasticTabstops"
},
"Incremental Search": {
path: "useIncrementalSearch"
},
"Read-only": {
path: "readOnly"
},
"Copy without selection": {
path: "copyWithEmptySelection"
},
"Live Autocompletion": {
path: "enableLiveAutocompletion"
}
}
};
var OptionPanel = function(editor, element) {
this.editor = editor;
this.container = element || document.createElement("div");
this.groups = [];
this.options = {};
};
(function() {
oop.implement(this, EventEmitter);
this.add = function(config) {
if (config.Main)
oop.mixin(optionGroups.Main, config.Main);
if (config.More)
oop.mixin(optionGroups.More, config.More);
};
this.render = function() {
this.container.innerHTML = "";
buildDom(["table", {id: "controls"},
this.renderOptionGroup(optionGroups.Main),
["tr", null, ["td", {colspan: 2},
["table", {id: "more-controls"},
this.renderOptionGroup(optionGroups.More)
]
]]
], this.container);
};
this.renderOptionGroup = function(group) {
return Object.keys(group).map(function(key, i) {
var item = group[key];
if (!item.position)
item.position = i / 10000;
if (!item.label)
item.label = key;
return item;
}).sort(function(a, b) {
return a.position - b.position;
}).map(function(item) {
return this.renderOption(item.label, item);
}, this);
};
this.renderOptionControl = function(key, option) {
var self = this;
if (Array.isArray(option)) {
return option.map(function(x) {
return self.renderOptionControl(key, x);
});
}
var control;
var value = self.getOption(option);
if (option.values && option.type != "checkbox") {
if (typeof option.values == "string")
option.values = option.values.split("|");
option.items = option.values.map(function(v) {
return { value: v, name: v };
});
}
if (option.type == "buttonBar") {
control = ["div", option.items.map(function(item) {
return ["button", {
value: item.value,
ace_selected_button: value == item.value,
onclick: function() {
self.setOption(option, item.value);
var nodes = this.parentNode.querySelectorAll("[ace_selected_button]");
for (var i = 0; i < nodes.length; i++) {
nodes[i].removeAttribute("ace_selected_button");
}
this.setAttribute("ace_selected_button", true);
}
}, item.desc || item.caption || item.name];
})];
} else if (option.type == "number") {
control = ["input", {type: "number", value: value || option.defaultValue, style:"width:3em", oninput: function() {
self.setOption(option, parseInt(this.value));
}}];
if (option.defaults) {
control = [control, option.defaults.map(function(item) {
return ["button", {onclick: function() {
var input = this.parentNode.firstChild;
input.value = item.value;
input.oninput();
}}, item.caption];
})];
}
} else if (option.items) {
var buildItems = function(items) {
return items.map(function(item) {
return ["option", { value: item.value || item.name }, item.desc || item.caption || item.name];
});
};
var items = Array.isArray(option.items)
? buildItems(option.items)
: Object.keys(option.items).map(function(key) {
return ["optgroup", {"label": key}, buildItems(option.items[key])];
});
control = ["select", { id: key, value: value, onchange: function() {
self.setOption(option, this.value);
} }, items];
} else {
if (typeof option.values == "string")
option.values = option.values.split("|");
if (option.values) value = value == option.values[1];
control = ["input", { type: "checkbox", id: key, checked: value || null, onchange: function() {
var value = this.checked;
if (option.values) value = option.values[value ? 1 : 0];
self.setOption(option, value);
}}];
if (option.type == "checkedNumber") {
control = [control, []];
}
}
return control;
};
this.renderOption = function(key, option) {
if (option.path && !option.onchange && !this.editor.$options[option.path])
return;
this.options[option.path] = option;
var safeKey = "-" + option.path;
var control = this.renderOptionControl(safeKey, option);
return ["tr", {class: "ace_optionsMenuEntry"}, ["td",
["label", {for: safeKey}, key]
], ["td", control]];
};
this.setOption = function(option, value) {
if (typeof option == "string")
option = this.options[option];
if (value == "false") value = false;
if (value == "true") value = true;
if (value == "null") value = null;
if (value == "undefined") value = undefined;
if (typeof value == "string" && parseFloat(value).toString() == value)
value = parseFloat(value);
if (option.onchange)
option.onchange(value);
else if (option.path)
this.editor.setOption(option.path, value);
this._signal("setOption", {name: option.path, value: value});
};
this.getOption = function(option) {
if (option.getValue)
return option.getValue();
return this.editor.getOption(option.path);
};
}).call(OptionPanel.prototype);
exports.OptionPanel = OptionPanel;
}); (function() {
window.require(["ace/ext/options"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
|
#!/usr/bin/env node
const user = {
name: '王顶',
age: 41,
qq: '408542507'
};
const log = console.log;
// 三种占位符
log('name: %s', user.name); // 字符串类型
log('age: %d', user.age); // 整数类型
log('JSON: %j', user); // 对象类型
log('qq: %s', user.qq); // 输出方式一:占位符输出
log('qq:', user.qq); // 输出方式二:逗号间隔,多变量输出
log('qq: ' + user.qq); // 输出方式三:拼接字符串输出
log(`qq: ${user.qq}`); // 输出方式四:模板字符串输出
console.table(user);
console.error('Error! something wrong!');
|
import { errorHandler } from './error';
import { headerSet } from '../util/httpHeaders';
import * as util from '../util/requestUrlUtil';
let path = '';
let base = '';
const cType = 'application/json'
let cj = {};
var friends = [];
const groupHandler = (req, res) => {
base = util.getBaseUrl(req)
let href = util.getUrlByAppendPath(req);
let parentUrl = util.getParentUrl(req);
cj.collection = {};
cj.collection.version = "1.0";
cj.collection.href = href;
cj.collection.links = [];
cj.collection.links.push({ 'rel': 'up', 'href': parentUrl });
cj.collection.links.push({ 'rel': 'template', 'href': href + '/template' });
cj.collection.links.push({ 'rel': 'list', 'href': href + '/list' });
res.status(200).set(headerSet).send(JSON.stringify(cj));
}
const groupListHandler = (req, res, result) => {
base = util.getBaseUrl(req)
let href = util.getUrlByAppendPath(req);
let parentUrl = util.getParentUrl(req);
cj.collection = {};
cj.collection.version = "1.0";
cj.collection.href = href;
cj.collection.links = [];
cj.collection.links.push({ 'rel': 'up', 'href': parentUrl });
cj.collection.links.push({ 'rel': 'template', 'href': parentUrl + '/template' });
cj.collection.items = [];
result.map((element) => {
cj.collection.items.push({
href: base + '/group' + '/' + element.idx,
data: [
{
"name": "name",
"value": element.name,
"prompt": "group name"
}
]
});
});
res.status(200).set(headerSet).send(JSON.stringify(cj));
}
const groupDetailHandler = (req, res, result) => {
base = util.getBaseUrl(req)
let href = util.getUrlByAppendPath(req);
let parentUrl = util.getParentUrl(req);
cj.collection = {};
cj.collection.version = "1.0";
cj.collection.href = href;
cj.collection.links = [];
cj.collection.links.push({ 'rel': 'up', 'href': parentUrl });
cj.collection.links.push({ 'rel': 'template', 'href': parentUrl + '/template' });
cj.collection.items = [];
result.map((element) => {
cj.collection.items.push({
href: base + '/group' + '/' + element.idx,
data: [
{
"name": "name",
"value": element.name,
"prompt": "group name"
},
{
"name": "created",
"value": element.created,
"prompt": "created date"
},
{
"name": "selected",
"value": element.selected ? true : false,
"prompt": "show selected"
}
]
});
});
res.status(200).set(headerSet).send(JSON.stringify(cj));
}
const groupTemplateHandler = (req, res) => {
base = util.getBaseUrl(req)
let href = util.getUrlByAppendPath(req);
let parentUrl = util.getParentUrl(req);
cj.collection = {};
cj.collection.version = "1.0";
cj.collection.href = href;
cj.collection.links = [];
cj.collection.links.push({ 'rel': 'up', 'href': parentUrl });
var template = {};
var item = {};
template.data = [];
item = {};
item.name = 'name';
item.value = '';
item.prompt = 'group name';
template.data.push(item);
item = {};
item.name = 'selected';
item.value = true;
item.prompt = 'show selected';
template.data.push(item);
cj.collection.template = template;
res.status(200).set(headerSet).send(JSON.stringify(cj));
}
const createGroupFromTemplate = (template) => {
let group = {};
let data = template.template.data;
data.map((element, index) => {
group[element.name] = element.value;
});
return group;
}
export {
groupHandler,
groupListHandler,
groupDetailHandler,
groupTemplateHandler,
createGroupFromTemplate
};
|
"use strict";
var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
// TODO springbokjs-validator
/*
S.extendPrototype(Validator, {
validParams() {
this.error = function(){ throw S.HttpError.notFound();};
},
error(msg) {
this._errors.push(msg);
},
getErrors() {
return this._errors;
},
hasErrors() {
return !!this._errors;
},
isValid() {
return !this._errors;
}
});
*/
var ParamValueValidator = (function () {
function ParamValueValidator(validator, name, value) {
_classCallCheck(this, ParamValueValidator);
this.validator = validator;
this.name = name;
this.value = value;
}
_createClass(ParamValueValidator, {
_error: {
value: function _error(key) {
this.validator._error(this.name, key, this.value);
}
}
});
return ParamValueValidator;
})();
var ParamValueStringValidator = (function (_ParamValueValidator) {
function ParamValueStringValidator() {
_classCallCheck(this, ParamValueStringValidator);
if (_ParamValueValidator != null) {
_ParamValueValidator.apply(this, arguments);
}
}
_inherits(ParamValueStringValidator, _ParamValueValidator);
_createClass(ParamValueStringValidator, {
notEmpty: {
value: function notEmpty() {
if (this.value == null || S.string.isEmpty(this.value)) {
this._error("notEmpty");
}
return this;
}
}
});
return ParamValueStringValidator;
})(ParamValueValidator);
/*
class ParamValueModelValidator extends ParamValueValidator {
required() {
if (this.value == null) {
this._error('required');
}
return this;
}
valid(fieldsRequired) {
if (this.value == null) {
return this;
}
if (S.isString(fieldsRequired)) {
fieldsRequired = fieldsRequired.split(' ');
}
S.forEach(this.value.constructor.Fields, (name, fModel) => {
var value = this.value[name];
if (fieldsRequired) {
if(S.array.has(fieldsRequired, name) && value == null) {
this._error('required');
}
} else {
if (value == null && fModel[1] && fModel[1].required) {
this._error('required');
}
}
//TODO ...
});
return this;
}
}
*/
var ParamValidator = (function () {
function ParamValidator(request) {
_classCallCheck(this, ParamValidator);
this.request = request;
}
_createClass(ParamValidator, {
_error: {
value: function _error(name, key, value) {
if (!this._errors) {
this._errors = {};
}
this._errors[name] = { error: key, value: value };
}
},
getErrors: {
value: function getErrors() {
return this._errors;
}
},
hasErrors: {
value: function hasErrors() {
return !!this._errors;
}
},
isValid: {
value: function isValid() {
return !this._errors;
}
},
string: {
value: function string(name, position) {
return new ParamValueStringValidator(this, name, this.request.param(name, position));
}
/*int(name, position) {
return new ParamValueIntValidator(this, name, this.request.param(name, position));
}
model(modelName, name) {
name = name || S.string.lcFirst(modelName);
console.log('paramvalidator model', modelName, M[modelName]);
var data = this.request.getOrPostParam(name);
return new ParamValueModelValidator(this, name, !data ? null : new M[modelName](data));
}*/
}
});
return ParamValidator;
})();
var ParamValidatorValid = (function (_ParamValidator) {
function ParamValidatorValid() {
_classCallCheck(this, ParamValidatorValid);
if (_ParamValidator != null) {
_ParamValidator.apply(this, arguments);
}
}
_inherits(ParamValidatorValid, _ParamValidator);
_createClass(ParamValidatorValid, {
_error: {
value: function _error() {
/* #if DEV */
console.warn("Invalid params: ", arguments, "\nRoute=", this.request.route, "\nGET=", this.request.query, "\nBody=", this.request.body);
/* #/if */
throw S.HttpError.notFound();
}
}
});
return ParamValidatorValid;
})(ParamValidator);
module.exports = {
requestMethods: {
param: function param(name, position) {
return this.namedParam(name) || position && this.otherParam(position) || this.paramGET(name);
},
namedParam: function namedParam(name) {
var namedParams = this.route.namedParams;
return namedParams && namedParams.get(name);
},
otherParam: function otherParam(position) {
var otherParams = this.route.otherParams;
return otherParams && otherParams[position - 1];
},
paramGET: function paramGET(name) {
var query = this.query;
return query && query[name];
},
paramGETorPOST: function paramGETorPOST(name) {
return this.body[name] !== undefined ? this.body[name] : this.query[name];
},
validator: function validator() {
return new ParamValidator(this);
},
validParams: function validParams() {
return new ParamValidatorValid(this);
}
}
};
//# sourceMappingURL=Validator.js.map
|
const models = require('../../models/models.js');
const uuid = require('uuid');
const config_service = require('../../lib/configService.js');
const config = config_service.get_config();
const debug = require('debug')('idm:api-authenticate');
const user_api_controller = require('../../controllers/api/users.js');
const pep_proxy_api_controller = require('../../controllers/api/pep_proxies.js');
// Middleware to see if the token correspond to user
const is_user = function (req, res, next) {
if (req.token_owner._modelOptions.tableName === 'user') {
next();
} else {
res.status(403).json({
error: {
message: 'User not allow to perform the action',
code: 403,
title: 'Forbidden'
}
});
}
};
// Middleware to check users token
const validate_token = function (req, res, next) {
debug(' --> validate_token');
check_validate_token_request(req)
.then(function (token_id) {
return search_token_owner(token_id);
})
.then(function (agent) {
req.token_owner = agent;
next();
})
.catch(function (error) {
debug('Error: ' + error);
if (!error.error) {
error = {
error: {
message: 'Internal error',
code: 500,
title: 'Internal error'
}
};
}
res.status(error.error.code).json(error);
});
};
// Function to check if parameters exist in request
function check_validate_token_request(req) {
const tokenvalue = req.headers.authorization
? req.headers.authorization.split('Bearer ')[1]
: req.headers['x-auth-token'];
return new Promise(function (resolve, reject) {
switch (true) {
case ['POST', 'PATCH', 'PUT'].includes(req.method) &&
(!req.headers['content-type'] || !req.headers['content-type'].startsWith('application/json')):
reject({
error: {
message: 'Missing parameter: header Content-Type: application/json',
code: 400,
title: 'Bad Request'
}
});
break;
case !req.headers.authorization && !req.headers['x-auth-token']:
reject({
error: {
message: 'Expecting to find X-Auth-token/Authorization in requests',
code: 400,
title: 'Bad Request'
}
});
break;
default:
resolve(tokenvalue);
}
});
}
// DELETE /v1/auth/tokens -- Delete token
const delete_token = function (req, res) {
debug(' --> delete_token');
check_headers_request(req)
.then(function (tokens) {
// Searc Auth token
const search_auth_token = search_token(tokens.auth);
// Search Subject token
const search_subj_token = search_token(tokens.subject);
return Promise.all([search_auth_token, search_subj_token]);
})
.then(function (values) {
return check_requested_tokens(values[0], values[1]);
})
.then(function (token) {
return token.destroy();
})
.then(function () {
res.status(204).json('Appication ' + req.params.application_id + ' destroyed');
})
.catch(function (error) {
debug('Error: ' + error);
if (!error.error) {
error = {
error: {
message: 'Internal error',
code: 500,
title: 'Internal error'
}
};
}
res.status(error.error.code).json(error);
});
};
// GET /v1/auth/tokens -- Get info from a token
const info_token = function (req, res) {
debug(' --> info_token');
check_headers_request(req)
.then(function (tokens) {
// Searc Auth token
const search_auth_token = search_token(tokens.auth);
// Search Subject token
const search_subj_token = search_token(tokens.subject);
return Promise.all([search_auth_token, search_subj_token]);
})
.then(function (values) {
return check_requested_tokens(values[0], values[1]);
})
.then(function (token) {
res.status(200).json(token);
})
.catch(function (error) {
// Log the actual error to the debug log
debug('Error: ' + error);
// Always return the same 401 - Unauthorized error to the user.
// This avoids information leakage.
if (!error.error || error.error.code !== 401) {
error = {
error: {
message: 'Invalid email or password',
code: 401,
title: 'Unauthorized'
}
};
}
res.status(error.error.code).json(error);
});
};
// Function to check if auth and subject token are valid
function check_requested_tokens(auth_token_info, subj_token_info) {
return new Promise(function (resolve, reject) {
if (!auth_token_info) {
reject({
error: {
message: 'Auth Token not found',
code: 404,
title: 'Not Found'
}
});
}
if (!subj_token_info) {
reject({
error: {
message: 'Subject Token not found',
code: 404,
title: 'Not Found'
}
});
}
if (new Date().getTime() > auth_token_info.expires.getTime()) {
reject({
error: {
message: 'Auth Token has expired',
code: 401,
title: 'Unauthorized'
}
});
}
if (auth_token_info.user_id && subj_token_info.user_id) {
if (auth_token_info.user_id === subj_token_info.user_id || auth_token_info.User.admin) {
delete subj_token_info.dataValues.pep_proxy_id;
delete subj_token_info.dataValues.user_id;
delete subj_token_info.dataValues.PepProxy;
resolve(subj_token_info);
} else {
reject({
error: {
message: 'User must be admin or owner of the two tokens',
code: 403,
title: 'Forbidden'
}
});
}
} else if (auth_token_info.pep_proxy_id && subj_token_info.pep_proxy_id) {
if (auth_token_info.pep_proxy_id !== subj_token_info.pep_proxy_id) {
reject({
error: {
message: 'Pep Proxy must be owner of the two tokens',
code: 403,
title: 'Forbidden'
}
});
}
delete subj_token_info.dataValues.pep_proxy_id;
delete subj_token_info.dataValues.user_id;
delete subj_token_info.dataValues.User;
resolve(subj_token_info);
} else {
reject({
error: {
message: 'Subject and auth token are not owned by the same entity',
code: 403,
title: 'Forbidden'
}
});
}
});
}
// Function to check if parameters exist in request
function check_headers_request(req) {
const tokenvalue = req.headers.authorization
? req.headers.authorization.split('Bearer ')[1]
: req.headers['x-auth-token'];
return new Promise(function (resolve, reject) {
switch (true) {
case !req.headers['x-subject-token']:
reject({
error: {
message: 'Expecting to find X-Subject-token in requests',
code: 400,
title: 'Bad Request'
}
});
break;
case !req.headers.authorization && !req.headers['x-auth-token']:
reject({
error: {
message: 'Expecting to find X-Auth-token/Authorization in requests',
code: 400,
title: 'Bad Request'
}
});
break;
default:
resolve({
auth: tokenvalue,
subject: req.headers['x-subject-token']
});
}
});
}
// Function to search token in database
function search_token(token_id) {
return models.auth_token
.findOne({
where: { access_token: token_id },
include: [
{
model: models.user,
attributes: ['id', 'username', 'email', 'date_password', 'enabled', 'admin']
},
{
model: models.pep_proxy,
attributes: ['id']
}
]
})
.then(function (token_row) {
return Promise.resolve(token_row);
})
.catch(function (error) {
return Promise.reject(error);
});
}
// POST /v1/auth/tokens -- Create a token
const create_token = function (req, res) {
debug(' --> create_token');
let response_methods = [];
const methods = [];
return check_create_token_request(req)
.then(function (checked) {
response_methods = checked;
// Check what methods are included in the request
if (checked.includes('password')) {
methods.push(search_identity(req.body.name, req.body.password));
}
if (checked.includes('token')) {
methods.push(search_token_owner(req.body.token));
}
return Promise.all(methods);
})
.then(function (values) {
if (methods.length === 2) {
if (values[0].id !== values[1].id) {
return Promise.reject({
error: {
message: 'Token not correspond to user',
code: 401,
title: 'Unauthorized'
}
});
}
}
return values;
})
.then(function (authenticated) {
const token_id = uuid.v4();
const expires = new Date(new Date().getTime() + 1000 * config.api.token_lifetime);
let row = { access_token: token_id, expires, valid: true };
if (authenticated[0]._modelOptions.tableName === 'user') {
row = Object.assign({}, row, { user_id: authenticated[0].id });
} else {
row = Object.assign({}, row, { pep_proxy_id: authenticated[0].id });
}
models.auth_token
.create(row)
.then(function () {
const response_body = {
token: {
methods: response_methods,
expires_at: expires
},
idm_authorization_config: {
level: config.authorization.level,
authzforce: config.authorization.authzforce.enabled
}
};
res.setHeader('X-Subject-Token', token_id);
res.status(201).json(response_body);
})
.catch(function (error) {
debug('Error: ', error);
res.status(500).json({
error: {
message: 'Internal error',
code: 500,
title: 'Internal error'
}
});
});
})
.catch(function (error) {
// Log the actual error to the debug log
debug('Error: ' + error);
// If an actual 401 has been raised, use the existing message.
// But always return a 401 - Unauthorized error to the user.
// This avoid information leakage.
if (!error.error || error.error.code !== 401) {
error = {
error: {
message: 'Invalid email or password',
code: 401,
title: 'Unauthorized'
}
};
}
res.status(error.error.code).json(error);
});
};
// Function to check if parameters exist in request
function check_create_token_request(req) {
return new Promise(function (resolve, reject) {
if (!req.headers['content-type'] || !req.headers['content-type'].startsWith('application/json')) {
reject({
error: {
message: 'Missing parameter: header Content-Type: application/json',
code: 400,
title: 'Bad Request'
}
});
}
const methods = [];
if (req.body.name && req.body.password) {
methods.push('password');
}
if (req.body.token) {
methods.push('token');
}
if (methods.length <= 0) {
reject({
error: {
message: 'Expecting to find name and password or token in body request',
code: 400,
title: 'Bad Request'
}
});
} else {
resolve(methods);
}
});
}
// Function to check password method parameter for identity
function search_identity(name, password) {
return new Promise(function (resolve, reject) {
models.helpers
.search_pep_or_user(name)
.then(function (identity) {
if (identity.length <= 0) {
reject({
error: { message: 'User not found', code: 404, title: 'Not Found' }
});
} else if (identity[0].source === 'user') {
authenticate_user(name, password)
.then(function (values) {
resolve(values);
})
.catch(function (error) {
reject(error);
});
} else if (identity[0].source === 'pep_proxy') {
authenticate_pep_proxy(name, password)
.then(function (values) {
resolve(values);
})
.catch(function (error) {
reject(error);
});
}
})
.catch(function (error) {
reject(error);
});
});
}
// Authenticate user
function authenticate_user(email, password) {
return new Promise(function (resolve, reject) {
user_api_controller.authenticate(email, password, function (error, user) {
if (error) {
if (error.message === 'invalid') {
reject({
error: {
message: 'Invalid email or password',
code: 401,
title: 'Unauthorized'
}
});
} else {
reject({
error: {
message: 'Internal error',
code: 500,
title: 'Internal error'
}
});
}
} else {
resolve(user);
}
});
});
}
// Authenticate pep proxy
function authenticate_pep_proxy(id, password) {
return new Promise(function (resolve, reject) {
pep_proxy_api_controller.authenticate(id, password, function (error, pep_proxy) {
if (error) {
if (error.message === 'invalid') {
reject({
error: {
message: 'Invalid id or password',
code: 401,
title: 'Unauthorized'
}
});
} else {
reject({
error: {
message: 'Internal error',
code: 500,
title: 'Internal error'
}
});
}
} else {
resolve(pep_proxy);
}
});
});
}
// Function to search token in database
function search_token_owner(token_id) {
return models.auth_token
.findOne({
where: { access_token: token_id },
include: [
{
model: models.user,
attributes: ['id', 'username', 'email', 'date_password', 'enabled', 'admin']
},
{
model: models.pep_proxy,
attributes: ['id']
}
]
})
.then(function (token_row) {
if (token_row) {
if (new Date().getTime() > token_row.expires.getTime()) {
return Promise.reject({
error: {
message: 'Token has expired',
code: 401,
title: 'Unauthorized'
}
});
}
const token_owner = token_row.User ? token_row.User : token_row.PepProxy;
return Promise.resolve(token_owner);
}
return Promise.reject({
error: { message: 'Token not found', code: 404, title: 'Not Found' }
});
})
.catch(function (error) {
return Promise.reject(error);
});
}
module.exports = {
validate_token,
create_token,
info_token,
is_user,
delete_token
};
|
'use strict';
const Ftp = require('ftp');
class FtpClient {
constructor(options) {
this.options = options;
}
connect() {
this.ftp = new Ftp();
return new Promise((resolve, reject) => {
let ready = false;
this.ftp.on('ready', () => {
ready = true;
resolve();
});
this.ftp.on('error', (error) => {
if (!ready) reject(error);
});
this.ftp.connect(this.options);
});
}
cwd(path) {
return new Promise((resolve, reject) => {
this.ftp.cwd(path, (error) => {
error ? reject(error) : resolve();
});
});
}
cwdUpdatesRoot() {
return this.cwd(this.options.remotePath);
}
mkDirNoError(name) {
return new Promise((resolve) => {
this.ftp.mkdir(name, resolve);
});
}
putFile(source, remotePath) {
return new Promise((resolve, reject) => {
this.ftp.put(source, remotePath, (error) => {
error ? reject(error) : resolve();
});
});
}
list() {
return new Promise((resolve, reject) => {
this.ftp.list(this.options.remotePath, (error, list) => {
error ? reject(error) : resolve(list);
});
});
}
rmDir(remotePath) {
return new Promise((resolve, reject) => {
this.ftp.rmdir(remotePath, true, (error) => {
error ? reject(error) : resolve();
});
});
}
close() {
this.ftp.end();
}
}
module.exports = FtpClient;
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.DriverDOM = {}));
}(this, (function (exports) {
var didWarnInvalidHydration = false;
function warnForReplacedHydratebleElement(parentNode, clientNode, serverNode) {
{
if (didWarnInvalidHydration) {
return;
} // should not warn for replace comment, bescause it may be a placeholder from server
if (serverNode.nodeType === 8) {
return;
}
didWarnInvalidHydration = true;
warning('Expected server HTML to contain a matching %s in %s, but got %s.', getNodeName(clientNode), getNodeName(parentNode), getNodeName(serverNode));
}
}
function warnForDeletedHydratableElement(parentNode, child) {
{
if (didWarnInvalidHydration) {
return;
}
didWarnInvalidHydration = true;
warning('Did not expect server HTML to contain a %s in %s.', getNodeName(child), getNodeName(parentNode));
}
}
function warnForInsertedHydratedElement(parentNode, node) {
{
if (didWarnInvalidHydration) {
return;
}
didWarnInvalidHydration = true;
warning('Expected server HTML to contain a matching %s in %s.', getNodeName(node), getNodeName(parentNode));
}
}
/**
* Concat tagName、 id and class info to help locate a node
* @param {*} node HTMLElement
* @returns {string} for example: <div#home.rax-view.home>
*/
function getNodeName(node) {
// text node don`t have tagName
if (!node.tagName) {
return node.nodeName;
}
var name = node.tagName.toLowerCase();
var id = node.id ? '#' + node.id : '';
var classStr = node.className || '';
var classList = classStr.split(' ').map(function (className) {
return className ? '.' + className : '';
});
return "<" + name + id + classList.join('') + ">";
}
var warning = function warning() {};
{
warning = function warning(template) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (typeof console !== 'undefined') {
var argsWithFormat = args.map(function (item) {
return '' + item;
});
argsWithFormat.unshift('Warning: ' + template); // Don't use spread (or .apply) directly because it breaks IE9
Function.prototype.apply.call(console.error, console, argsWithFormat);
} // For works in DevTools when enable `Pause on caught exceptions`
// that can find the component where caused this warning
try {
var argIndex = 0;
var message = 'Warning: ' + template.replace(/%s/g, function () {
return args[argIndex++];
});
throw new Error(message);
} catch (e) {}
};
}
/**
* Driver for Web DOM
**/
var RPX_REG = /[-+]?\d*\.?\d+(rpx)/g; // opacity -> opa
// fontWeight -> ntw
// lineHeight|lineClamp -> ne[ch]
// flex|flexGrow|flexPositive|flexShrink|flexNegative|boxFlex|boxFlexGroup|zIndex -> ex(?:s|g|n|p|$)
// order -> ^ord
// zoom -> zoo
// gridArea|gridRow|gridRowEnd|gridRowSpan|gridRowStart|gridColumn|gridColumnEnd|gridColumnSpan|gridColumnStart -> grid
// columnCount -> mnc
// tabSize -> bs
// orphans -> orp
// windows -> ows
// animationIterationCount -> onit
// borderImageOutset|borderImageSlice|borderImageWidth -> erim
var NON_DIMENSIONAL_REG = /opa|ntw|ne[ch]|ex(?:s|g|n|p|$)|^ord|zoo|grid|orp|ows|mnc|^columns$|bs|erim|onit/i;
var EVENT_PREFIX_REG = /^on[A-Z]/;
var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';
var HTML = '__html';
var INNER_HTML = 'innerHTML';
var CLASS_NAME = 'className';
var CLASS = 'class';
var STYLE = 'style';
var CHILDREN = 'children';
var TEXT_CONTENT_ATTR = 'textContent';
var CREATE_ELEMENT = 'createElement';
var CREATE_COMMENT = 'createComment';
var CREATE_TEXT_NODE = 'createTextNode';
var SET_ATTRIBUTE = 'setAttribute';
var REMOVE_ATTRIBUTE = 'removeAttribute';
var SVG_NS = 'http://www.w3.org/2000/svg';
var TEXT_NODE = 3;
var COMMENT_NODE = 8;
var TEXT_SPLIT_COMMENT = '|';
var EMPTY = '';
var HYDRATION_INDEX = '__i';
var HYDRATION_APPEND = '__a';
var WITH_INNERHTML = '__h';
var tagNamePrefix = EMPTY; // Flag indicating if the diff is currently within an SVG
var isSVGMode = false;
var isHydrating = false;
var viewportWidth = 750;
var unitPrecision = 4;
/**
* Set viewport width.
* @param viewport {Number} Viewport width, default to 750.
*/
function setViewportWidth(viewport) {
viewportWidth = viewport;
}
/**
* Set unit precision.
* @param n {Number} Unit precision, default to 4.
*/
function setUnitPrecision(n) {
unitPrecision = n;
}
/**
* Set a function to transform unit of pixel,
* default to passthrough.
* @param {Function} transformer function
*/
function setDecimalPixelTransformer(transformer) {
}
function unitTransformer(n) {
return toFixed(parseFloat(n) / (viewportWidth / 100), unitPrecision) + 'vw';
}
function toFixed(number, precision) {
var multiplier = Math.pow(10, precision + 1);
var wholeNumber = Math.floor(number * multiplier);
return Math.round(wholeNumber / 10) * 10 / multiplier;
}
/**
* Create a cached version of a pure function.
*/
function cached(fn) {
var cache = Object.create(null);
return function cachedFn(str) {
return cache[str] || (cache[str] = fn(str));
};
}
function calcRpxToVw(value) {
return value.replace(RPX_REG, unitTransformer);
}
function isRpx(str) {
return RPX_REG.test(str);
} // Cache the convert fn.
var convertUnit = cached(function (value) {
return isRpx(value) ? calcRpxToVw(value) : value;
});
/**
* Camelize CSS property.
* Vendor prefixes should begin with a capital letter.
* For example:
* background-color -> backgroundColor
* -webkit-transition -> webkitTransition
*/
var camelizeStyleName = cached(function (name) {
return name.replace(/-([a-z])/gi, function (s, g) {
return g.toUpperCase();
});
});
var isDimensionalProp = cached(function (prop) {
return !NON_DIMENSIONAL_REG.test(prop);
});
var isEventProp = cached(function (prop) {
return EVENT_PREFIX_REG.test(prop);
});
function setTagNamePrefix(prefix) {
tagNamePrefix = prefix;
}
function createBody() {
return document.body;
}
function createEmpty(component) {
var parent = component._parent;
var node;
if (isHydrating) {
var hydrationChild = findHydrationChild(parent);
if (hydrationChild) {
if (hydrationChild.nodeType === COMMENT_NODE) {
return hydrationChild;
} else {
node = document[CREATE_COMMENT](EMPTY);
replaceChild(node, hydrationChild, parent);
}
} else {
node = document[CREATE_COMMENT](EMPTY);
node[HYDRATION_APPEND] = true;
}
} else {
node = document[CREATE_COMMENT](EMPTY);
}
return node;
}
function createText(text, component) {
var parent = component._parent;
var node;
if (isHydrating) {
var hydrationChild = findHydrationChild(parent);
if (hydrationChild) {
if (hydrationChild.nodeType === TEXT_NODE) {
if (text !== hydrationChild[TEXT_CONTENT_ATTR]) {
hydrationChild[TEXT_CONTENT_ATTR] = text;
}
return hydrationChild;
} else {
node = document[CREATE_TEXT_NODE](text);
replaceChild(node, hydrationChild, parent);
}
} else {
node = document[CREATE_TEXT_NODE](text);
node[HYDRATION_APPEND] = true;
}
} else {
node = document[CREATE_TEXT_NODE](text);
}
return node;
}
function updateText(node, text) {
node[TEXT_CONTENT_ATTR] = text;
}
function findHydrationChild(parent) {
var childNodes = parent.childNodes;
if (parent[HYDRATION_INDEX] == null) {
parent[HYDRATION_INDEX] = 0;
}
var child = childNodes[parent[HYDRATION_INDEX]++]; // If child is an comment node for spliting text node, use the next node.
if (child && child.nodeType === COMMENT_NODE && child.data === TEXT_SPLIT_COMMENT) {
return childNodes[parent[HYDRATION_INDEX]++];
} else {
return child;
}
}
/**
* @param {string} type node type
* @param {object} props elemement properties
* @param {object} component component instance
* @param {boolean} __shouldConvertUnitlessToRpx should add unit when missing
* @param {boolean} __shouldConvertRpxToVw should transfrom rpx to vw
*/
function createElement(type, props, component, __shouldConvertUnitlessToRpx, __shouldConvertRpxToVw) {
if (__shouldConvertRpxToVw === void 0) {
__shouldConvertRpxToVw = true;
}
var parent = component._parent;
isSVGMode = type === 'svg' || parent && parent.namespaceURI === SVG_NS;
var node;
var hydrationChild = null;
function createNode() {
if (isSVGMode) {
node = document.createElementNS(SVG_NS, type);
} else if (tagNamePrefix) {
var _tagNamePrefix = typeof _tagNamePrefix === 'function' ? _tagNamePrefix(type) : _tagNamePrefix;
node = document[CREATE_ELEMENT](_tagNamePrefix + type);
} else {
node = document[CREATE_ELEMENT](type);
}
}
if (isHydrating) {
hydrationChild = findHydrationChild(parent);
if (hydrationChild) {
if (type === hydrationChild.nodeName.toLowerCase()) {
for (var attributes = hydrationChild.attributes, i = attributes.length; i--;) {
var attribute = attributes[i];
var attributeName = attribute.name;
var propValue = props[attributeName];
if ( // The class or className prop all not in props
attributeName === CLASS && props[CLASS_NAME] == null && propValue == null || // The style prop is empty object or not in props
attributeName === STYLE && (propValue == null || Object.keys(propValue).length === 0) || // Remove rendered node attribute that not existed
attributeName !== CLASS && attributeName !== STYLE && propValue == null) {
hydrationChild[REMOVE_ATTRIBUTE](attributeName);
continue;
}
if (attributeName === STYLE) {
// Remove invalid style prop, and direct reset style to child avoid diff style
// Set style to empty will change the index of style, so here need to traverse style backwards
for (var l = hydrationChild.style.length; 0 < l; l--) {
// Prop name get from node style is hyphenated, eg: background-color
var stylePropName = hydrationChild.style[l - 1];
var camelizedStyleName = camelizeStyleName(stylePropName);
if (propValue[camelizedStyleName] == null) {
hydrationChild.style[camelizedStyleName] = EMPTY;
}
}
}
}
node = hydrationChild;
} else {
createNode();
replaceChild(node, hydrationChild, parent);
{
warnForReplacedHydratebleElement(parent, node, hydrationChild);
}
}
} else {
createNode();
node[HYDRATION_APPEND] = true;
{
warnForInsertedHydratedElement(parent, node);
}
}
} else {
createNode();
}
for (var prop in props) {
var value = props[prop];
if (prop === CHILDREN) continue;
if (value != null) {
if (prop === STYLE) {
setStyle(node, value, __shouldConvertUnitlessToRpx, __shouldConvertRpxToVw);
} else if (isEventProp(prop)) {
addEventListener(node, prop.slice(2).toLowerCase(), value);
} else {
setAttribute(node, prop, value, isSVGMode);
}
}
}
return node;
}
function appendChild(node, parent) {
if (!isHydrating || node[HYDRATION_APPEND]) {
return parent.appendChild(node);
}
}
function removeChild(node, parent) {
parent = parent || node.parentNode; // Maybe has been removed when remove child
if (parent) {
parent.removeChild(node);
}
}
function replaceChild(newChild, oldChild, parent) {
parent = parent || oldChild.parentNode;
parent.replaceChild(newChild, oldChild);
}
function insertAfter(node, after, parent) {
parent = parent || after.parentNode;
var nextSibling = after.nextSibling;
if (nextSibling) {
// Performance improve when node has been existed before nextSibling
if (nextSibling !== node) {
insertBefore(node, nextSibling, parent);
}
} else {
appendChild(node, parent);
}
}
function insertBefore(node, before, parent) {
parent = parent || before.parentNode;
parent.insertBefore(node, before);
}
function addEventListener(node, eventName, eventHandler) {
return node.addEventListener(eventName, eventHandler);
}
function removeEventListener(node, eventName, eventHandler) {
return node.removeEventListener(eventName, eventHandler);
}
function removeAttribute(node, propKey) {
if (propKey === DANGEROUSLY_SET_INNER_HTML) {
return node[INNER_HTML] = null;
}
if (propKey === CLASS_NAME) propKey = CLASS;
if (propKey in node) {
try {
// Some node property is readonly when in strict mode
node[propKey] = null;
} catch (e) {}
}
node[REMOVE_ATTRIBUTE](propKey);
}
function setAttribute(node, propKey, propValue, isSvg) {
if (propKey === DANGEROUSLY_SET_INNER_HTML) {
// For reduce innerHTML operation to improve performance.
if (node[INNER_HTML] !== propValue[HTML]) {
node[INNER_HTML] = propValue[HTML];
}
node[WITH_INNERHTML] = true;
return;
}
if (propKey === CLASS_NAME) propKey = CLASS; // Prop for svg can only be set by attribute
if (!isSvg && propKey in node) {
try {
// Some node property is readonly when in strict mode
node[propKey] = propValue;
} catch (e) {
node[SET_ATTRIBUTE](propKey, propValue);
}
} else {
node[SET_ATTRIBUTE](propKey, propValue);
}
}
/**
* @param {object} node target node
* @param {object} style target node style value
* @param {boolean} __shouldConvertUnitlessToRpx
* @param {boolean} __shouldConvertRpxToVw should transfrom rpx to vw
*/
function setStyle(node, style, __shouldConvertUnitlessToRpx, __shouldConvertRpxToVw) {
if (__shouldConvertRpxToVw === void 0) {
__shouldConvertRpxToVw = true;
}
for (var prop in style) {
var value = style[prop];
var convertedValue = void 0;
if (typeof value === 'number' && isDimensionalProp(prop)) {
if (__shouldConvertUnitlessToRpx) {
convertedValue = value + 'rpx';
if (__shouldConvertRpxToVw) {
// Transfrom rpx to vw
convertedValue = convertUnit(convertedValue);
}
} else {
convertedValue = value + 'px';
}
} else {
convertedValue = __shouldConvertRpxToVw ? convertUnit(value) : value;
} // Support CSS custom properties (variables) like { --main-color: "black" }
if (prop[0] === '-' && prop[1] === '-') {
// reference: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty.
// style.setProperty do not support Camel-Case style properties.
node.style.setProperty(prop, convertedValue);
} else {
node.style[prop] = convertedValue;
}
}
}
function beforeRender(_ref) {
var hydrate = _ref.hydrate;
// Nested render may reset `isHydrating`, `recolectHydrationChild` will not work correctly after render.
if (isHydrating && !hydrate) {
{
throw new Error('Nested render is not allowed when hydrating. ' + 'If necessary, trigger render in useEffect.');
}
}
isHydrating = hydrate;
}
function recolectHydrationChild(hydrationParent) {
// Should not to compare node with dangerouslySetInnerHTML because vdomLength is alway 0
if (hydrationParent[WITH_INNERHTML]) {
return;
}
var nativeLength = hydrationParent.childNodes.length;
var vdomLength = hydrationParent[HYDRATION_INDEX] || 0;
if (nativeLength - vdomLength > 0) {
for (var i = nativeLength - 1; i >= vdomLength; i--) {
{
warnForDeletedHydratableElement(hydrationParent, hydrationParent.childNodes[i]);
}
hydrationParent.removeChild(hydrationParent.childNodes[i]);
}
}
for (var j = hydrationParent.childNodes.length - 1; j >= 0; j--) {
recolectHydrationChild(hydrationParent.childNodes[j]);
}
}
function afterRender(_ref2) {
var container = _ref2.container;
if (isHydrating) {
// Remove native node when more then vdom node
recolectHydrationChild(container);
isHydrating = false;
}
}
/**
* Remove all children from node.
* @NOTE: Optimization at web.
*/
function removeChildren(node) {
node.textContent = EMPTY;
}
exports.addEventListener = addEventListener;
exports.afterRender = afterRender;
exports.appendChild = appendChild;
exports.beforeRender = beforeRender;
exports.createBody = createBody;
exports.createElement = createElement;
exports.createEmpty = createEmpty;
exports.createText = createText;
exports.insertAfter = insertAfter;
exports.insertBefore = insertBefore;
exports.removeAttribute = removeAttribute;
exports.removeChild = removeChild;
exports.removeChildren = removeChildren;
exports.removeEventListener = removeEventListener;
exports.replaceChild = replaceChild;
exports.setAttribute = setAttribute;
exports.setDecimalPixelTransformer = setDecimalPixelTransformer;
exports.setStyle = setStyle;
exports.setTagNamePrefix = setTagNamePrefix;
exports.setUnitPrecision = setUnitPrecision;
exports.setViewportWidth = setViewportWidth;
exports.updateText = updateText;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=driver-dom.umd.js.map
|
var Layer = require('../')
var Rec2 = require('rec2')
var tape = require('tape')
tape('layer1 gets the right tiles', function (t) {
var l = new Layer({scale: 1})
var mapBounds = new Rec2().set(0, 0)
mapBounds.bound.set(1000, 1000)
console.log(l.tileRange(mapBounds))
t.deepEqual(l.minTile.toJSON(), {x:0, y:0})
t.deepEqual(l.maxTile.toJSON(), {x:1, y:1})
t.end()
})
tape('layer1 gets the right tiles - real example', function (t) {
var l = new Layer({scale: 1})
var mapBounds = new Rec2().set(298, 179)
mapBounds.bound.set(621, 501)
console.log(l.tileRange(mapBounds))
t.deepEqual(l.minTile.toJSON(), {x:0, y:0})
t.deepEqual(l.maxTile.toJSON(), {x:1, y:1})
t.end()
})
tape('layer1 gets the right tiless - real example2', function (t) {
var l = new Layer({scale: 1})
var mapBounds = new Rec2().set(-161, 159)
mapBounds.bound.set(521, 481)
console.log(l.tileRange(mapBounds))
t.deepEqual(l.minTile.toJSON(), {x:0, y:0})
t.deepEqual(l.maxTile.toJSON(), {x:1, y:0})
t.end()
})
tape('layer1 gets the right tiless - real example3', function (t) {
var l = new Layer({scale: 1})
var mapBounds = new Rec2().set(161, -341)
mapBounds.bound.set(841, 19)
console.log(l.tileRange(mapBounds))
t.deepEqual(l.minTile.toJSON(), {x:0, y:0}, 'min tile')
t.deepEqual(l.maxTile.toJSON(), {x:1, y:0}, 'max tile')
t.end()
})
tape('layer1 gets the right tiles 2', function (t) {
var l = new Layer({scale: 1})
var mapBounds = new Rec2().set(500, 500)
mapBounds.bound.set(1000, 1000)
var b = l.tileRange(mapBounds)
console.log(b)
t.deepEqual(b.minTile.toJSON(), {x:1, y:1}, 'min tile')
t.deepEqual(b.maxTile.toJSON(), {x:1, y:1}, 'max tile')
t.end()
})
tape('layer1 gets the right tiles 3', function (t) {
var l = new Layer({scale: 1})
var mapBounds = new Rec2().set(0, 0)
mapBounds.bound.set(1000, 1000)
var b = l.tileRange(mapBounds)
console.log(b)
t.deepEqual(l.minTile.toJSON(), {x:0, y:0})
t.deepEqual(l.maxTile.toJSON(), {x:1, y:1})
t.end()
})
tape('layer2', function (t) {
console.log('layer2')
var l = new Layer({scale: 2})
var mapBounds = new Rec2().set(0, 0)
mapBounds.bound.set(1000, 1000)
var b = l.tileRange(mapBounds)
t.deepEqual(b.minTile.toJSON(), {x:0, y:0})
t.deepEqual(b.maxTile.toJSON(), {x:3, y:3})
t.end()
})
tape('layer2', function (t) {
console.log('layer2')
var l = new Layer({scale: 2})
var mapBounds = new Rec2().set(250, 250)
mapBounds.bound.set(750, 750)
var b = l.tileRange(mapBounds)
t.deepEqual(b.minTile.toJSON(), {x:1, y:1})
t.deepEqual(b.maxTile.toJSON(), {x:3, y:3})
t.end()
})
|
angular.module('app')
.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ( $stateProvider, $urlRouterProvider, $locationProvider ) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
$stateProvider
.state('map', {
url: '/',
controller:'MapController',
templateUrl: 'views/map.html',
data: {
pageTitle:'Map'
}
});
}]);
|
// Action types
export const REQUEST_MAKE = 'REQUEST_MAKE';
export const REQUEST_FAILED = 'REQUEST_FAILED';
export const REQUEST_COMPLETED = 'REQUEST_COMPLETED';
// Other variables
export const REQUEST_STATUS = {
LOADING: 'LOADING',
FAILED: 'FAILED',
SUCCESS: 'SUCCESS'
};
// Action creators
export function requestMake(request_string) {
return { type: REQUEST_MAKE, request_string, request_status: REQUEST_STATUS.LOADING };
}
export function requestFailed(error_message) {
return { type: REQUEST_FAILED, error_message, request_status: REQUEST_STATUS.FAILED };
}
export function requestCompleted(result) {
return { type: REQUEST_COMPLETED, result, request_status: REQUEST_STATUS.SUCCESS };
}
|
import { runCallbacksAsync } from 'meteor/vulcan:core';
import escapeStringRegexp from 'escape-string-regexp';
import { Picker } from 'meteor/meteorhacks:picker';
import Posts from '../collection.js';
Picker.route('/out', ({ query}, req, res, next) => {
if(query.url){ // for some reason, query.url doesn't need to be decoded
/*
If the URL passed to ?url= is in plain text, any hash fragment
will get stripped out.
So we search for any post whose URL contains the current URL to get a match
even without the hash
*/
// decode url just in case
const decodedUrl = decodeURIComponent(query.url);
try {
const post = Posts.findOne({url: {$regex: escapeStringRegexp(decodedUrl)}}, {sort: {postedAt: -1, createdAt: -1}});
if (post) {
const ip = req.headers && req.headers['x-forwarded-for'] || req.connection.remoteAddress;
runCallbacksAsync('posts.click.async', post, ip);
res.writeHead(301, {'Location': query.url});
res.end();
} else {
// don't redirect if we can't find a post for that link
res.writeHead(301, {'Location': query.url});
res.end(`Invalid URL: ${query.url}`);
}
} catch (error) {
console.log('// /out error')
console.log(error)
console.log(query)
}
} else {
res.end("Please provide a URL");
}
});
|
var fs = require('fs');
var sysPath = require('path');
var colors = require('colors');
var mkdirp = require('mkdirp');
var artTemplate = require('art-template');
var childProcess = require('child_process');
var marked = require('marked');
var glob = require('glob');
var fse = require('fs-extra');
var parsers = require('../parsers');
artTemplate.config('escape', false);
artTemplate.helper('markdown', function(content) {
return marked(content);
});
artTemplate.helper('anchor', function(name) {
return name ? name.replace(/[\.\:]/g, '-') : '';
});
artTemplate.helper('txt', function(html) {
return html ? html.replace(/\<\/?[^\>]*\>/g, '') : '';
});
function doParser(cwd, filePath, ignore, compile, options, conf) {
var extName = sysPath.extname(filePath),
parser;
if (compile) {
parsers.some(function(p) {
if (p.type == compile) {
parser = p;
return true;
}
});
} else {
parsers.some(function(p) {
if (p.extNames.indexOf(extName) > -1) {
parser = p;
return true;
}
});
}
if (parser) {
var files = glob.sync(filePath, {
cwd: cwd,
ignore: ignore || []
}),
options = Object.assign({
files: files
}, conf.options[parser.type] || {}, options || {});
if (files.length) {
var contents = files.map(function(fp) {
var content = fs.readFileSync(sysPath.join(cwd, fp), 'UTF-8');
if (options.source) {
var dp = sysPath.join(conf.dest, 'static', sysPath.dirname(fp));
mkdirp.sync(dp);
fs.writeFileSync(sysPath.join(dp, sysPath.basename(fp) + '.html'), 'UTF-8');
console.log(('√ 生成文件: ' + sysPath.join(dp, sysPath.basename(fp) + '.html')).yellow);
}
return content;
});
var ret = parser.parser(contents, options, conf);
return ret;
} else {
console.log(('X ' + filePath + ' 未找到文件。').red);
}
} else {
console.log(('X ' + extName + ' 未找到编译器。').red);
}
return {};
}
module.exports = function(cwd, conf) {
conf.cwd = cwd;
conf.options = conf.options || {};
var render = artTemplate.compile(conf.templateContent);
var resources = conf.resources || {};
// build增加其他静态资源输出
var basePath = sysPath.join(process.cwd(), conf.rootDir);
var outPath = conf.dest;
fse.copySync(basePath,outPath,{filter: function(single){
const fileType = sysPath.extname(single);
if(fileType != '.md'){
return true
} else {
return false
}
}});
if (conf.pages) {
conf.pages.forEach(function(page) {
var data = {},
common = conf.common || {};
data.name = conf.name;
data.title = common.title + ' ' + page.title;
data.footer = common.footer;
data.home = common.home;
data.homeUrl = common.homeUrl;
data.navbars = common.navbars.map(function(item) {
return {
name: item.name,
url: item.url,
target: item.target || 'self',
active: item.name == conf.name
};
});
data.tabs = conf.pages.map(function(item) {
return {
name: item.name,
url: item.url,
title: item.title,
active: item.name == page.name
}
});
data.banner = page.banner;
if (page.intro) {
var introPath = sysPath.join(cwd, page.intro);
if (fs.existsSync(introPath)) {
data.intro = marked(fs.readFileSync(introPath, 'UTF-8'));
}
}
if (page.content && (!conf.buildPages.length || conf.buildPages.indexOf(page.name) > -1)) {
if (page.content.multi) {
var navs = page.content.pages.map(function(p) {
return {
name: p.name,
sub: !!p.sub,
blank: !p.content,
url: page.name + '-' + p.name + '.html'
};
});
page.content.pages.forEach(function(p, index) {
if (p.content) {
var curNavs = navs.slice(0);
data.article = doParser(cwd, p.content, p.ignore, p.compile, p.options, conf);
if (data.article.menus) {
curNavs.splice.apply(curNavs, [index + 1, 0].concat(data.article.menus.filter(function(item) {
return !item.sub;
})).map(function(item) {
item.sub = true;
return item;
}));
}
data.article.sidebars = curNavs;
data.article.name = p.name;
fs.writeFileSync(sysPath.join(conf.dest, page.name + '-' + p.name + '.html'), render(data));
console.log(('√ 生成文件: ' + sysPath.join(conf.dest, page.name + '-' + p.name + '.html')).yellow);
}
});
data.article = doParser(cwd, page.content.index, page.indexIngore, page.indexCompile, page.content.indexOptions, conf);
data.article.sidebars = navs;
} else if (typeof page.content == 'string') {
data.article = doParser(cwd, page.content, page.ignore, page.compile, page.options, conf);
if (data.article.menus && data.article.menus.length && !data.article.sidebars) {
data.article.sidebars = data.article.menus;
}
} else {
var navs = [],
blocks = [];
page.content.blocks.forEach(function(block) {
if (block.name) {
navs.push({
name: block.name,
sub: block.sub || false
});
}
if (typeof block.content == 'string') {
var ret = doParser(cwd, block.content, block.ignore, block.compile, block.options, conf);
if (block.name && !block.sub && ret.menus) {
ret.menus.forEach(function(item) {
if (!item.sub) {
navs.push({
name: item.name,
sub: true
});
}
});
}
ret.name = block.name;
ret.sub = block.sub || false;
blocks.push(ret);
} else {
blocks.push({
type: 'html',
name: block.name,
sub: false,
content: ''
});
}
});
data.article = {
type: 'block'
};
if (page.content.sidebar) {
data.article.sidebars = navs;
}
data.article.blocks = blocks;
}
fs.writeFileSync(sysPath.join(conf.dest, page.name + '.html'), render(data));
console.log(('√ 生成文件: ' + sysPath.join(conf.dest, page.name + '.html')).yellow);
}
});
}
for (var key in resources) {
try {
childProcess.execSync('cp -r ' + sysPath.join(cwd, resources[key]) + ' ' + sysPath.join(conf.dest, key));
} catch(e) {
console.log(('X 资源 ' + key + ' 复制失败').red);
console.log(e.toString().red);
}
}
};
module.exports.usage = '构建文档';
module.exports.setOptions = function(optimist) {
optimist.alias('t', 'template');
optimist.describe('t', '模板路径');
optimist.alias('p', 'page');
optimist.describe('p', '选择生成的页面,默认生成所有');
optimist.alias('w', 'watch');
optimist.describe('w', '监控文件更改,自动编译');
optimist.alias('o', 'output');
optimist.describe('o', '指定输出目录');
};
|
import React, { Component } from 'react';
import Canvas from './helpers/canvas';
import { SetDefaultCanvas, SetCanvasText, ResetCanvas, SetCanvasBorder, LoadImg } from './helpers/helpers';
import { PongInstructions, SnakeInstructions } from './helpers/instructions';
import GameHome from './game-home';
import Retrocade from '../assets/img/retrocade.jpg';
class HomeScreen extends Component {
constructor(props) {
super(props);
this.state = {
gameSelected: false,
game: null
};
}
componentDidMount() {
SetDefaultCanvas('black', 'canvas');
SetCanvasText('deeppink', 'Choose Your Game', '40px', 80, 50, 'canvas');
this.newGame('Pong', 'lime');
this.newGame('Snake', 'lime');
LoadImg('canvas', Retrocade, 50, 75, 700, 450);
}
newGame(name, color) {
SetCanvasBorder(color, name, 6);
SetCanvasText(color, name, '35px', 20, 120, name);
}
handleClick(e) {
e.preventDefault();
this.setState({
gameSelected: true,
game: e.target.id
});
ResetCanvas('black', 'canvas');
}
handleMouseEnter(e) {
const canvasName = e.target.id;
this.newGame(canvasName, 'darkorange');
}
handleMouseLeave(e) {
const canvasName = e.target.id;
this.newGame(canvasName, 'lime');
}
render() {
const pongStyle = {
margin: 'auto auto',
position: 'absolute',
zIndex: '1',
bottom: '5%',
left: '5%'
}
const snakeStyle = {
margin: 'auto auto',
position: 'absolute',
zIndex: '1',
bottom: '5%',
right: '5%'
}
return (
<div className="HomeScreen">
<Canvas
id='canvas'
width={815}
height={615}
/>
{!this.state.gameSelected &&
<div>
<Canvas
id={'Pong'}
width={200}
height={200}
onClick={this.handleClick.bind(this)}
onMouseEnter={this.handleMouseEnter.bind(this)}
onMouseLeave={this.handleMouseLeave.bind(this)}
canvasStyle={pongStyle}
/>
<Canvas
id={'Snake'}
width={200}
height={200}
onClick={this.handleClick.bind(this)}
onMouseEnter={this.handleMouseEnter.bind(this)}
onMouseLeave={this.handleMouseLeave.bind(this)}
canvasStyle={snakeStyle}
/>
</div>
}
{this.state.game === 'Pong' &&
<GameHome
instructions={PongInstructions}
game={this.state.game}
/>
}
{this.state.game === 'Snake' &&
<GameHome
instructions={SnakeInstructions}
game={this.state.game}
/>
}
</div>
);
}
}
export default HomeScreen;
|
//! moment.js locale configuration
//! locale : Central Atlas Tamazight [tzm]
//! author : Abdel Said : https://github.com/abdelsaid
import moment from '../moment';
export default moment.defineLocale('tzm', {
months: 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'),
monthsShort: 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'),
weekdays: 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'),
weekdaysShort: 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'),
weekdaysMin: 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'),
longDateFormat: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'DD/MM/YYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY HH:mm',
LLLL: 'dddd D MMMM YYYY HH:mm'
},
calendar: {
sameDay: '[ⴰⵙⴷⵅ ⴴ] LT',
nextDay: '[ⴰⵙⴽⴰ ⴴ] LT',
nextWeek: 'dddd [ⴴ] LT',
lastDay: '[ⴰⵚⴰⵏⵜ ⴴ] LT',
lastWeek: 'dddd [ⴴ] LT',
sameElse: 'L'
},
relativeTime: {
future: 'ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s',
past: 'ⵢⴰⵏ %s',
s: 'ⵉⵎⵉⴽ',
m: 'ⵎⵉⵏⵓⴺ',
mm: '%d ⵎⵉⵏⵓⴺ',
h: 'ⵙⴰⵄⴰ',
hh: '%d ⵜⴰⵙⵙⴰⵄⵉⵏ',
d: 'ⴰⵙⵙ',
dd: '%d oⵙⵙⴰⵏ',
M: 'ⴰⵢoⵓⵔ',
MM: '%d ⵉⵢⵢⵉⵔⵏ',
y: 'ⴰⵙⴳⴰⵙ',
yy: '%d ⵉⵙⴳⴰⵙⵏ'
},
week: {
dow: 6, // Saturday is the first day of the week.
doy: 12 // The week that contains Jan 1st is the first week of the year.
}
});
|
/*
Commands to try:
node example.js --version
node example.js -v
node example.js dir
node example.js dir -l
node example.js --spawn [ ls -l ]
node example.js -s [ ls -l ]
node example.js --execute [ ls -l ]
node example.js -e [ ls -l ]
node example.js "something" --rebuild_command
node example.js "something" -r
node example.js "something" --subcontext [ A 29787 "b C" -a -B 29872 ]
node example.js "something" -S [ A 29787 "b C" -a -B 29872 ]
node example.js "something" -S [ A --good ]
*/
var pjson = require('../package.json');
var spawn = require('child_process').spawn;
var exec = require('child_process').exec;
// begin example
var protogram = require('../main');
var program = protogram.create();
program.command('*', {
includeRoot: true,
error: function(err, args){
console.error(err.message);
// console.log("here are your possible options", Object.keys(this.options));
// console.log("and your possible commands", Object.keys(this.commands));
}
}).option('--version', {
action: function(value) {
console.log("Protogram Example v" + pjson.version);
}
});
program
.option('--rebuild_command', {
description: 'rebuild the original command',
action: rebuildCommand
})
.option('--execute', {
description: 'execute a command (ex. --execute [ ls -l ./ ])',
required: 'command array',
action: executeCommand
})
.option('--spawn', {
description: 'spawn an evented command (captures stdout and stderr as streams, as well as an exit code) (ex. --execute [ ls -l ./ ])',
required: 'command array',
action: spawnCommand
})
.option('--subcontext', {
description: 'test subcontexts',
required: 'command string',
action: testSubcontext
});
program.command('dir', {
description: 'run a command (ex. [ ls -l ./ ])',
action: function(args, flags) {
var arr = ['ls'];
if (flags.list) arr.push('-l');
spawnCommand({_: arr});
}
}).option('--list', {
action: function(val) {
console.log("Directory as Vertical List");
}
});
function executeCommand(value) {
var command = program.rebuildArgString(value);
console.log("executing command", command);
exec(command, function(error, stdout, stderr) {
console.log(stdout ? "stdout:\n" + stdout : '');
console.log(stderr ? "stderr:\n" + stderr : '');
console.log(error ? "Error:\n" + error : '');
});
}
function rebuildCommand(value) {
var originalCommand = program.rebuildArgString(program.raw_arguments);
console.log("Original command", originalCommand);
}
function spawnCommand(value) {
var arr = program.rebuildArgArray(value);
console.log("spawing from array", arr);
var little_one = spawn(arr[0], arr.slice(1), {
stdio: "inherit"
});
}
function testSubcontext(value) {
console.log("Sub Context:", JSON.stringify(value));
var new_protogram = protogram.create();
new_protogram.option('--good', {
action: function(value) {
console.log("Good Worked on Subcontext", value);
}
});
new_protogram.option('--optionA', {
action: function(value) {
console.log("OptionA Worked on Subcontext", value);
}
});
new_protogram.parse(value);
}
program.parse(process.argv);
|
const path = require('path');
const config = require('../../../shared/config');
function servePreview(req, res, next) {
if (req.path === '/') {
const templatePath = path.resolve(config.get('paths').adminViews, 'preview.html');
return res.sendFile(templatePath);
}
next();
}
module.exports = [
servePreview
];
|
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
require('redux');
require('./turn-order-fc38e264.js');
require('immer');
require('./reducer-d0b6edbb.js');
require('./initialize-a9a217ca.js');
require('./base-4e44970d.js');
var master = require('./master-468d9986.js');
exports.Master = master.Master;
|
/* eslint-env mocha */
var P = require('autoresolve')
var path = require('path')
var fs = require('fs')
var rock = require(P('lib/rock'))
var testutil = require('testutil')
var nock = require('nock')
require('terst')
var TEST_DIR = null
var TMPL = 'Hi, @@author@@ is going to build:\n@@project-name@@.'
var TMPL_E = 'Hi, JP is going to build:\nRock.'
describe('rock', function () {
beforeEach(function () {
TEST_DIR = testutil.createTestDir('rock')
TEST_DIR = path.join(TEST_DIR, 'fetch-file')
})
describe('+ fetchFile()', function () {
describe('> when change open and closing templates', function () {
it('should generate a basic project', function () {
return TEST()
})
})
})
})
function TEST () {
var file = path.join(TEST_DIR, 'info.txt')
var remote = 'http://localhost/data.txt'
nock('http://localhost')
.get('/data.txt')
.reply(200, TMPL, {'Content-Type': 'text/plain'})
var templateValues = {
'author': 'JP',
'project-name': 'Rock'
}
return rock.fetchFile(file, remote, {templateValues: templateValues, tokens: {open: '@@', close: '@@'}})
.then(function () {
EQ(TMPL_E, fs.readFileSync(file, 'utf8'))
})
}
|
/*! Buefy v0.9.17 | MIT License | github.com/buefy/buefy */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.Toast = {}));
}(this, function (exports) { 'use strict';
var config = {
defaultContainerElement: null,
defaultIconPack: 'mdi',
defaultIconComponent: null,
defaultIconPrev: 'chevron-left',
defaultIconNext: 'chevron-right',
defaultLocale: undefined,
defaultDialogConfirmText: null,
defaultDialogCancelText: null,
defaultSnackbarDuration: 3500,
defaultSnackbarPosition: null,
defaultToastDuration: 2000,
defaultToastPosition: null,
defaultNotificationDuration: 2000,
defaultNotificationPosition: null,
defaultTooltipType: 'is-primary',
defaultTooltipDelay: null,
defaultSidebarDelay: null,
defaultInputAutocomplete: 'on',
defaultDateFormatter: null,
defaultDateParser: null,
defaultDateCreator: null,
defaultTimeCreator: null,
defaultDayNames: null,
defaultMonthNames: null,
defaultFirstDayOfWeek: null,
defaultUnselectableDaysOfWeek: null,
defaultTimeFormatter: null,
defaultTimeParser: null,
defaultModalCanCancel: ['escape', 'x', 'outside', 'button'],
defaultModalScroll: null,
defaultDatepickerMobileNative: true,
defaultTimepickerMobileNative: true,
defaultNoticeQueue: true,
defaultInputHasCounter: true,
defaultTaginputHasCounter: true,
defaultUseHtml5Validation: true,
defaultDropdownMobileModal: true,
defaultFieldLabelPosition: null,
defaultDatepickerYearsRange: [-100, 10],
defaultDatepickerNearbyMonthDays: true,
defaultDatepickerNearbySelectableMonthDays: false,
defaultDatepickerShowWeekNumber: false,
defaultDatepickerWeekNumberClickable: false,
defaultDatepickerMobileModal: true,
defaultTrapFocus: true,
defaultAutoFocus: true,
defaultButtonRounded: false,
defaultSwitchRounded: true,
defaultCarouselInterval: 3500,
defaultTabsExpanded: false,
defaultTabsAnimated: true,
defaultTabsType: null,
defaultStatusIcon: true,
defaultProgrammaticPromise: false,
defaultLinkTags: ['a', 'button', 'input', 'router-link', 'nuxt-link', 'n-link', 'RouterLink', 'NuxtLink', 'NLink'],
defaultImageWebpFallback: null,
defaultImageLazy: true,
defaultImageResponsive: true,
defaultImageRatio: null,
defaultImageSrcsetFormatter: null,
defaultBreadcrumbTag: 'a',
defaultBreadcrumbAlign: 'is-left',
defaultBreadcrumbSeparator: '',
defaultBreadcrumbSize: 'is-medium',
customIconPacks: null
};
var VueInstance;
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
/**
* Merge function to replace Object.assign with deep merging possibility
*/
var isObject = function isObject(item) {
return _typeof(item) === 'object' && !Array.isArray(item);
};
var mergeFn = function mergeFn(target, source) {
var deep = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (deep || !Object.assign) {
var isDeep = function isDeep(prop) {
return isObject(source[prop]) && target !== null && target.hasOwnProperty(prop) && isObject(target[prop]);
};
var replaced = Object.getOwnPropertyNames(source).map(function (prop) {
return _defineProperty({}, prop, isDeep(prop) ? mergeFn(target[prop], source[prop], deep) : source[prop]);
}).reduce(function (a, b) {
return _objectSpread2({}, a, {}, b);
}, {});
return _objectSpread2({}, target, {}, replaced);
} else {
return Object.assign(target, source);
}
};
var merge = mergeFn;
function removeElement(el) {
if (typeof el.remove !== 'undefined') {
el.remove();
} else if (typeof el.parentNode !== 'undefined' && el.parentNode !== null) {
el.parentNode.removeChild(el);
}
}
var NoticeMixin = {
props: {
type: {
type: String,
default: 'is-dark'
},
message: [String, Array],
duration: Number,
queue: {
type: Boolean,
default: undefined
},
indefinite: {
type: Boolean,
default: false
},
pauseOnHover: {
type: Boolean,
default: false
},
position: {
type: String,
default: 'is-top',
validator: function validator(value) {
return ['is-top-right', 'is-top', 'is-top-left', 'is-bottom-right', 'is-bottom', 'is-bottom-left'].indexOf(value) > -1;
}
},
container: String
},
data: function data() {
return {
isActive: false,
isPaused: false,
parentTop: null,
parentBottom: null,
newContainer: this.container || config.defaultContainerElement
};
},
computed: {
correctParent: function correctParent() {
switch (this.position) {
case 'is-top-right':
case 'is-top':
case 'is-top-left':
return this.parentTop;
case 'is-bottom-right':
case 'is-bottom':
case 'is-bottom-left':
return this.parentBottom;
}
},
transition: function transition() {
switch (this.position) {
case 'is-top-right':
case 'is-top':
case 'is-top-left':
return {
enter: 'fadeInDown',
leave: 'fadeOut'
};
case 'is-bottom-right':
case 'is-bottom':
case 'is-bottom-left':
return {
enter: 'fadeInUp',
leave: 'fadeOut'
};
}
}
},
methods: {
pause: function pause() {
if (this.pauseOnHover && !this.indefinite) {
this.isPaused = true;
clearInterval(this.$buefy.globalNoticeInterval);
}
},
removePause: function removePause() {
if (this.pauseOnHover && !this.indefinite) {
this.isPaused = false;
this.close();
}
},
shouldQueue: function shouldQueue() {
var queue = this.queue !== undefined ? this.queue : config.defaultNoticeQueue;
if (!queue) return false;
return this.parentTop.childElementCount > 0 || this.parentBottom.childElementCount > 0;
},
click: function click() {
this.$emit('click');
},
close: function close() {
var _this = this;
if (!this.isPaused) {
clearTimeout(this.timer);
this.isActive = false;
this.$emit('close'); // Timeout for the animation complete before destroying
setTimeout(function () {
_this.$destroy();
removeElement(_this.$el);
}, 150);
}
},
timeoutCallback: function timeoutCallback() {
return this.close();
},
showNotice: function showNotice() {
var _this2 = this;
if (this.shouldQueue()) this.correctParent.innerHTML = '';
this.correctParent.insertAdjacentElement('afterbegin', this.$el);
this.isActive = true;
if (!this.indefinite) {
this.timer = setTimeout(function () {
return _this2.timeoutCallback();
}, this.newDuration);
}
},
setupContainer: function setupContainer() {
this.parentTop = document.querySelector((this.newContainer ? this.newContainer : 'body') + '>.notices.is-top');
this.parentBottom = document.querySelector((this.newContainer ? this.newContainer : 'body') + '>.notices.is-bottom');
if (this.parentTop && this.parentBottom) return;
if (!this.parentTop) {
this.parentTop = document.createElement('div');
this.parentTop.className = 'notices is-top';
}
if (!this.parentBottom) {
this.parentBottom = document.createElement('div');
this.parentBottom.className = 'notices is-bottom';
}
var container = document.querySelector(this.newContainer) || document.body;
container.appendChild(this.parentTop);
container.appendChild(this.parentBottom);
if (this.newContainer) {
this.parentTop.classList.add('has-custom-container');
this.parentBottom.classList.add('has-custom-container');
}
}
},
beforeMount: function beforeMount() {
this.setupContainer();
},
mounted: function mounted() {
this.showNotice();
}
};
//
var script = {
name: 'BToast',
mixins: [NoticeMixin],
data: function data() {
return {
newDuration: this.duration || config.defaultToastDuration
};
}
};
function normalizeComponent(template, style, script, scopeId, isFunctionalTemplate, moduleIdentifier
/* server only */
, shadowMode, createInjector, createInjectorSSR, createInjectorShadow) {
if (typeof shadowMode !== 'boolean') {
createInjectorSSR = createInjector;
createInjector = shadowMode;
shadowMode = false;
} // Vue.extend constructor export interop.
var options = typeof script === 'function' ? script.options : script; // render functions
if (template && template.render) {
options.render = template.render;
options.staticRenderFns = template.staticRenderFns;
options._compiled = true; // functional template
if (isFunctionalTemplate) {
options.functional = true;
}
} // scopedId
if (scopeId) {
options._scopeId = scopeId;
}
var hook;
if (moduleIdentifier) {
// server build
hook = function hook(context) {
// 2.3 injection
context = context || // cached call
this.$vnode && this.$vnode.ssrContext || // stateful
this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext; // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__;
} // inject component styles
if (style) {
style.call(this, createInjectorSSR(context));
} // register component module identifier for async chunk inference
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier);
}
}; // used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook;
} else if (style) {
hook = shadowMode ? function () {
style.call(this, createInjectorShadow(this.$root.$options.shadowRoot));
} : function (context) {
style.call(this, createInjector(context));
};
}
if (hook) {
if (options.functional) {
// register for functional component in vue file
var originalRender = options.render;
options.render = function renderWithStyleInjection(h, context) {
hook.call(context);
return originalRender(h, context);
};
} else {
// inject component registration as beforeCreate hook
var existing = options.beforeCreate;
options.beforeCreate = existing ? [].concat(existing, hook) : [hook];
}
}
return script;
}
var normalizeComponent_1 = normalizeComponent;
/* script */
const __vue_script__ = script;
/* template */
var __vue_render__ = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('transition',{attrs:{"enter-active-class":_vm.transition.enter,"leave-active-class":_vm.transition.leave}},[_c('div',{directives:[{name:"show",rawName:"v-show",value:(_vm.isActive),expression:"isActive"}],staticClass:"toast",class:[_vm.type, _vm.position],attrs:{"aria-hidden":!_vm.isActive,"role":"alert"},on:{"mouseenter":_vm.pause,"mouseleave":_vm.removePause}},[(_vm.$slots.default)?[_vm._t("default")]:[_c('div',{domProps:{"innerHTML":_vm._s(_vm.message)}})]],2)])};
var __vue_staticRenderFns__ = [];
/* style */
const __vue_inject_styles__ = undefined;
/* scoped */
const __vue_scope_id__ = undefined;
/* module identifier */
const __vue_module_identifier__ = undefined;
/* functional template */
const __vue_is_functional_template__ = false;
/* style inject */
/* style inject SSR */
var Toast = normalizeComponent_1(
{ render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ },
__vue_inject_styles__,
__vue_script__,
__vue_scope_id__,
__vue_is_functional_template__,
__vue_module_identifier__,
undefined,
undefined
);
var use = function use(plugin) {
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(plugin);
}
};
var registerComponentProgrammatic = function registerComponentProgrammatic(Vue, property, component) {
if (!Vue.prototype.$buefy) Vue.prototype.$buefy = {};
Vue.prototype.$buefy[property] = component;
};
var localVueInstance;
var ToastProgrammatic = {
open: function open(params) {
var parent;
if (typeof params === 'string') {
params = {
message: params
};
}
var defaultParam = {
position: config.defaultToastPosition || 'is-top'
};
if (params.parent) {
parent = params.parent;
delete params.parent;
}
var slot;
if (Array.isArray(params.message)) {
slot = params.message;
delete params.message;
}
var propsData = merge(defaultParam, params);
var vm = typeof window !== 'undefined' && window.Vue ? window.Vue : localVueInstance || VueInstance;
var ToastComponent = vm.extend(Toast);
var component = new ToastComponent({
parent: parent,
el: document.createElement('div'),
propsData: propsData
});
if (slot) {
component.$slots.default = slot;
component.$forceUpdate();
}
return component;
}
};
var Plugin = {
install: function install(Vue) {
localVueInstance = Vue;
registerComponentProgrammatic(Vue, 'toast', ToastProgrammatic);
}
};
use(Plugin);
exports.BToast = Toast;
exports.ToastProgrammatic = ToastProgrammatic;
exports.default = Plugin;
Object.defineProperty(exports, '__esModule', { value: true });
}));
|
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { useThemeVariants } from '@material-ui/styles';
import withStyles from '../styles/withStyles';
import { fade } from '../styles/colorManipulator';
import ButtonBase from '../ButtonBase';
import capitalize from '../utils/capitalize';
export const styles = theme => ({
/* Styles applied to the root element. */
root: _extends({}, theme.typography.button, {
minWidth: 64,
padding: '6px 16px',
borderRadius: theme.shape.borderRadius,
transition: theme.transitions.create(['background-color', 'box-shadow', 'border'], {
duration: theme.transitions.duration.short
}),
'&:hover': {
textDecoration: 'none',
backgroundColor: fade(theme.palette.text.primary, theme.palette.action.hoverOpacity),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
},
'&$disabled': {
color: theme.palette.action.disabled
}
}),
/* Styles applied to the span element that wraps the children. */
label: {
width: '100%',
// Ensure the correct width for iOS Safari
display: 'inherit',
alignItems: 'inherit',
justifyContent: 'inherit'
},
/* Styles applied to the root element if `variant="text"`. */
text: {
padding: '6px 8px'
},
/* Styles applied to the root element if `variant="text"` and `color="primary"`. */
textPrimary: {
color: theme.palette.primary.main,
'&:hover': {
backgroundColor: fade(theme.palette.primary.main, theme.palette.action.hoverOpacity),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}
},
/* Styles applied to the root element if `variant="text"` and `color="secondary"`. */
textSecondary: {
color: theme.palette.secondary.main,
'&:hover': {
backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.hoverOpacity),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}
},
/* Styles applied to the root element if `variant="outlined"`. */
outlined: {
padding: '5px 15px',
border: `1px solid ${theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)'}`,
'&$disabled': {
border: `1px solid ${theme.palette.action.disabledBackground}`
}
},
/* Styles applied to the root element if `variant="outlined"` and `color="primary"`. */
outlinedPrimary: {
color: theme.palette.primary.main,
border: `1px solid ${fade(theme.palette.primary.main, 0.5)}`,
'&:hover': {
border: `1px solid ${theme.palette.primary.main}`,
backgroundColor: fade(theme.palette.primary.main, theme.palette.action.hoverOpacity),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}
},
/* Styles applied to the root element if `variant="outlined"` and `color="secondary"`. */
outlinedSecondary: {
color: theme.palette.secondary.main,
border: `1px solid ${fade(theme.palette.secondary.main, 0.5)}`,
'&:hover': {
border: `1px solid ${theme.palette.secondary.main}`,
backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.hoverOpacity),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
},
'&$disabled': {
border: `1px solid ${theme.palette.action.disabled}`
}
},
/* Styles applied to the root element if `variant="contained"`. */
contained: {
color: theme.palette.getContrastText(theme.palette.grey[300]),
backgroundColor: theme.palette.grey[300],
boxShadow: theme.shadows[2],
'&:hover': {
backgroundColor: theme.palette.grey.A100,
boxShadow: theme.shadows[4],
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
boxShadow: theme.shadows[2],
backgroundColor: theme.palette.grey[300]
}
},
'&$focusVisible': {
boxShadow: theme.shadows[6]
},
'&:active': {
boxShadow: theme.shadows[8]
},
'&$disabled': {
color: theme.palette.action.disabled,
boxShadow: theme.shadows[0],
backgroundColor: theme.palette.action.disabledBackground
}
},
/* Styles applied to the root element if `variant="contained"` and `color="primary"`. */
containedPrimary: {
color: theme.palette.primary.contrastText,
backgroundColor: theme.palette.primary.main,
'&:hover': {
backgroundColor: theme.palette.primary.dark,
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: theme.palette.primary.main
}
}
},
/* Styles applied to the root element if `variant="contained"` and `color="secondary"`. */
containedSecondary: {
color: theme.palette.secondary.contrastText,
backgroundColor: theme.palette.secondary.main,
'&:hover': {
backgroundColor: theme.palette.secondary.dark,
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: theme.palette.secondary.main
}
}
},
/* Styles applied to the root element if `disableElevation={true}`. */
disableElevation: {
boxShadow: 'none',
'&:hover': {
boxShadow: 'none'
},
'&$focusVisible': {
boxShadow: 'none'
},
'&:active': {
boxShadow: 'none'
},
'&$disabled': {
boxShadow: 'none'
}
},
/* Pseudo-class applied to the ButtonBase root element if the button is keyboard focused. */
focusVisible: {},
/* Pseudo-class applied to the root element if `disabled={true}`. */
disabled: {},
/* Styles applied to the root element if `color="inherit"`. */
colorInherit: {
color: 'inherit',
borderColor: 'currentColor'
},
/* Styles applied to the root element if `size="small"` and `variant="text"`. */
textSizeSmall: {
padding: '4px 5px',
fontSize: theme.typography.pxToRem(13)
},
/* Styles applied to the root element if `size="large"` and `variant="text"`. */
textSizeLarge: {
padding: '8px 11px',
fontSize: theme.typography.pxToRem(15)
},
/* Styles applied to the root element if `size="small"` and `variant="outlined"`. */
outlinedSizeSmall: {
padding: '3px 9px',
fontSize: theme.typography.pxToRem(13)
},
/* Styles applied to the root element if `size="large"` and `variant="outlined"`. */
outlinedSizeLarge: {
padding: '7px 21px',
fontSize: theme.typography.pxToRem(15)
},
/* Styles applied to the root element if `size="small"` and `variant="contained"`. */
containedSizeSmall: {
padding: '4px 10px',
fontSize: theme.typography.pxToRem(13)
},
/* Styles applied to the root element if `size="large"` and `variant="contained"`. */
containedSizeLarge: {
padding: '8px 22px',
fontSize: theme.typography.pxToRem(15)
},
/* Styles applied to the root element if `size="small"`. */
sizeSmall: {},
/* Styles applied to the root element if `size="large"`. */
sizeLarge: {},
/* Styles applied to the root element if `fullWidth={true}`. */
fullWidth: {
width: '100%'
},
/* Styles applied to the startIcon element if supplied. */
startIcon: {
display: 'inherit',
marginRight: 8,
marginLeft: -4,
'&$iconSizeSmall': {
marginLeft: -2
}
},
/* Styles applied to the endIcon element if supplied. */
endIcon: {
display: 'inherit',
marginRight: -4,
marginLeft: 8,
'&$iconSizeSmall': {
marginRight: -2
}
},
/* Styles applied to the icon element if supplied and `size="small"`. */
iconSizeSmall: {
'& > *:first-child': {
fontSize: 18
}
},
/* Styles applied to the icon element if supplied and `size="medium"`. */
iconSizeMedium: {
'& > *:first-child': {
fontSize: 20
}
},
/* Styles applied to the icon element if supplied and `size="large"`. */
iconSizeLarge: {
'& > *:first-child': {
fontSize: 22
}
}
});
const Button = /*#__PURE__*/React.forwardRef(function Button(props, ref) {
const {
children,
classes,
className,
color = 'primary',
component = 'button',
disabled = false,
disableElevation = false,
disableFocusRipple = false,
endIcon: endIconProp,
focusVisibleClassName,
fullWidth = false,
size = 'medium',
startIcon: startIconProp,
type = 'button',
variant = 'text'
} = props,
other = _objectWithoutPropertiesLoose(props, ["children", "classes", "className", "color", "component", "disabled", "disableElevation", "disableFocusRipple", "endIcon", "focusVisibleClassName", "fullWidth", "size", "startIcon", "type", "variant"]);
const themeVariantsClasses = useThemeVariants(_extends({}, props, {
color,
component,
disabled,
disableElevation,
disableFocusRipple,
fullWidth,
size,
type,
variant
}), 'MuiButton');
const startIcon = startIconProp && /*#__PURE__*/React.createElement("span", {
className: clsx(classes.startIcon, classes[`iconSize${capitalize(size)}`])
}, startIconProp);
const endIcon = endIconProp && /*#__PURE__*/React.createElement("span", {
className: clsx(classes.endIcon, classes[`iconSize${capitalize(size)}`])
}, endIconProp);
return /*#__PURE__*/React.createElement(ButtonBase, _extends({
className: clsx(classes.root, classes[variant], themeVariantsClasses, className, color === 'inherit' ? classes.colorInherit : classes[`${variant}${capitalize(color)}`], size !== 'medium' && [classes[`${variant}Size${capitalize(size)}`], classes[`size${capitalize(size)}`]], disableElevation && classes.disableElevation, disabled && classes.disabled, fullWidth && classes.fullWidth),
component: component,
disabled: disabled,
focusRipple: !disableFocusRipple,
focusVisibleClassName: clsx(classes.focusVisible, focusVisibleClassName),
ref: ref,
type: type
}, other), /*#__PURE__*/React.createElement("span", {
className: classes.label
}, startIcon, children, endIcon));
});
process.env.NODE_ENV !== "production" ? Button.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The content of the button.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
* @default 'primary'
*/
color: PropTypes.oneOf(['inherit', 'primary', 'secondary']),
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: PropTypes.elementType,
/**
* If `true`, the button will be disabled.
* @default false
*/
disabled: PropTypes.bool,
/**
* If `true`, no elevation is used.
* @default false
*/
disableElevation: PropTypes.bool,
/**
* If `true`, the keyboard focus ripple will be disabled.
* @default false
*/
disableFocusRipple: PropTypes.bool,
/**
* If `true`, the ripple effect will be disabled.
*
* ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure
* to highlight the element by applying separate styles with the `focusVisibleClassName`.
* @default false
*/
disableRipple: PropTypes.bool,
/**
* Element placed after the children.
*/
endIcon: PropTypes.node,
/**
* @ignore
*/
focusVisibleClassName: PropTypes.string,
/**
* If `true`, the button will take up the full width of its container.
* @default false
*/
fullWidth: PropTypes.bool,
/**
* The URL to link to when the button is clicked.
* If defined, an `a` element will be used as the root node.
*/
href: PropTypes.string,
/**
* The size of the button.
* `small` is equivalent to the dense button styling.
* @default 'medium'
*/
size: PropTypes.oneOf(['large', 'medium', 'small']),
/**
* Element placed before the children.
*/
startIcon: PropTypes.node,
/**
* @ignore
*/
type: PropTypes.oneOfType([PropTypes.oneOf(['button', 'reset', 'submit']), PropTypes.string]),
/**
* The variant to use.
* @default 'text'
*/
variant: PropTypes
/* @typescript-to-proptypes-ignore */
.oneOfType([PropTypes.oneOf(['contained', 'outlined', 'text']), PropTypes.string])
} : void 0;
export default withStyles(styles, {
name: 'MuiButton'
})(Button);
|
// Sample Event
// { "Filter": { "Name": "tag:TerminationGroup", "Values": [ "KILL_ME" ] } }
// Be shure to have an EC2 instance with tag "TerminationGroup" and value "KILL_ME"
// http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#terminateInstances-property
var AWS = require('aws-sdk');
AWS.config.apiVersions = {
ec2: '2015-10-01'
};
var ec2 = new AWS.EC2();
exports.handler = function(event, context) {
var _params = { InstanceIds: [] };
ec2.describeInstances({ Filters: [ event.Filter ] }, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
data.Reservations.forEach(function(r) {
r.Instances.forEach(function(i) {
_params.InstanceIds.push(i.InstanceId);
});
});
ec2.terminateInstances(_params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
context.done();
});
}
});
};
|
var Class = require('./Class')
var map = require('./map')
var toArray = require('./toArray')
var isArray = require('std/isArray')
var URL = Class(function() {
this._extractionRegex = new RegExp([
'^', // start at the beginning of the string
'((\\w+:)?//)?', // match a possible protocol, like http://, ftp://, or // for a relative url
'(\\w[\\w\\.\\-]+)?', // match a possible domain
'(:\\d+)?', // match a possible port
'(\\/[^\\?#]+)?', // match a possible path
'(\\?[^#]+)?', // match possible GET parameters
'(#.*)?' // match the rest of the URL as the hash
].join(''), 'i')
this.init = function(url) {
var match = (url || '').toString().match(this._extractionRegex) || []
this.protocol = match[2] || ''
this.hostname = match[3] || ''
this.port = (match[4] || '').substr(1)
this.host = (this.hostname ? this.hostname : '') + (this.port ? ':' + this.port : '')
this.pathname = match[5] || ''
this.search = (match[6]||'').substr(1)
this.hash = (match[7]||'').substr(1)
}
this.setProtocol = function(protocol) {
this.protocol = protocol
return this
}
this.toString = function() {
return [
this.protocol || '//',
this.host,
this.pathname,
this.getSearch(),
this.getHash()
].join('')
}
this.toJSON = this.toString
this.getTopLevelDomain = function() {
if (!this.host) { return '' }
var parts = this.host.split('.')
return parts.slice(parts.length - 2).join('.')
}
this.getSearchParams = function() {
if (this._searchParams) { return this._searchParams }
return this._searchParams = url.query.parse(this.search) || {}
}
this.getHashParams = function() {
if (this._hashParams) { return this._hashParams }
return this._hashParams = url.query.parse(this.hash) || {}
}
this.addToSearch = function(key, val) { this.getSearchParams()[key] = val; return this }
this.addToHash = function(key, val) { this.getHashParams()[key] = val; return this }
this.removeFromSearch = function(key) { delete this.getSearchParams()[key]; return this }
this.removeFromHash = function(key) { delete this.getHashParams()[key]; return this }
this.getSearch = function() {
return (
this._searchParams ? '?' + url.query.string(this._searchParams)
: this.search ? '?' + this.search
: '')
}
this.getHash = function() {
return (
this._hashParams ? '#' + url.query.string(this._hashParams)
: this.hash ? '?' + this.hash
: '')
}
this.getSearchParam = function(key) { return this.getSearchParams()[key] }
this.getHashParam = function(key) { return this.getHashParams()[key] }
})
var url = module.exports = function url(url) { return new URL(url) }
url.parse = url
url.query = {
parse:function(paramString) {
var parts = paramString.split('&'),
params = {}
for (var i=0; i<parts.length; i++) {
var kvp = parts[i].split('=')
if (kvp.length != 2) { continue }
params[decodeURIComponent(kvp[0])] = decodeURIComponent(kvp[1])
}
return params
},
string:function(params) {
return toArray(params, function(val, key) {
return encodeURIComponent(key) + '=' + url.query.encodeValue(val)
}).join('&')
},
encodeValue:function(val) {
if (isArray(val)) {
return map(val, function(v) {
return encodeURIComponent(v)
}).join(',')
} else {
return encodeURIComponent(val)
}
}
}
|
import{borders,compose,display,flexbox,grid,palette,positions,shadows,sizing,spacing,typography,css}from"@material-ui/system";import styled from"../styles/styled";const styleFunction=css(compose(borders,display,flexbox,grid,positions,palette,shadows,sizing,spacing,typography)),Box=styled("div")(styleFunction,{name:"MuiBox"});export default Box;export{styleFunction};
|
requireCore('user');
require(__rootdir + '/data-modules/anime');
require(__rootdir + '/data-modules/book');
require(__rootdir + '/data-modules/game');
requireCore('auth');
var mongoose = require('mongoose');
var config = require('./../config.json');
var testDataHelper = require('./testData-helper.js');
var expect = require('chai').expect;
mongoose.connect(config.mongourl);
var getModel = function (modelName) {
return mongoose.model(modelName);
};
var getAll = function (modelName, filter, callback) {
getModel(modelName).find(filter, callback);
};
var getAllWithTestUser = function (modelName, callback) {
getAll(modelName, {user: new mongoose.Types.ObjectId(testDataHelper.UserId)}, function (err, items) {
expect(err).to.be.equal(null);
callback(err, items);
});
};
var getRandomItem = function (modelName, callback) {
getAllWithTestUser(modelName, function (err, items) {
var item = items[Math.floor(Math.random() * items.length)];
callback(err, item);
});
};
module.exports = {
get: getModel,
getAll: getAll,
getAllWithTestUser: getAllWithTestUser,
getRandomItem: getRandomItem
};
|
Ext.define('sisprod.model.ChemicalTreatmentModel', {
extend: 'Ext.data.Model',
require:[
'Ext.data.Model'
],
fields:[
{name: 'idChemicalTreatment', type: 'int', visible: false},
{name: 'chemicalTreatmentDate', type: 'date', visible: true, dateFormat: 'Y-m-d'},
{name: 'well.idWell', type: 'int', visible: false, mapping:'well.idWell'},
{name: 'well.wellName', type: 'string', visible: true, mapping:'well.wellName'}
],
idProperty: 'idChemicalTreatment'
});
|
var gulp = require('gulp');
require('require-dir')('./tasks');
gulp.task('assets', ['bower', 'tpl', 'jade', 'stylus', 'js']);
gulp.task('watch', ['assets'], function () {
gulp.watch(['./client/app/tpl/**/*.jade'], ['tpl']);
gulp.watch(['./client/app/jade/**/*.jade'], ['jade']);
gulp.watch(['./client/app/styl/**/*.styl'], ['stylus']);
gulp.watch(['./client/app/js/**/*.{es6,js}'], ['js']);
gulp.watch(['./client/app/**/*'], ['manifest']);
gulp.run('nodemon');
});
gulp.task('default', ['connect', 'watch']);
|
'use strict';
var statisticController = require('../controllers/statisticController');
var apiConfig = require('../config/api.config.json');
var timestamp = require('../../config/timestamp.helper');
var that = {};
var run = function() {
for (var prop in apiConfig.statistics) {
if (!apiConfig.statistics.hasOwnProperty(prop)) continue;
if (apiConfig.statistics[prop].datatype === 'melodic') {
console.log(timestamp(), 'Enqueue updating statistics for', prop);
statisticController.updateStats(apiConfig.statistics[prop].mode, function (result) {
console.log(timestamp(), 'Updated statistics for', result.value.mode);
});
}
}
};
that.run = run;
module.exports = that;
|
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
import { GameEvent } from '../Events';
var MediaEvent = /** @class */ (function (_super) {
__extends(MediaEvent, _super);
function MediaEvent(target, _name) {
if (_name === void 0) { _name = 'MediaEvent'; }
var _this = _super.call(this) || this;
_this.target = target;
_this._name = _name;
return _this;
}
Object.defineProperty(MediaEvent.prototype, "bubbles", {
/**
* Media event cannot bubble
*/
get: function () {
return false;
},
/**
* Media event cannot bubble
*/
set: function (_value) {
// stubbed
},
enumerable: false,
configurable: true
});
Object.defineProperty(MediaEvent.prototype, "_path", {
/**
* Media event cannot bubble, so they have no path
*/
get: function () {
return null;
},
/**
* Media event cannot bubble, so they have no path
*/
set: function (_val) {
// stubbed
},
enumerable: false,
configurable: true
});
/**
* Prevents event from bubbling
*/
MediaEvent.prototype.stopPropagation = function () {
/**
* Stub
*/
};
/**
* Action, that calls when event happens
*/
MediaEvent.prototype.action = function () {
/**
* Stub
*/
};
/**
* Propagate event further through event path
*/
MediaEvent.prototype.propagate = function () {
/**
* Stub
*/
};
MediaEvent.prototype.layPath = function (_actor) {
/**
* Stub
*/
};
return MediaEvent;
}(GameEvent));
export { MediaEvent };
var NativeSoundEvent = /** @class */ (function (_super) {
__extends(NativeSoundEvent, _super);
function NativeSoundEvent(target, track) {
var _this = _super.call(this, target, 'NativeSoundEvent') || this;
_this.track = track;
return _this;
}
return NativeSoundEvent;
}(MediaEvent));
export { NativeSoundEvent };
var NativeSoundProcessedEvent = /** @class */ (function (_super) {
__extends(NativeSoundProcessedEvent, _super);
function NativeSoundProcessedEvent(target, processedData) {
var _this = _super.call(this, target, 'NativeSoundProcessedEvent') || this;
_this.processedData = processedData;
_this.data = _this.processedData;
return _this;
}
return NativeSoundProcessedEvent;
}(MediaEvent));
export { NativeSoundProcessedEvent };
//# sourceMappingURL=MediaEvents.js.map
|
define([
'underscore',
'backbone',
'orotranslation/js/translator',
'oroui/js/mediator',
'oroui/js/tools',
'backbone-bootstrap-modal'
], function(_, Backbone, __, mediator, tools) {
'use strict';
var Modal;
var $ = Backbone.$;
/**
* Implementation of Bootstrap Modal
* Oro extension of Bootstrap Modal wrapper for use with Backbone.
*
* @export oroui/js/modal
* @class oroui.Modal
* @extends Backbone.BootstrapModal
*/
Modal = Backbone.BootstrapModal.extend({
events: _.extend(Backbone.BootstrapModal.prototype.events, {
'click [data-button-id]': 'onButtonClick'
}),
defaults: {
okText: __('OK'),
cancelText: __('Cancel'),
handleClose: false
},
/** @property {String} */
className: 'modal oro-modal-normal',
initialize: function(options) {
options = options || {};
_.defaults(options, this.defaults);
if (options.handleClose) {
this.events = _.extend({}, this.events, {'click .close': _.bind(this.onClose, this)});
}
Modal.__super__.initialize.call(this, options);
},
onClose: function(event) {
event.preventDefault();
this.trigger('close');
if (this.options.content && this.options.content.trigger) {
this.options.content.trigger('close', this);
}
},
/**
* Handler for button click
*
* @param {jQuery.Event} event
*/
onButtonClick: function(event) {
event.preventDefault();
this.trigger('buttonClick', $(event.target).data('button-id'));
this.close();
},
/**
* Renders and shows the modal
*
* @param {Function} [cb] Optional callback that runs only when OK is pressed.
*/
open: function(cb) {
if (!this.isRendered) {
this.render();
}
this.delegateEvents();
var self = this;
var $el = this.$el;
//Create it
$el.modal(_.extend({
keyboard: this.options.allowCancel,
backdrop: this.options.allowCancel ? true : 'static'
}, this.options.modalOptions));
$el.one('shown', function() {
if (self.options.content && self.options.content.trigger) {
self.options.content.trigger('shown', self);
}
self.trigger('shown');
});
//Adjust the modal and backdrop z-index; for dealing with multiple modals
var numModals = Backbone.BootstrapModal.count;
var $backdrop = $('.modal-backdrop:eq(' + numModals + ')');
var backdropIndex = parseInt($backdrop.css('z-index'), 10);
var elIndex = parseInt($backdrop.css('z-index'), 10) + 1;
$backdrop.css('z-index', backdropIndex + numModals);
this.$el.css('z-index', elIndex + numModals);
if (this.options.allowCancel) {
$backdrop.one('click', function() {
if (self.options.content && self.options.content.trigger) {
self.options.content.trigger('cancel', self);
}
self.trigger('cancel');
});
$(document).one('keyup.dismiss.modal' + this._eventNamespace(), function(e) {
if (e.which !== 27) {
return;
}
if (self.options.handleClose) {
self.trigger('close');
} else {
self.trigger('cancel');
}
if (self.options.content && self.options.content.trigger) {
self.options.content.trigger('shown', self);
}
});
}
this.once('cancel', function() {
self.close();
});
this.once('close', function() {
self.close();
});
Backbone.BootstrapModal.count++;
//Run callback on OK if provided
if (cb) {
self.on('ok', cb);
}
this.once('cancel', _.bind(function() {
this.$el.trigger('hidden');
}, this));
if (tools.isMobile()) {
this._fixHeightForMobile();
$(window).on('resize' + this._eventNamespace(), _.bind(this._fixHeightForMobile, this));
}
mediator.trigger('modal:open', this);
//Focus OK button
if (self.options.focusOk) {
$el.find('.btn.ok')
.one('focusin', function(e) {
/*
* Prevents jquery-ui from focusing different dialog
* (which is happening when focusin is triggered on document
*/
e.stopPropagation();
})
.focus();
}
return this;
},
/**
* @inheritDoc
*/
close: function() {
Modal.__super__.close.call(this);
$(document).off(this._eventNamespace());
$(window).off(this._eventNamespace());
this.stopListening();
mediator.trigger('modal:close', this);
},
/**
* @inheritDoc
*/
dispose: function() {
if (this.disposed) {
return;
}
delete this.$content;
Modal.__super__.dispose.call(this);
},
/**
* Updates content of modal dialog
*/
setContent: function(content) {
this.options.content = content;
this.$el.find('.modal-body').html(content);
},
/**
* Returns event's name space
*
* @returns {string}
* @protected
*/
_eventNamespace: function() {
return '.delegateEvents' + this.cid;
},
_fixHeightForMobile: function() {
this.$('.modal-body').height('auto');
var clientHeight = this.$el[0].clientHeight;
if (clientHeight < this.$el[0].scrollHeight) {
this.$('.modal-body').height(clientHeight -
this.$('.modal-header').outerHeight() -
this.$('.modal-footer').outerHeight());
}
}
});
return Modal;
});
|
/**
* Broadcast updates to client when the model changes
*/
'use strict';
var fs = require('fs');
var app = require('../../app');
var logger = require('log4js').getLogger('mediaSocket');
exports.client = function(socket) {
socket.on('start', function(data) {
onStart(socket, data);
});
socket.on('upload', function(data) {
onUpload(socket, data);
});
};
exports.global = function(socket) {
};
var files = [];
function onStart(socket, data) {
var name = data.name;
logger.info('Starting uploading file: ' + name);
files[name] = {
data: [],
size: data.size,
downloaded: 0
};
fs.open(getType(data.type) + name, 'a', function (err, fd) {
if (err) {
logger.error(err);
} else {
files[name].handler = fd;
socket.emit('moreData', {
place: 0
});
}
});
}
function onUpload(socket, data) {
var name = data.name;
var file = files[name];
file.data.push(data.data);
file.downloaded += data.data.length;
if (file.downloaded == file.size) {
var buff = Buffer.concat(file.data);
fs.write(file.handler, buff, 0, buff.length, null, function(err) {
if (err) {
logger.error(err);
} else {
socket.emit('done');
fs.close(file.handler);
delete files[name];
}
});
} else {
var place = file.downloaded;
socket.emit('moreData', {
place: place
});
}
}
function getType(type) {
var found = type.replace(/.*(image|video).*/, '$1');
if (found) {
logger.debug('Media type: ' + found);
return app.get('appPath') + '/assets/' + found + 's/';
}
}
|
/**
*
* @param {Object} obj
* @returns {Array} of the values on the object
*/
Object.values = function (obj) {
var vals = [];
for( var key in obj ) {
if ( obj.hasOwnProperty(key) ) {
vals.push(obj[key]);
}
}
return vals;
};
|
/*
* Database schema.
* On this example we have the following schema on mongo:
* {"userId":"userIdValue",
* answers:[
* {"idUser":1111,"testNo":1,"answerNo":2,"answerValue":"answer1"},
* {"idUser":1111,"testNo":1,"answerNo":2,"answerValue":"answer1"}
* ]}
*/
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var NewUserSchema = new Schema({
id: Number,
Timestamp:Date
});
module.exports = mongoose.model('NewUser', NewUserSchema);
|
define(['react','underscore'], function(React,_) {
var LazyLoadImg=React.createClass({displayName: "LazyLoadImg",
componentDidUpdate: function() {
console.log("algoCambio");
},
render:function(){
return React.createElement("img", {src: this.props.img, alt: this.props.alt})
}
});
var FeedNoticia = React.createClass({displayName: "FeedNoticia",
getInitialState: function() {
return {
visible:false
};
},
componentWillMount:function(){
console.log("imagen Cargada");
},
componentDidUpdate: function() {
console.log("algoCambio");
},
render: function() {
return React.createElement("article", {className: "Componente_Article"},
React.createElement("div", {className: "Loader_Noticias"},
React.createElement("figure", null, React.createElement(LazyLoadImg, {img: this.props.img, alt: this.props.titulo})),
React.createElement("div", {className: "Loader_Noticias-Cont"},
React.createElement("div", {className: "L-sh1"}),
React.createElement("div", {className: "L-sh2"}),
React.createElement("div", {className: "L-sh2"}),
React.createElement("div", {className: "L-sh2"}),
React.createElement("div", {className: "L-sh2"}),
React.createElement("div", {className: "L-sbu"})
)
)
)
}
});
//**Componente Principal - Recibe datos del ajax
var AppNoticiasCA = React.createClass({displayName: 'AppNoticiasCA',
getInitialState: function() {
return {
Noticias:this.props.Noticias,
};
},
render: function() {
var Items = _.map(this.state.Noticias, function(item){
return React.createElement(FeedNoticia, {key: item.clave, id_noticia: item.clave, img: item.grande, sumario: item.sumario, titulo: item.titulo, fecha: item.fecha})
});
return React.createElement("div", {className: "ThoyCA_ContMain-MoPrincipal--React"},
Items
)
}
});
window.React = React;
return AppNoticiasCA;
});
|
function strchr (haystack, needle, bool) {
// From: http://phpjs.org/functions
// + original by: Philip Peterson
// - depends on: strstr
// * example 1: strchr('Kevin van Zonneveld', 'van');
// * returns 1: 'van Zonneveld'
// * example 2: strchr('Kevin van Zonneveld', 'van', true);
// * returns 2: 'Kevin '
return this.strstr(haystack, needle, bool);
}
|
const path = require('path')
const { IgnorePlugin } = require('webpack');
const FilterWarningsPlugin = require('webpack-filter-warnings-plugin');
module.exports = {
mode: 'production',
entry: './src/index.ts',
target: 'node',
node: {
global: true,
__filename: false,
__dirname: false,
},
plugins: [
new IgnorePlugin({ resourceRegExp: /^pg-native$/}),
new FilterWarningsPlugin({
exclude: [/hdb-pool/, /@sap\/hana-client/, /mongodb/, /mssql/, /mysql/, /mysql2/, /oracledb/, /pg/, /pg-query-stream/, /react-native-sqlite-storage/, /redis/, /sqlite3/, /sql.js/, /typeorm-aurora-data-api-driver/]
}),
// new CopyPlugin({
// patterns: [
// { from: "**/*", to: "" },
// ],
// }),
],
output: {
path: path.resolve(__dirname, '../dist/umd'),
filename: 'index.js',
library: '@rollem/language',
libraryTarget: 'umd',
globalObject: 'this',
},
module: {
rules: [
{
test: /\.ts(x*)?$/,
exclude: /node_modules/,
use: {
loader: 'ts-loader',
options: {
configFile: 'config/tsconfig.umd.json',
},
},
},
{
test: /\.pegjs$/,
use: "pegjs-loader",
},
],
},
resolve: {
extensions: [".tsx", ".ts", ".js", ".pegjs"],
// alias: {
// "@language-v1": path.resolve(__dirname, "../src/rollem-language-1/"),
// "@language-v1-beta": path.resolve(__dirname, "../src/rollem-language-1-beta/"),
// "@language-v2": path.resolve(__dirname, "../src/rollem-language-2/"),
// },
},
}
|
function changeSize1(){
var d = document.getElementsByClassName('triangle1');
d[0].style.width = '700px';
d[0].style.height = '100px';
}
function reset1(){
document.getElementsByClassName('triangle1')[0].style.width = '600px';
document.getElementsByClassName('triangle1')[0].style.height = '100px';
}
function changeSize2(){
var d = document.getElementsByClassName('triangle2');
d[0].style.width = '600px';
d[0].style.height = '100px';
}
function reset2(){
document.getElementsByClassName('triangle2')[0].style.width = '500px';
document.getElementsByClassName('triangle2')[0].style.height = '100px';
}
function changeSize3(){
var d = document.getElementsByClassName('triangle3');
d[0].style.width = '500px';
d[0].style.height = '100px';
}
function reset3(){
document.getElementsByClassName('triangle3')[0].style.width = '400px';
document.getElementsByClassName('triangle3')[0].style.height = '100px';
}
function changeSize4(){
var d = document.getElementsByClassName('triangle4');
d[0].style.width = '400px';
d[0].style.height = '100px';
}
function reset4(){
document.getElementsByClassName('triangle4')[0].style.width = '300px';
document.getElementsByClassName('triangle4')[0].style.height = '100px';
}
function changeSize5(){
var d = document.getElementsByClassName('triangle5');
d[0].style.width = '300px';
d[0].style.height = '100px';
}
function reset5(){
document.getElementsByClassName('triangle5')[0].style.width = '200px';
document.getElementsByClassName('triangle5')[0].style.bottom = '60px';
}
function changeSize6(){
var d = document.getElementsByClassName('triangle6');
d[0].style.width = '200px';
d[0].style.height = '100px';
}
function reset6(){
document.getElementsByClassName('triangle6')[0].style.width = '100px';
document.getElementsByClassName('triangle6')[0].style.bottom = '-44px';
}
|
'use strict'
module.exports = function SharedFlat (sequelize, DataTypes) {
let SharedFlat = sequelize.define('SharedFlat', {
name: DataTypes.STRING,
address: DataTypes.STRING
})
return SharedFlat
}
|
'use strict';
var _ReactInstrumentation = require('react/lib/ReactInstrumentation');
var _ReactInstrumentation2 = _interopRequireDefault(_ReactInstrumentation);
var _ReactDOMUnknownPropertyHook = require('react/lib/ReactDOMUnknownPropertyHook');
var _ReactDOMUnknownPropertyHook2 = _interopRequireDefault(_ReactDOMUnknownPropertyHook);
var _ReactDOMNullInputValuePropHook = require('react/lib/ReactDOMNullInputValuePropHook');
var _ReactDOMNullInputValuePropHook2 = _interopRequireDefault(_ReactDOMNullInputValuePropHook);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var devToolRemoved = false;
function removeDevTool() {
if (!devToolRemoved) {
_ReactInstrumentation2.default.debugTool.removeHook(_ReactDOMUnknownPropertyHook2.default);
_ReactInstrumentation2.default.debugTool.removeHook(_ReactDOMNullInputValuePropHook2.default);
devToolRemoved = true;
return true;
}
return false;
}
removeDevTool.restore = function restore() {
devToolRemoved = false;
_ReactInstrumentation2.default.debugTool.addHook(_ReactDOMUnknownPropertyHook2.default);
_ReactInstrumentation2.default.debugTool.addHook(_ReactDOMNullInputValuePropHook2.default);
};
module.exports = removeDevTool;
|
MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS["STIXGeneral-italic"],{8450:[666,18,702,35,702],8453:[676,14,855,47,808],8458:[441,219,738,30,678],8459:[687,15,997,53,991],8461:[653,0,732,17,767],8462:[668,11,513,45,483],8464:[675,15,897,26,888],8466:[687,15,946,33,931],8469:[653,0,727,25,755],8470:[668,15,1046,19,1031],8473:[653,0,687,17,686],8474:[666,71,723,35,713],8475:[687,15,944,34,876],8477:[653,0,687,17,686],8482:[653,-247,980,30,957],8484:[653,0,754,7,750],8492:[687,15,950,34,902],8495:[441,11,627,30,554],8496:[687,15,750,100,734],8497:[680,0,919,43,907],8499:[674,15,1072,38,1056],8500:[441,11,697,30,680],8508:[428,12,635,40,630],8511:[653,0,750,30,780],8517:[653,0,713,17,703],8518:[683,11,581,40,634],8519:[441,11,515,40,485],8520:[653,0,293,27,346],8521:[653,217,341,-104,394]}),MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/General/Italic/LetterlikeSymbols.js");
|
const utils = require("../utils.js");
var sqlite3 = require("sqlite3");
exports.run = (client, message, config, sconfig, args) => {
if (utils.isDM(message)) {
return "Sorry " + message.author.username +", you have to be in a Discord Server to run this command.";
}
if (utils.isRaidCoordinator(message)) {
var db = new sqlite3.Database(config.databaseFile);
let users = new Array();
db.all("SELECT id, discordUser FROM raiders", function (err,rows) {
rows.forEach(function (row) {
users.push(row.discordUser + " (" + row.id +")");
});
});
db.close(function () {
utils.sendBotMessage(message, "Currently stored raiders:\r\n" + users.join("\r\n"));
});
return null;
} else {
return "Sorry " + message.author.username + ", you must be a " + config.raidCoordRoleName + " to do this.";
}
}
|
/*!
* Native JavaScript for Bootstrap - Carousel v4.1.0alpha1 (https://thednp.github.io/bootstrap.native/)
* Copyright 2015-2022 © dnp_theme
* Licensed under MIT (https://github.com/thednp/bootstrap.native/blob/master/LICENSE)
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Carousel = factory());
})(this, (function () { 'use strict';
/**
* A global namespace for `mouseenter` event.
* @type {string}
*/
const mouseenterEvent = 'mouseenter';
/**
* A global namespace for `mouseleave` event.
* @type {string}
*/
const mouseleaveEvent = 'mouseleave';
/**
* A global namespace for `click` event.
* @type {string}
*/
const mouseclickEvent = 'click';
/**
* A global namespace for `keydown` event.
* @type {string}
*/
const keydownEvent = 'keydown';
/**
* A global namespace for `touchmove` event.
* @type {string}
*/
const touchmoveEvent = 'touchmove';
/**
* A global namespace for `touchend` event.
* @type {string}
*/
const touchendEvent = 'touchend';
/**
* A global namespace for `touchstart` event.
* @type {string}
*/
const touchstartEvent = 'touchstart';
/**
* A global namespace for `ArrowLeft` key.
* @type {string} e.which = 37 equivalent
*/
const keyArrowLeft = 'ArrowLeft';
/**
* A global namespace for `ArrowRight` key.
* @type {string} e.which = 39 equivalent
*/
const keyArrowRight = 'ArrowRight';
/**
* Add eventListener to an `Element` | `HTMLElement` | `Document` target.
*
* @param {HTMLElement | Element | Document | Window} element event.target
* @param {string} eventName event.type
* @param {EventListenerObject['handleEvent']} handler callback
* @param {(EventListenerOptions | boolean)=} options other event options
*/
function on(element, eventName, handler, options) {
const ops = options || false;
element.addEventListener(eventName, handler, ops);
}
/**
* Remove eventListener from an `Element` | `HTMLElement` | `Document` | `Window` target.
*
* @param {HTMLElement | Element | Document | Window} element event.target
* @param {string} eventName event.type
* @param {EventListenerObject['handleEvent']} handler callback
* @param {(EventListenerOptions | boolean)=} options other event options
*/
function off(element, eventName, handler, options) {
const ops = options || false;
element.removeEventListener(eventName, handler, ops);
}
/**
* Returns the `Window` object of a target node.
* @see https://github.com/floating-ui/floating-ui
*
* @param {(Node | HTMLElement | Element | Window)=} node target node
* @returns {globalThis}
*/
function getWindow(node) {
if (node == null) {
return window;
}
if (!(node instanceof Window)) {
const { ownerDocument } = node;
return ownerDocument ? ownerDocument.defaultView || window : window;
}
// @ts-ignore
return node;
}
/**
* Returns the `document` or the `#document` element.
* @see https://github.com/floating-ui/floating-ui
* @param {(Node | HTMLElement | Element | globalThis)=} node
* @returns {Document}
*/
function getDocument(node) {
if (node instanceof HTMLElement) return node.ownerDocument;
if (node instanceof Window) return node.document;
return window.document;
}
/**
* A global namespace for 'transitionDuration' string.
* @type {string}
*/
const transitionDuration = 'transitionDuration';
/**
* A global namespace for:
* * `transitionProperty` string for Firefox,
* * `transition` property for all other browsers.
*
* @type {string}
*/
const transitionProperty = 'transitionProperty';
/**
* Shortcut for `window.getComputedStyle(element).propertyName`
* static method.
*
* * If `element` parameter is not an `HTMLElement`, `getComputedStyle`
* throws a `ReferenceError`.
*
* @param {HTMLElement | Element} element target
* @param {string} property the css property
* @return {string} the css property value
*/
function getElementStyle(element, property) {
const computedStyle = getComputedStyle(element);
// @ts-ignore -- must use camelcase strings,
// or non-camelcase strings with `getPropertyValue`
return property in computedStyle ? computedStyle[property] : '';
}
/**
* Utility to get the computed `transitionDuration`
* from Element in miliseconds.
*
* @param {HTMLElement | Element} element target
* @return {number} the value in miliseconds
*/
function getElementTransitionDuration(element) {
const propertyValue = getElementStyle(element, transitionProperty);
const durationValue = getElementStyle(element, transitionDuration);
const durationScale = durationValue.includes('ms') ? 1 : 1000;
const duration = propertyValue && propertyValue !== 'none'
? parseFloat(durationValue) * durationScale : 0;
return !Number.isNaN(duration) ? duration : 0;
}
/**
* Returns the bounding client rect of a target `HTMLElement`.
*
* @see https://github.com/floating-ui/floating-ui
*
* @param {HTMLElement | Element} element event.target
* @param {boolean=} includeScale when *true*, the target scale is also computed
* @returns {SHORTER.BoundingClientRect} the bounding client rect object
*/
function getBoundingClientRect(element, includeScale) {
const {
width, height, top, right, bottom, left,
} = element.getBoundingClientRect();
let scaleX = 1;
let scaleY = 1;
if (includeScale && element instanceof HTMLElement) {
const { offsetWidth, offsetHeight } = element;
scaleX = offsetWidth > 0 ? Math.round(width) / offsetWidth || 1 : 1;
scaleY = offsetHeight > 0 ? Math.round(height) / offsetHeight || 1 : 1;
}
return {
width: width / scaleX,
height: height / scaleY,
top: top / scaleY,
right: right / scaleX,
bottom: bottom / scaleY,
left: left / scaleX,
x: left / scaleX,
y: top / scaleY,
};
}
/**
* Returns the `document.documentElement` or the `<html>` element.
*
* @param {(Node | HTMLElement | Element | globalThis)=} node
* @returns {HTMLElement | HTMLHtmlElement}
*/
function getDocumentElement(node) {
return getDocument(node).documentElement;
}
/**
* Utility to determine if an `HTMLElement`
* is partially visible in viewport.
*
* @param {HTMLElement | Element} element target
* @return {boolean} the query result
*/
const isElementInScrollRange = (element) => {
const { top, bottom } = getBoundingClientRect(element);
const { clientHeight } = getDocumentElement(element);
// checks bottom && top
return top <= clientHeight && bottom >= 0;
};
/**
* Checks if a page is Right To Left.
* @param {(HTMLElement | Element)=} node the target
* @returns {boolean} the query result
*/
const isRTL = (node) => getDocumentElement(node).dir === 'rtl';
/**
* Shortcut for `HTMLElement.closest` method which also works
* with children of `ShadowRoot`. The order of the parameters
* is intentional since they're both required.
*
* @see https://stackoverflow.com/q/54520554/803358
*
* @param {HTMLElement | Element} element Element to look into
* @param {string} selector the selector name
* @return {(HTMLElement | Element)?} the query result
*/
function closest(element, selector) {
return element ? (element.closest(selector)
// @ts-ignore -- break out of `ShadowRoot`
|| closest(element.getRootNode().host, selector)) : null;
}
/**
* A global array of possible `ParentNode`.
*/
const parentNodes = [Document, Node, Element, HTMLElement];
/**
* A global array with `Element` | `HTMLElement`.
*/
const elementNodes = [Element, HTMLElement];
/**
* Utility to check if target is typeof `HTMLElement`, `Element`, `Node`
* or find one that matches a selector.
*
* @param {HTMLElement | Element | string} selector the input selector or target element
* @param {(HTMLElement | Element | Node | Document)=} parent optional node to look into
* @return {(HTMLElement | Element)?} the `HTMLElement` or `querySelector` result
*/
function querySelector(selector, parent) {
const selectorIsString = typeof selector === 'string';
const lookUp = parent && parentNodes.some((x) => parent instanceof x)
? parent : getDocument();
if (!selectorIsString && [...elementNodes].some((x) => selector instanceof x)) {
return selector;
}
// @ts-ignore -- `ShadowRoot` is also a node
return selectorIsString ? lookUp.querySelector(selector) : null;
}
/**
* A shortcut for `(document|Element).querySelectorAll`.
*
* @param {string} selector the input selector
* @param {(HTMLElement | Element | Document | Node)=} parent optional node to look into
* @return {NodeListOf<HTMLElement | Element>} the query result
*/
function querySelectorAll(selector, parent) {
const lookUp = parent && parentNodes
.some((x) => parent instanceof x) ? parent : getDocument();
// @ts-ignore -- `ShadowRoot` is also a node
return lookUp.querySelectorAll(selector);
}
/**
* Shortcut for `HTMLElement.getElementsByClassName` method. Some `Node` elements
* like `ShadowRoot` do not support `getElementsByClassName`.
*
* @param {string} selector the class name
* @param {(HTMLElement | Element | Document)=} parent optional Element to look into
* @return {HTMLCollectionOf<HTMLElement | Element>} the 'HTMLCollection'
*/
function getElementsByClassName(selector, parent) {
const lookUp = parent && parentNodes.some((x) => parent instanceof x)
? parent : getDocument();
return lookUp.getElementsByClassName(selector);
}
/**
* Shortcut for `HTMLElement.getAttribute()` method.
* @param {HTMLElement | Element} element target element
* @param {string} attribute attribute name
*/
const getAttribute = (element, attribute) => element.getAttribute(attribute);
/** @type {Map<HTMLElement | Element, any>} */
const TimeCache = new Map();
/**
* An interface for one or more `TimerHandler`s per `Element`.
* @see https://github.com/thednp/navbar.js/
*/
const Timer = {
/**
* Sets a new timeout timer for an element, or element -> key association.
* @param {HTMLElement | Element | string} target target element
* @param {ReturnType<TimerHandler>} callback the callback
* @param {number} delay the execution delay
* @param {string=} key a unique
*/
set: (target, callback, delay, key) => {
const element = querySelector(target);
if (!element) return;
if (key && key.length) {
if (!TimeCache.has(element)) {
TimeCache.set(element, new Map());
}
const keyTimers = TimeCache.get(element);
keyTimers.set(key, setTimeout(callback, delay));
} else {
TimeCache.set(element, setTimeout(callback, delay));
}
},
/**
* Returns the timer associated with the target.
* @param {HTMLElement | Element | string} target target element
* @param {string=} key a unique
* @returns {number?} the timer
*/
get: (target, key) => {
const element = querySelector(target);
if (!element) return null;
const keyTimers = TimeCache.get(element);
if (key && key.length && keyTimers && keyTimers.get) {
return keyTimers.get(key) || null;
}
return keyTimers || null;
},
/**
* Clears the element's timer.
* @param {HTMLElement | Element | string} target target element
* @param {string=} key a unique key
*/
clear: (target, key) => {
const element = querySelector(target);
if (!element) return;
if (key && key.length) {
const keyTimers = TimeCache.get(element);
if (keyTimers && keyTimers.get) {
clearTimeout(keyTimers.get(key));
keyTimers.delete(key);
if (keyTimers.size === 0) {
TimeCache.delete(element);
}
}
} else {
clearTimeout(TimeCache.get(element));
TimeCache.delete(element);
}
},
};
/**
* Utility to force re-paint of an `HTMLElement` target.
*
* @param {HTMLElement | Element} element is the target
* @return {number} the `Element.offsetHeight` value
*/
// @ts-ignore
const reflow = (element) => element.offsetHeight;
/**
* A global namespace for most scroll event listeners.
* @type {Partial<AddEventListenerOptions>}
*/
const passiveHandler = { passive: true };
/**
* A global namespace for 'transitionend' string.
* @type {string}
*/
const transitionEndEvent = 'transitionend';
/**
* A global namespace for 'transitionDelay' string.
* @type {string}
*/
const transitionDelay = 'transitionDelay';
/**
* Utility to get the computed `transitionDelay`
* from Element in miliseconds.
*
* @param {HTMLElement | Element} element target
* @return {number} the value in miliseconds
*/
function getElementTransitionDelay(element) {
const propertyValue = getElementStyle(element, transitionProperty);
const delayValue = getElementStyle(element, transitionDelay);
const delayScale = delayValue.includes('ms') ? 1 : 1000;
const duration = propertyValue && propertyValue !== 'none'
? parseFloat(delayValue) * delayScale : 0;
return !Number.isNaN(duration) ? duration : 0;
}
/**
* Utility to make sure callbacks are consistently
* called when transition ends.
*
* @param {HTMLElement | Element} element target
* @param {EventListener} handler `transitionend` callback
*/
function emulateTransitionEnd(element, handler) {
let called = 0;
const endEvent = new Event(transitionEndEvent);
const duration = getElementTransitionDuration(element);
const delay = getElementTransitionDelay(element);
if (duration) {
/**
* Wrap the handler in on -> off callback
* @param {TransitionEvent} e Event object
*/
const transitionEndWrapper = (e) => {
if (e.target === element) {
handler.apply(element, [e]);
off(element, transitionEndEvent, transitionEndWrapper);
called = 1;
}
};
on(element, transitionEndEvent, transitionEndWrapper);
setTimeout(() => {
if (!called) element.dispatchEvent(endEvent);
}, duration + delay + 17);
} else {
handler.apply(element, [endEvent]);
}
}
/**
* Shortcut for `Object.assign()` static method.
* @param {Record<string, any>} obj a target object
* @param {Record<string, any>} source a source object
*/
const ObjectAssign = (obj, source) => Object.assign(obj, source);
/**
* Shortcut for the `Element.dispatchEvent(Event)` method.
*
* @param {HTMLElement | Element} element is the target
* @param {Event} event is the `Event` object
*/
const dispatchEvent = (element, event) => element.dispatchEvent(event);
/** @type {Map<string, Map<HTMLElement | Element, Record<string, any>>>} */
const componentData = new Map();
/**
* An interface for web components background data.
* @see https://github.com/thednp/bootstrap.native/blob/master/src/components/base-component.js
*/
const Data = {
/**
* Sets web components data.
* @param {HTMLElement | Element | string} target target element
* @param {string} component the component's name or a unique key
* @param {Record<string, any>} instance the component instance
*/
set: (target, component, instance) => {
const element = querySelector(target);
if (!element) return;
if (!componentData.has(component)) {
componentData.set(component, new Map());
}
const instanceMap = componentData.get(component);
// @ts-ignore - not undefined, but defined right above
instanceMap.set(element, instance);
},
/**
* Returns all instances for specified component.
* @param {string} component the component's name or a unique key
* @returns {Map<HTMLElement | Element, Record<string, any>>?} all the component instances
*/
getAllFor: (component) => {
const instanceMap = componentData.get(component);
return instanceMap || null;
},
/**
* Returns the instance associated with the target.
* @param {HTMLElement | Element | string} target target element
* @param {string} component the component's name or a unique key
* @returns {Record<string, any>?} the instance
*/
get: (target, component) => {
const element = querySelector(target);
const allForC = Data.getAllFor(component);
const instance = element && allForC && allForC.get(element);
return instance || null;
},
/**
* Removes web components data.
* @param {HTMLElement | Element | string} target target element
* @param {string} component the component's name or a unique key
*/
remove: (target, component) => {
const element = querySelector(target);
const instanceMap = componentData.get(component);
if (!instanceMap || !element) return;
instanceMap.delete(element);
if (instanceMap.size === 0) {
componentData.delete(component);
}
},
};
/**
* An alias for `Data.get()`.
* @type {SHORTER.getInstance<any>}
*/
const getInstance = (target, component) => Data.get(target, component);
/**
* Returns a namespaced `CustomEvent` specific to each component.
* @param {string} EventType Event.type
* @param {Record<string, any>=} config Event.options | Event.properties
* @returns {SHORTER.OriginalEvent} a new namespaced event
*/
function OriginalEvent(EventType, config) {
const OriginalCustomEvent = new CustomEvent(EventType, {
cancelable: true, bubbles: true,
});
if (config instanceof Object) {
ObjectAssign(OriginalCustomEvent, config);
}
return OriginalCustomEvent;
}
/**
* Add class to `HTMLElement.classList`.
*
* @param {HTMLElement | Element} element target
* @param {string} classNAME to add
*/
function addClass(element, classNAME) {
element.classList.add(classNAME);
}
/**
* Check class in `HTMLElement.classList`.
*
* @param {HTMLElement | Element} element target
* @param {string} classNAME to check
* @return {boolean}
*/
function hasClass(element, classNAME) {
return element.classList.contains(classNAME);
}
/**
* Remove class from `HTMLElement.classList`.
*
* @param {HTMLElement | Element} element target
* @param {string} classNAME to remove
*/
function removeClass(element, classNAME) {
element.classList.remove(classNAME);
}
/**
* Global namespace for most components active class.
*/
const activeClass = 'active';
/**
* Global namespace for most components `target` option.
*/
const dataBsTarget = 'data-bs-target';
/** @type {string} */
const carouselString = 'carousel';
/** @type {string} */
const carouselComponent = 'Carousel';
/**
* Global namespace for most components `parent` option.
*/
const dataBsParent = 'data-bs-parent';
/**
* Global namespace for most components `container` option.
*/
const dataBsContainer = 'data-bs-container';
/**
* Returns the `Element` that THIS one targets
* via `data-bs-target`, `href`, `data-bs-parent` or `data-bs-container`.
*
* @param {HTMLElement | Element} element the target element
* @returns {(HTMLElement | Element)?} the query result
*/
function getTargetElement(element) {
const targetAttr = [dataBsTarget, dataBsParent, dataBsContainer, 'href'];
const doc = getDocument(element);
return targetAttr.map((att) => {
const attValue = getAttribute(element, att);
if (attValue) {
return att === dataBsParent ? closest(element, attValue) : querySelector(attValue, doc);
}
return null;
}).filter((x) => x)[0];
}
/**
* The raw value or a given component option.
*
* @typedef {string | HTMLElement | Function | number | boolean | null} niceValue
*/
/**
* Utility to normalize component options
*
* @param {any} value the input value
* @return {niceValue} the normalized value
*/
function normalizeValue(value) {
if (value === 'true') { // boolean
return true;
}
if (value === 'false') { // boolean
return false;
}
if (!Number.isNaN(+value)) { // number
return +value;
}
if (value === '' || value === 'null') { // null
return null;
}
// string / function / HTMLElement / object
return value;
}
/**
* Shortcut for `Object.keys()` static method.
* @param {Record<string, any>} obj a target object
* @returns {string[]}
*/
const ObjectKeys = (obj) => Object.keys(obj);
/**
* Shortcut for `String.toLowerCase()`.
*
* @param {string} source input string
* @returns {string} lowercase output string
*/
const toLowerCase = (source) => source.toLowerCase();
/**
* Utility to normalize component options.
*
* @param {HTMLElement | Element} element target
* @param {Record<string, any>} defaultOps component default options
* @param {Record<string, any>} inputOps component instance options
* @param {string=} ns component namespace
* @return {Record<string, any>} normalized component options object
*/
function normalizeOptions(element, defaultOps, inputOps, ns) {
// @ts-ignore -- our targets are always `HTMLElement`
const data = { ...element.dataset };
/** @type {Record<string, any>} */
const normalOps = {};
/** @type {Record<string, any>} */
const dataOps = {};
const title = 'title';
ObjectKeys(data).forEach((k) => {
const key = ns && k.includes(ns)
? k.replace(ns, '').replace(/[A-Z]/, (match) => toLowerCase(match))
: k;
dataOps[key] = normalizeValue(data[k]);
});
ObjectKeys(inputOps).forEach((k) => {
inputOps[k] = normalizeValue(inputOps[k]);
});
ObjectKeys(defaultOps).forEach((k) => {
if (k in inputOps) {
normalOps[k] = inputOps[k];
} else if (k in dataOps) {
normalOps[k] = dataOps[k];
} else {
normalOps[k] = k === title
? getAttribute(element, title)
: defaultOps[k];
}
});
return normalOps;
}
var version = "4.1.0alpha1";
const Version = version;
/* Native JavaScript for Bootstrap 5 | Base Component
----------------------------------------------------- */
/** Returns a new `BaseComponent` instance. */
class BaseComponent {
/**
* @param {HTMLElement | Element | string} target `Element` or selector string
* @param {BSN.ComponentOptions=} config component instance options
*/
constructor(target, config) {
const self = this;
const element = querySelector(target);
if (!element) {
throw Error(`${self.name} Error: "${target}" is not a valid selector.`);
}
/** @static @type {BSN.ComponentOptions} */
self.options = {};
const prevInstance = Data.get(element, self.name);
if (prevInstance) prevInstance.dispose();
/** @type {HTMLElement | Element} */
self.element = element;
if (self.defaults && Object.keys(self.defaults).length) {
self.options = normalizeOptions(element, self.defaults, (config || {}), 'bs');
}
Data.set(element, self.name, self);
}
/* eslint-disable */
/** @static */
get version() { return Version; }
/* eslint-enable */
/** @static */
get name() { return this.constructor.name; }
/** @static */
// @ts-ignore
get defaults() { return this.constructor.defaults; }
/**
* Removes component from target element;
*/
dispose() {
const self = this;
Data.remove(self.element, self.name);
// @ts-ignore
ObjectKeys(self).forEach((prop) => { self[prop] = null; });
}
}
/* Native JavaScript for Bootstrap 5 | Carousel
----------------------------------------------- */
// CAROUSEL PRIVATE GC
// ===================
const carouselSelector = `[data-bs-ride="${carouselString}"]`;
const carouselItem = `${carouselString}-item`;
const dataBsSlideTo = 'data-bs-slide-to';
const dataBsSlide = 'data-bs-slide';
const pausedClass = 'paused';
const carouselDefaults = {
pause: 'hover',
keyboard: false,
touch: true,
interval: 5000,
};
/**
* Static method which returns an existing `Carousel` instance associated
* to a target `Element`.
*
* @type {BSN.GetInstance<Carousel>}
*/
const getCarouselInstance = (element) => getInstance(element, carouselComponent);
/**
* A `Carousel` initialization callback.
* @type {BSN.InitCallback<Carousel>}
*/
const carouselInitCallback = (element) => new Carousel(element);
let startX = 0;
let currentX = 0;
let endX = 0;
// CAROUSEL CUSTOM EVENTS
// ======================
const carouselSlideEvent = OriginalEvent(`slide.bs.${carouselString}`);
const carouselSlidEvent = OriginalEvent(`slid.bs.${carouselString}`);
// CAROUSEL EVENT HANDLERS
// =======================
/**
* The `transitionend` event listener of the `Carousel`.
* @param {Carousel} self the `Carousel` instance
*/
function carouselTransitionEndHandler(self) {
const {
index, direction, element, slides, options,
} = self;
// discontinue disposed instances
if (self.isAnimating && getCarouselInstance(element)) {
const activeItem = getActiveIndex(self);
const orientation = direction === 'left' ? 'next' : 'prev';
const directionClass = direction === 'left' ? 'start' : 'end';
addClass(slides[index], activeClass);
removeClass(slides[activeItem], activeClass);
removeClass(slides[index], `${carouselItem}-${orientation}`);
removeClass(slides[index], `${carouselItem}-${directionClass}`);
removeClass(slides[activeItem], `${carouselItem}-${directionClass}`);
dispatchEvent(element, carouselSlidEvent);
Timer.clear(element, dataBsSlide);
// check for element, might have been disposed
if (!getDocument(element).hidden && options.interval
&& !self.isPaused) {
self.cycle();
}
}
}
/**
* Handles the `mouseenter` / `touchstart` events when *options.pause*
* is set to `hover`.
*
* @this {HTMLElement | Element}
*/
function carouselPauseHandler() {
const element = this;
const self = getCarouselInstance(element);
if (self && !self.isPaused && !Timer.get(element, pausedClass)) {
addClass(element, pausedClass);
}
}
/**
* Handles the `mouseleave` / `touchend` events when *options.pause*
* is set to `hover`.
*
* @this {HTMLElement | Element}
*/
function carouselResumeHandler() {
const element = this;
const self = getCarouselInstance(element);
if (self && self.isPaused && !Timer.get(element, pausedClass)) {
self.cycle();
}
}
/**
* Handles the `click` event for the `Carousel` indicators.
*
* @this {HTMLElement}
* @param {MouseEvent} e the `Event` object
*/
function carouselIndicatorHandler(e) {
e.preventDefault();
const indicator = this;
const element = closest(indicator, carouselSelector) || getTargetElement(indicator);
if (!element) return;
const self = getCarouselInstance(element);
if (!self || self.isAnimating) return;
// @ts-ignore
const newIndex = +getAttribute(indicator, dataBsSlideTo);
if (indicator && !hasClass(indicator, activeClass) // event target is not active
&& !Number.isNaN(newIndex)) { // AND has the specific attribute
self.to(newIndex); // do the slide
}
}
/**
* Handles the `click` event for the `Carousel` arrows.
*
* @this {HTMLElement}
* @param {MouseEvent} e the `Event` object
*/
function carouselControlsHandler(e) {
e.preventDefault();
const control = this;
const element = closest(control, carouselSelector) || getTargetElement(control);
const self = element && getCarouselInstance(element);
if (!self || self.isAnimating) return;
const orientation = getAttribute(control, dataBsSlide);
if (orientation === 'next') {
self.next();
} else if (orientation === 'prev') {
self.prev();
}
}
/**
* Handles the keyboard `keydown` event for the visible `Carousel` elements.
*
* @param {KeyboardEvent} e the `Event` object
*/
function carouselKeyHandler({ code }) {
const [element] = [...querySelectorAll(carouselSelector)]
.filter((x) => isElementInScrollRange(x));
const self = getCarouselInstance(element);
if (!self) return;
const RTL = isRTL();
const arrowKeyNext = !RTL ? keyArrowRight : keyArrowLeft;
const arrowKeyPrev = !RTL ? keyArrowLeft : keyArrowRight;
if (code === arrowKeyPrev) self.prev();
else if (code === arrowKeyNext) self.next();
}
// CAROUSEL TOUCH HANDLERS
// =======================
/**
* Handles the `touchdown` event for the `Carousel` element.
*
* @this {HTMLElement | Element}
* @param {TouchEvent} e the `Event` object
*/
function carouselTouchDownHandler(e) {
const element = this;
const self = getCarouselInstance(element);
if (!self || self.isTouch) { return; }
startX = e.changedTouches[0].pageX;
// @ts-ignore
if (element.contains(e.target)) {
self.isTouch = true;
toggleCarouselTouchHandlers(self, true);
}
}
/**
* Handles the `touchmove` event for the `Carousel` element.
*
* @this {HTMLElement | Element}
* @param {TouchEvent} e
*/
function carouselTouchMoveHandler(e) {
const { changedTouches, type } = e;
const self = getCarouselInstance(this);
if (!self || !self.isTouch) { return; }
currentX = changedTouches[0].pageX;
// cancel touch if more than one changedTouches detected
if (type === touchmoveEvent && changedTouches.length > 1) {
e.preventDefault();
}
}
/**
* Handles the `touchend` event for the `Carousel` element.
*
* @this {HTMLElement | Element}
* @param {TouchEvent} e
*/
function carouselTouchEndHandler(e) {
const element = this;
const self = getCarouselInstance(element);
if (!self || !self.isTouch) { return; }
endX = currentX || e.changedTouches[0].pageX;
if (self.isTouch) {
// the event target is outside the carousel OR carousel doens't include the related target
// @ts-ignore
if ((!element.contains(e.target) || !element.contains(e.relatedTarget))
&& Math.abs(startX - endX) < 75) { // AND swipe distance is less than 75px
// when the above conditions are satisfied, no need to continue
return;
} // OR determine next index to slide to
if (currentX < startX) {
self.index += 1;
} else if (currentX > startX) {
self.index -= 1;
}
self.isTouch = false;
self.to(self.index); // do the slide
toggleCarouselTouchHandlers(self); // remove touch events handlers
}
}
// CAROUSEL PRIVATE METHODS
// ========================
/**
* Sets active indicator for the `Carousel` instance.
* @param {Carousel} self the `Carousel` instance
* @param {number} pageIndex the index of the new active indicator
*/
function activateCarouselIndicator(self, pageIndex) {
const { indicators } = self;
[...indicators].forEach((x) => removeClass(x, activeClass));
if (self.indicators[pageIndex]) addClass(indicators[pageIndex], activeClass);
}
/**
* Toggles the touch event listeners for a given `Carousel` instance.
* @param {Carousel} self the `Carousel` instance
* @param {boolean=} add when `TRUE` event listeners are added
*/
function toggleCarouselTouchHandlers(self, add) {
const { element } = self;
const action = add ? on : off;
action(element, touchmoveEvent, carouselTouchMoveHandler, passiveHandler);
action(element, touchendEvent, carouselTouchEndHandler, passiveHandler);
}
/**
* Toggles all event listeners for a given `Carousel` instance.
* @param {Carousel} self the `Carousel` instance
* @param {boolean=} add when `TRUE` event listeners are added
*/
function toggleCarouselHandlers(self, add) {
const {
element, options, slides, controls, indicators,
} = self;
const {
touch, pause, interval, keyboard,
} = options;
const action = add ? on : off;
if (pause && interval) {
action(element, mouseenterEvent, carouselPauseHandler);
action(element, mouseleaveEvent, carouselResumeHandler);
action(element, touchstartEvent, carouselPauseHandler, passiveHandler);
action(element, touchendEvent, carouselResumeHandler, passiveHandler);
}
if (touch && slides.length > 1) {
action(element, touchstartEvent, carouselTouchDownHandler, passiveHandler);
}
if (controls.length) {
controls.forEach((arrow) => {
if (arrow) action(arrow, mouseclickEvent, carouselControlsHandler);
});
}
if (indicators.length) {
indicators.forEach((indicator) => {
action(indicator, mouseclickEvent, carouselIndicatorHandler);
});
}
// @ts-ignore
if (keyboard) action(getWindow(element), keydownEvent, carouselKeyHandler);
}
/**
* Returns the index of the current active item.
* @param {Carousel} self the `Carousel` instance
* @returns {number} the query result
*/
function getActiveIndex(self) {
const { slides, element } = self;
const activeItem = querySelector(`.${carouselItem}.${activeClass}`, element);
// @ts-ignore
return [...slides].indexOf(activeItem);
}
// CAROUSEL DEFINITION
// ===================
/** Creates a new `Carousel` instance. */
class Carousel extends BaseComponent {
/**
* @param {HTMLElement | Element | string} target mostly a `.carousel` element
* @param {BSN.Options.Carousel=} config instance options
*/
constructor(target, config) {
super(target, config);
// bind
const self = this;
// additional properties
/** @type {string} */
self.direction = isRTL() ? 'right' : 'left';
/** @type {number} */
self.index = 0;
/** @type {boolean} */
self.isTouch = false;
// initialization element
const { element } = self;
// carousel elements
// a LIVE collection is prefferable
self.slides = getElementsByClassName(carouselItem, element);
const { slides } = self;
// invalidate when not enough items
// no need to go further
if (slides.length < 2) { return; }
self.controls = [
...querySelectorAll(`[${dataBsSlide}]`, element),
...querySelectorAll(`[${dataBsSlide}][${dataBsTarget}="#${element.id}"]`),
];
/** @type {(HTMLElement | Element)?} */
self.indicator = querySelector(`.${carouselString}-indicators`, element);
// a LIVE collection is prefferable
/** @type {(HTMLElement | Element)[]} */
self.indicators = [
...(self.indicator ? querySelectorAll(`[${dataBsSlideTo}]`, self.indicator) : []),
...querySelectorAll(`[${dataBsSlideTo}][${dataBsTarget}="#${element.id}"]`),
];
// set JavaScript and DATA API options
const { options } = self;
// don't use TRUE as interval, it's actually 0, use the default 5000ms better
self.options.interval = options.interval === true
? carouselDefaults.interval
: options.interval;
// set first slide active if none
if (getActiveIndex(self) < 0) {
if (slides.length) addClass(slides[0], activeClass);
if (self.indicators.length) activateCarouselIndicator(self, 0);
}
// attach event handlers
toggleCarouselHandlers(self, true);
// start to cycle if interval is set
if (options.interval) self.cycle();
}
/* eslint-disable */
/**
* Returns component name string.
* @readonly @static
*/
get name() { return carouselComponent; }
/**
* Returns component default options.
* @readonly @static
*/
get defaults() { return carouselDefaults; }
/* eslint-enable */
/**
* Check if instance is paused.
* @returns {boolean}
*/
get isPaused() {
return hasClass(this.element, pausedClass);
}
/**
* Check if instance is animating.
* @returns {boolean}
*/
get isAnimating() {
return querySelector(`.${carouselItem}-next,.${carouselItem}-prev`, this.element) !== null;
}
// CAROUSEL PUBLIC METHODS
// =======================
/** Slide automatically through items. */
cycle() {
const self = this;
const { element, options, isPaused } = self;
Timer.clear(element, carouselString);
if (isPaused) {
Timer.clear(element, pausedClass);
removeClass(element, pausedClass);
}
Timer.set(element, () => {
if (!self.isPaused && isElementInScrollRange(element)) {
self.index += 1;
self.to(self.index);
}
}, options.interval, carouselString);
}
/** Pause the automatic cycle. */
pause() {
const self = this;
const { element, options } = self;
if (!self.isPaused && options.interval) {
addClass(element, pausedClass);
Timer.set(element, () => {}, 1, pausedClass);
}
}
/** Slide to the next item. */
next() {
const self = this;
if (!self.isAnimating) { self.index += 1; self.to(self.index); }
}
/** Slide to the previous item. */
prev() {
const self = this;
if (!self.isAnimating) { self.index -= 1; self.to(self.index); }
}
/**
* Jump to the item with the `idx` index.
* @param {number} idx the index of the item to jump to
*/
to(idx) {
const self = this;
const {
element, slides, options,
} = self;
const activeItem = getActiveIndex(self);
const RTL = isRTL();
let next = idx;
// when controled via methods, make sure to check again
// first return if we're on the same item #227
if (self.isAnimating || activeItem === next) return;
// determine transition direction
if ((activeItem < next) || (activeItem === 0 && next === slides.length - 1)) {
self.direction = RTL ? 'right' : 'left'; // next
} else if ((activeItem > next) || (activeItem === slides.length - 1 && next === 0)) {
self.direction = RTL ? 'left' : 'right'; // prev
}
const { direction } = self;
// find the right next index
if (next < 0) { next = slides.length - 1; } else if (next >= slides.length) { next = 0; }
// orientation, class name, eventProperties
const orientation = direction === 'left' ? 'next' : 'prev';
const directionClass = direction === 'left' ? 'start' : 'end';
const eventProperties = {
relatedTarget: slides[next],
from: activeItem,
to: next,
direction,
};
// update event properties
ObjectAssign(carouselSlideEvent, eventProperties);
ObjectAssign(carouselSlidEvent, eventProperties);
// discontinue when prevented
dispatchEvent(element, carouselSlideEvent);
if (carouselSlideEvent.defaultPrevented) return;
// update index
self.index = next;
activateCarouselIndicator(self, next);
if (getElementTransitionDuration(slides[next]) && hasClass(element, 'slide')) {
Timer.set(element, () => {
addClass(slides[next], `${carouselItem}-${orientation}`);
reflow(slides[next]);
addClass(slides[next], `${carouselItem}-${directionClass}`);
addClass(slides[activeItem], `${carouselItem}-${directionClass}`);
emulateTransitionEnd(slides[next], () => carouselTransitionEndHandler(self));
}, 17, dataBsSlide);
} else {
addClass(slides[next], activeClass);
removeClass(slides[activeItem], activeClass);
Timer.set(element, () => {
Timer.clear(element, dataBsSlide);
// check for element, might have been disposed
if (element && options.interval && !self.isPaused) {
self.cycle();
}
dispatchEvent(element, carouselSlidEvent);
}, 17, dataBsSlide);
}
}
/** Remove `Carousel` component from target. */
dispose() {
const self = this;
const { slides } = self;
const itemClasses = ['start', 'end', 'prev', 'next'];
[...slides].forEach((slide, idx) => {
if (hasClass(slide, activeClass)) activateCarouselIndicator(self, idx);
itemClasses.forEach((c) => removeClass(slide, `${carouselItem}-${c}`));
});
toggleCarouselHandlers(self);
super.dispose();
}
}
ObjectAssign(Carousel, {
selector: carouselSelector,
init: carouselInitCallback,
getInstance: getCarouselInstance,
});
return Carousel;
}));
|
/** @license React vundefined
* react.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.React = {}));
}(this, (function (exports) { 'use strict';
var ReactVersion = '18.0.0-55d75005b-20211011';
// ATTENTION
// When adding new symbols to this file,
// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var REACT_ELEMENT_TYPE = 0xeac7;
var REACT_PORTAL_TYPE = 0xeaca;
exports.Fragment = 0xeacb;
exports.StrictMode = 0xeacc;
exports.Profiler = 0xead2;
var REACT_PROVIDER_TYPE = 0xeacd;
var REACT_CONTEXT_TYPE = 0xeace;
var REACT_FORWARD_REF_TYPE = 0xead0;
exports.Suspense = 0xead1;
exports.SuspenseList = 0xead8;
var REACT_MEMO_TYPE = 0xead3;
var REACT_LAZY_TYPE = 0xead4;
var REACT_SCOPE_TYPE = 0xead7;
var REACT_OPAQUE_ID_TYPE = 0xeae0;
var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1;
var REACT_OFFSCREEN_TYPE = 0xeae2;
var REACT_LEGACY_HIDDEN_TYPE = 0xeae3;
var REACT_CACHE_TYPE = 0xeae4;
if (typeof Symbol === 'function' && Symbol.for) {
var symbolFor = Symbol.for;
REACT_ELEMENT_TYPE = symbolFor('react.element');
REACT_PORTAL_TYPE = symbolFor('react.portal');
exports.Fragment = symbolFor('react.fragment');
exports.StrictMode = symbolFor('react.strict_mode');
exports.Profiler = symbolFor('react.profiler');
REACT_PROVIDER_TYPE = symbolFor('react.provider');
REACT_CONTEXT_TYPE = symbolFor('react.context');
REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref');
exports.Suspense = symbolFor('react.suspense');
exports.SuspenseList = symbolFor('react.suspense_list');
REACT_MEMO_TYPE = symbolFor('react.memo');
REACT_LAZY_TYPE = symbolFor('react.lazy');
REACT_SCOPE_TYPE = symbolFor('react.scope');
REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id');
REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode');
REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen');
REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden');
REACT_CACHE_TYPE = symbolFor('react.cache');
}
var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator';
function getIteratorFn(maybeIterable) {
if (maybeIterable === null || typeof maybeIterable !== 'object') {
return null;
}
var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
if (typeof maybeIterator === 'function') {
return maybeIterator;
}
return null;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
var _assign = function (to, from) {
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
};
var assign = Object.assign || function (target, sources) {
if (target == null) {
throw new TypeError('Object.assign target cannot be null or undefined');
}
var to = Object(target);
for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) {
var nextSource = arguments[nextIndex];
if (nextSource != null) {
_assign(to, Object(nextSource));
}
}
return to;
};
/**
* Keeps track of the current dispatcher.
*/
var ReactCurrentDispatcher = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
/**
* Keeps track of the current batch's configuration such as how long an update
* should suspend for if it needs to.
*/
var ReactCurrentBatchConfig = {
transition: 0
};
{
ReactCurrentBatchConfig._updatedFibers = new Set();
}
var ReactCurrentActQueue = {
current: null,
// Our internal tests use a custom implementation of `act` that works by
// mocking the Scheduler package. Use this field to disable the `act` warning.
// TODO: Maybe the warning should be disabled by default, and then turned
// on at the testing frameworks layer? Instead of what we do now, which
// is check if a `jest` global is defined.
disableActWarning: false,
// Used to reproduce behavior of `batchedUpdates` in legacy mode.
isBatchingLegacy: false,
didScheduleLegacyUpdate: false
};
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
var ReactDebugCurrentFrame = {};
var currentExtraStackFrame = null;
function setExtraStackFrame(stack) {
{
currentExtraStackFrame = stack;
}
}
{
ReactDebugCurrentFrame.setExtraStackFrame = function (stack) {
{
currentExtraStackFrame = stack;
}
}; // Stack implementation injected by the current renderer.
ReactDebugCurrentFrame.getCurrentStack = null;
ReactDebugCurrentFrame.getStackAddendum = function () {
var stack = ''; // Add an extra top frame while an element is being validated
if (currentExtraStackFrame) {
stack += currentExtraStackFrame;
} // Delegate to the injected renderer-specific implementation
var impl = ReactDebugCurrentFrame.getCurrentStack;
if (impl) {
stack += impl() || '';
}
return stack;
};
}
var ReactSharedInternals = {
ReactCurrentDispatcher: ReactCurrentDispatcher,
ReactCurrentBatchConfig: ReactCurrentBatchConfig,
ReactCurrentOwner: ReactCurrentOwner,
// Used by renderers to avoid bundling object-assign twice in UMD bundles:
assign: assign
};
{
ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue;
}
// by calls to these methods by a Babel plugin.
//
// In PROD (or in packages without access to React internals),
// they are left as they are instead.
function warn(format) {
{
{
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
printWarning('warn', format, args);
}
}
}
function error(format) {
{
{
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
printWarning('error', format, args);
}
}
}
function printWarning(level, format, args) {
// When changing this logic, you might want to also
// update consoleWithStackDev.www.js as well.
{
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
var stack = ReactDebugCurrentFrame.getStackAddendum();
if (stack !== '') {
format += '%s';
args = args.concat([stack]);
} // eslint-disable-next-line react-internal/safe-string-coercion
var argsWithFormat = args.map(function (item) {
return String(item);
}); // Careful: RN currently depends on this prefix
argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
// breaks IE9: https://github.com/facebook/react/issues/13610
// eslint-disable-next-line react-internal/no-production-logging
Function.prototype.apply.call(console[level], console, argsWithFormat);
}
}
var didWarnStateUpdateForUnmountedComponent = {};
function warnNoop(publicInstance, callerName) {
{
var _constructor = publicInstance.constructor;
var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';
var warningKey = componentName + "." + callerName;
if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
return;
}
error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);
didWarnStateUpdateForUnmountedComponent[warningKey] = true;
}
}
/**
* This is the abstract API for an update queue.
*/
var ReactNoopUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function (publicInstance) {
return false;
},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {?function} callback Called after component is updated.
* @param {?string} callerName name of the calling function in the public API.
* @internal
*/
enqueueForceUpdate: function (publicInstance, callback, callerName) {
warnNoop(publicInstance, 'forceUpdate');
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @param {?function} callback Called after component is updated.
* @param {?string} callerName name of the calling function in the public API.
* @internal
*/
enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {
warnNoop(publicInstance, 'replaceState');
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @param {?function} callback Called after component is updated.
* @param {?string} Name of the calling function in the public API.
* @internal
*/
enqueueSetState: function (publicInstance, partialState, callback, callerName) {
warnNoop(publicInstance, 'setState');
}
};
var emptyObject = {};
{
Object.freeze(emptyObject);
}
/**
* Base class helpers for the updating state of a component.
*/
function Component(props, context, updater) {
this.props = props;
this.context = context; // If a component has string refs, we will assign a different object later.
this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
Component.prototype.isReactComponent = {};
/**
* Sets a subset of the state. Always use this to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* When a function is provided to setState, it will be called at some point in
* the future (not synchronously). It will be called with the up to date
* component arguments (state, props, context). These values can be different
* from this.* because your function may be called after receiveProps but before
* shouldComponentUpdate, and this new state, props, and context will not yet be
* assigned to this.
*
* @param {object|function} partialState Next partial state or function to
* produce next partial state to be merged with current state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
Component.prototype.setState = function (partialState, callback) {
if (typeof partialState !== 'object' && typeof partialState !== 'function' && partialState != null) {
throw Error( 'setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.' );
}
this.updater.enqueueSetState(this, partialState, callback, 'setState');
};
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
Component.prototype.forceUpdate = function (callback) {
this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};
/**
* Deprecated APIs. These APIs used to exist on classic React classes but since
* we would like to deprecate them, we're not going to move them over to this
* modern base class. Instead, we define a getter that warns if it's accessed.
*/
{
var deprecatedAPIs = {
isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
};
var defineDeprecationWarning = function (methodName, info) {
Object.defineProperty(Component.prototype, methodName, {
get: function () {
warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);
return undefined;
}
});
};
for (var fnName in deprecatedAPIs) {
if (deprecatedAPIs.hasOwnProperty(fnName)) {
defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
}
}
}
function ComponentDummy() {}
ComponentDummy.prototype = Component.prototype;
/**
* Convenience component with default shallow equality check for sCU.
*/
function PureComponent(props, context, updater) {
this.props = props;
this.context = context; // If a component has string refs, we will assign a different object later.
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
}
var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods.
assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true;
// an immutable object with a single mutable value
function createRef() {
var refObject = {
current: null
};
{
Object.seal(refObject);
}
return refObject;
}
var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
function isArray(a) {
return isArrayImpl(a);
}
/*
* The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
* and Temporal.* types. See https://github.com/facebook/react/pull/22064.
*
* The functions in this module will throw an easier-to-understand,
* easier-to-debug exception with a clear errors message message explaining the
* problem. (Instead of a confusing exception thrown inside the implementation
* of the `value` object).
*/
// $FlowFixMe only called in DEV, so void return is not possible.
function typeName(value) {
{
// toStringTag is needed for namespaced types like Temporal.Instant
var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
return type;
}
} // $FlowFixMe only called in DEV, so void return is not possible.
function willCoercionThrow(value) {
{
if (value !== null && typeof value === 'object' && value.$$typeof === REACT_OPAQUE_ID_TYPE) {
// OpaqueID type is expected to throw, so React will handle it. Not sure if
// it's expected that string coercion will throw, but we'll assume it's OK.
// See https://github.com/facebook/react/issues/20127.
return;
}
try {
testStringCoercion(value);
return false;
} catch (e) {
return true;
}
}
}
function testStringCoercion(value) {
// If you ended up here by following an exception call stack, here's what's
// happened: you supplied an object or symbol value to React (as a prop, key,
// DOM attribute, CSS property, string ref, etc.) and when React tried to
// coerce it to a string using `'' + value`, an exception was thrown.
//
// The most common types that will cause this exception are `Symbol` instances
// and Temporal objects like `Temporal.Instant`. But any object that has a
// `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
// exception. (Library authors do this to prevent users from using built-in
// numeric operators like `+` or comparison operators like `>=` because custom
// methods are needed to perform accurate arithmetic or comparison.)
//
// To fix the problem, coerce this object or symbol value to a string before
// passing it to React. The most reliable way is usually `String(value)`.
//
// To find which value is throwing, check the browser or debugger console.
// Before this exception was thrown, there should be `console.error` output
// that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
// problem and how that type was used: key, atrribute, input value prop, etc.
// In most cases, this console output also shows the component and its
// ancestor components where the exception happened.
//
// eslint-disable-next-line react-internal/safe-string-coercion
return '' + value;
}
function checkKeyStringCoercion(value) {
{
if (willCoercionThrow(value)) {
error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
}
}
}
function getWrappedName(outerType, innerType, wrapperName) {
var displayName = outerType.displayName;
if (displayName) {
return displayName;
}
var functionName = innerType.displayName || innerType.name || '';
return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
} // Keep in sync with react-reconciler/getComponentNameFromFiber
function getContextName(type) {
return type.displayName || 'Context';
} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
function getComponentNameFromType(type) {
if (type == null) {
// Host root, text node or just invalid type.
return null;
}
{
if (typeof type.tag === 'number') {
error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
}
}
if (typeof type === 'function') {
return type.displayName || type.name || null;
}
if (typeof type === 'string') {
return type;
}
switch (type) {
case exports.Fragment:
return 'Fragment';
case REACT_PORTAL_TYPE:
return 'Portal';
case exports.Profiler:
return 'Profiler';
case exports.StrictMode:
return 'StrictMode';
case exports.Suspense:
return 'Suspense';
case exports.SuspenseList:
return 'SuspenseList';
case REACT_CACHE_TYPE:
return 'Cache';
}
if (typeof type === 'object') {
switch (type.$$typeof) {
case REACT_CONTEXT_TYPE:
var context = type;
return getContextName(context) + '.Consumer';
case REACT_PROVIDER_TYPE:
var provider = type;
return getContextName(provider._context) + '.Provider';
case REACT_FORWARD_REF_TYPE:
return getWrappedName(type, type.render, 'ForwardRef');
case REACT_MEMO_TYPE:
var outerName = type.displayName || null;
if (outerName !== null) {
return outerName;
}
return getComponentNameFromType(type.type) || 'Memo';
case REACT_LAZY_TYPE:
{
var lazyComponent = type;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
return getComponentNameFromType(init(payload));
} catch (x) {
return null;
}
}
}
}
return null;
}
var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
var RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true
};
var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;
{
didWarnAboutStringRefs = {};
}
function hasValidRef(config) {
{
if (hasOwnProperty$1.call(config, 'ref')) {
var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.ref !== undefined;
}
function hasValidKey(config) {
{
if (hasOwnProperty$1.call(config, 'key')) {
var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.key !== undefined;
}
function defineKeyPropWarningGetter(props, displayName) {
var warnAboutAccessingKey = function () {
{
if (!specialPropKeyWarningShown) {
specialPropKeyWarningShown = true;
error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
}
}
};
warnAboutAccessingKey.isReactWarning = true;
Object.defineProperty(props, 'key', {
get: warnAboutAccessingKey,
configurable: true
});
}
function defineRefPropWarningGetter(props, displayName) {
var warnAboutAccessingRef = function () {
{
if (!specialPropRefWarningShown) {
specialPropRefWarningShown = true;
error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
}
}
};
warnAboutAccessingRef.isReactWarning = true;
Object.defineProperty(props, 'ref', {
get: warnAboutAccessingRef,
configurable: true
});
}
function warnIfStringRefCannotBeAutoConverted(config) {
{
if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {
var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
if (!didWarnAboutStringRefs[componentName]) {
error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref);
didWarnAboutStringRefs[componentName] = true;
}
}
}
}
/**
* Factory method to create a new React element. This no longer adheres to
* the class pattern, so do not use new to call it. Also, instanceof check
* will not work. Instead test $$typeof field against Symbol.for('react.element') to check
* if something is a React Element.
*
* @param {*} type
* @param {*} props
* @param {*} key
* @param {string|object} ref
* @param {*} owner
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @internal
*/
var ReactElement = function (type, key, ref, self, source, owner, props) {
var element = {
// This tag allows us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner
};
{
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: false
}); // self and source are DEV only properties.
Object.defineProperty(element, '_self', {
configurable: false,
enumerable: false,
writable: false,
value: self
}); // Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: false,
enumerable: false,
writable: false,
value: source
});
if (Object.freeze) {
Object.freeze(element.props);
Object.freeze(element);
}
}
return element;
};
/**
* Create and return a new ReactElement of the given type.
* See https://reactjs.org/docs/react-api.html#createelement
*/
function createElement(type, config, children) {
var propName; // Reserved names are extracted
var props = {};
var key = null;
var ref = null;
var self = null;
var source = null;
if (config != null) {
if (hasValidRef(config)) {
ref = config.ref;
{
warnIfStringRefCannotBeAutoConverted(config);
}
}
if (hasValidKey(config)) {
{
checkKeyStringCoercion(config.key);
}
key = '' + config.key;
}
self = config.__self === undefined ? null : config.__self;
source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object
for (propName in config) {
if (hasOwnProperty$1.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
} // Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
{
if (Object.freeze) {
Object.freeze(childArray);
}
}
props.children = childArray;
} // Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}
{
if (key || ref) {
var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
if (key) {
defineKeyPropWarningGetter(props, displayName);
}
if (ref) {
defineRefPropWarningGetter(props, displayName);
}
}
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
}
function cloneAndReplaceKey(oldElement, newKey) {
var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
return newElement;
}
/**
* Clone and return a new ReactElement using element as the starting point.
* See https://reactjs.org/docs/react-api.html#cloneelement
*/
function cloneElement(element, config, children) {
if (element === null || element === undefined) {
throw Error( "React.cloneElement(...): The argument must be a React element, but you passed " + element + "." );
}
var propName; // Original props are copied
var props = assign({}, element.props); // Reserved names are extracted
var key = element.key;
var ref = element.ref; // Self is preserved since the owner is preserved.
var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a
// transpiler, and the original source is probably a better indicator of the
// true owner.
var source = element._source; // Owner will be preserved, unless ref is overridden
var owner = element._owner;
if (config != null) {
if (hasValidRef(config)) {
// Silently steal the ref from the parent.
ref = config.ref;
owner = ReactCurrentOwner.current;
}
if (hasValidKey(config)) {
{
checkKeyStringCoercion(config.key);
}
key = '' + config.key;
} // Remaining properties override existing props
var defaultProps;
if (element.type && element.type.defaultProps) {
defaultProps = element.type.defaultProps;
}
for (propName in config) {
if (hasOwnProperty$1.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
if (config[propName] === undefined && defaultProps !== undefined) {
// Resolve default props
props[propName] = defaultProps[propName];
} else {
props[propName] = config[propName];
}
}
}
} // Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
return ReactElement(element.type, key, ref, self, source, owner, props);
}
/**
* Verifies the object is a ReactElement.
* See https://reactjs.org/docs/react-api.html#isvalidelement
* @param {?object} object
* @return {boolean} True if `object` is a ReactElement.
* @final
*/
function isValidElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
var SEPARATOR = '.';
var SUBSEPARATOR = ':';
/**
* Escape and wrap key so it is safe to use as a reactid
*
* @param {string} key to be escaped.
* @return {string} the escaped key.
*/
function escape(key) {
var escapeRegex = /[=:]/g;
var escaperLookup = {
'=': '=0',
':': '=2'
};
var escapedString = key.replace(escapeRegex, function (match) {
return escaperLookup[match];
});
return '$' + escapedString;
}
/**
* TODO: Test that a single child and an array with one item have the same key
* pattern.
*/
var didWarnAboutMaps = false;
var userProvidedKeyEscapeRegex = /\/+/g;
function escapeUserProvidedKey(text) {
return text.replace(userProvidedKeyEscapeRegex, '$&/');
}
/**
* Generate a key string that identifies a element within a set.
*
* @param {*} element A element that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
*/
function getElementKey(element, index) {
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
if (typeof element === 'object' && element !== null && element.key != null) {
// Explicit key
{
checkKeyStringCoercion(element.key);
}
return escape('' + element.key);
} // Implicit key determined by the index in the set
return index.toString(36);
}
function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
var type = typeof children;
if (type === 'undefined' || type === 'boolean') {
// All of the above are perceived as null.
children = null;
}
var invokeCallback = false;
if (children === null) {
invokeCallback = true;
} else {
switch (type) {
case 'string':
case 'number':
invokeCallback = true;
break;
case 'object':
switch (children.$$typeof) {
case REACT_ELEMENT_TYPE:
case REACT_PORTAL_TYPE:
invokeCallback = true;
}
}
}
if (invokeCallback) {
var _child = children;
var mappedChild = callback(_child); // If it's the only child, treat the name as if it was wrapped in an array
// so that it's consistent if the number of children grows:
var childKey = nameSoFar === '' ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;
if (isArray(mappedChild)) {
var escapedChildKey = '';
if (childKey != null) {
escapedChildKey = escapeUserProvidedKey(childKey) + '/';
}
mapIntoArray(mappedChild, array, escapedChildKey, '', function (c) {
return c;
});
} else if (mappedChild != null) {
if (isValidElement(mappedChild)) {
{
// The `if` statement here prevents auto-disabling of the safe
// coercion ESLint rule, so we must manually disable it below.
// $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) {
checkKeyStringCoercion(mappedChild.key);
}
}
mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as
// traverseAllChildren used to do for objects as children
escapedPrefix + ( // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
mappedChild.key && (!_child || _child.key !== mappedChild.key) ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number
// eslint-disable-next-line react-internal/safe-string-coercion
escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey);
}
array.push(mappedChild);
}
return 1;
}
var child;
var nextName;
var subtreeCount = 0; // Count of children found in the current subtree.
var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (isArray(children)) {
for (var i = 0; i < children.length; i++) {
child = children[i];
nextName = nextNamePrefix + getElementKey(child, i);
subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
}
} else {
var iteratorFn = getIteratorFn(children);
if (typeof iteratorFn === 'function') {
var iterableChildren = children;
{
// Warn about using Maps as children
if (iteratorFn === iterableChildren.entries) {
if (!didWarnAboutMaps) {
warn('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.');
}
didWarnAboutMaps = true;
}
}
var iterator = iteratorFn.call(iterableChildren);
var step;
var ii = 0;
while (!(step = iterator.next()).done) {
child = step.value;
nextName = nextNamePrefix + getElementKey(child, ii++);
subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
}
} else if (type === 'object') {
// eslint-disable-next-line react-internal/safe-string-coercion
var childrenString = String(children);
throw Error( "Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.' );
}
}
return subtreeCount;
}
/**
* Maps children that are typically specified as `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenmap
*
* The provided mapFunction(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func The map function.
* @param {*} context Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var result = [];
var count = 0;
mapIntoArray(children, result, '', '', function (child) {
return func.call(context, child, count++);
});
return result;
}
/**
* Count the number of children that are typically specified as
* `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrencount
*
* @param {?*} children Children tree container.
* @return {number} The number of children.
*/
function countChildren(children) {
var n = 0;
mapChildren(children, function () {
n++; // Don't return anything
});
return n;
}
/**
* Iterates through children that are typically specified as `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenforeach
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc
* @param {*} forEachContext Context for forEachContext.
*/
function forEachChildren(children, forEachFunc, forEachContext) {
mapChildren(children, function () {
forEachFunc.apply(this, arguments); // Don't return anything.
}, forEachContext);
}
/**
* Flatten a children object (typically specified as `props.children`) and
* return an array with appropriately re-keyed children.
*
* See https://reactjs.org/docs/react-api.html#reactchildrentoarray
*/
function toArray(children) {
return mapChildren(children, function (child) {
return child;
}) || [];
}
/**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenonly
*
* The current implementation of this function assumes that a single child gets
* passed without a wrapper, but the purpose of this helper function is to
* abstract away the particular structure of children.
*
* @param {?object} children Child collection structure.
* @return {ReactElement} The first and only `ReactElement` contained in the
* structure.
*/
function onlyChild(children) {
if (!isValidElement(children)) {
throw Error( 'React.Children.only expected to receive a single React element child.' );
}
return children;
}
function createContext(defaultValue) {
// TODO: Second argument used to be an optional `calculateChangedBits`
// function. Warn to reserve for future use?
var context = {
$$typeof: REACT_CONTEXT_TYPE,
// As a workaround to support multiple concurrent renderers, we categorize
// some renderers as primary and others as secondary. We only expect
// there to be two concurrent renderers at most: React Native (primary) and
// Fabric (secondary); React DOM (primary) and React ART (secondary).
// Secondary renderers store their context values on separate fields.
_currentValue: defaultValue,
_currentValue2: defaultValue,
// Used to track how many concurrent renderers this context currently
// supports within in a single renderer. Such as parallel server rendering.
_threadCount: 0,
// These are circular
Provider: null,
Consumer: null
};
context.Provider = {
$$typeof: REACT_PROVIDER_TYPE,
_context: context
};
var hasWarnedAboutUsingNestedContextConsumers = false;
var hasWarnedAboutUsingConsumerProvider = false;
var hasWarnedAboutDisplayNameOnConsumer = false;
{
// A separate object, but proxies back to the original context object for
// backwards compatibility. It has a different $$typeof, so we can properly
// warn for the incorrect usage of Context as a Consumer.
var Consumer = {
$$typeof: REACT_CONTEXT_TYPE,
_context: context
}; // $FlowFixMe: Flow complains about not setting a value, which is intentional here
Object.defineProperties(Consumer, {
Provider: {
get: function () {
if (!hasWarnedAboutUsingConsumerProvider) {
hasWarnedAboutUsingConsumerProvider = true;
error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');
}
return context.Provider;
},
set: function (_Provider) {
context.Provider = _Provider;
}
},
_currentValue: {
get: function () {
return context._currentValue;
},
set: function (_currentValue) {
context._currentValue = _currentValue;
}
},
_currentValue2: {
get: function () {
return context._currentValue2;
},
set: function (_currentValue2) {
context._currentValue2 = _currentValue2;
}
},
_threadCount: {
get: function () {
return context._threadCount;
},
set: function (_threadCount) {
context._threadCount = _threadCount;
}
},
Consumer: {
get: function () {
if (!hasWarnedAboutUsingNestedContextConsumers) {
hasWarnedAboutUsingNestedContextConsumers = true;
error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
}
return context.Consumer;
}
},
displayName: {
get: function () {
return context.displayName;
},
set: function (displayName) {
if (!hasWarnedAboutDisplayNameOnConsumer) {
warn('Setting `displayName` on Context.Consumer has no effect. ' + "You should set it directly on the context with Context.displayName = '%s'.", displayName);
hasWarnedAboutDisplayNameOnConsumer = true;
}
}
}
}); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty
context.Consumer = Consumer;
}
{
context._currentRenderer = null;
context._currentRenderer2 = null;
}
return context;
}
var Uninitialized = -1;
var Pending = 0;
var Resolved = 1;
var Rejected = 2;
function lazyInitializer(payload) {
if (payload._status === Uninitialized) {
var ctor = payload._result;
var thenable = ctor(); // Transition to the next state.
// This might throw either because it's missing or throws. If so, we treat it
// as still uninitialized and try again next time. Which is the same as what
// happens if the ctor or any wrappers processing the ctor throws. This might
// end up fixing it if the resolution was a concurrency bug.
thenable.then(function (moduleObject) {
if (payload._status === Pending || payload._status === Uninitialized) {
// Transition to the next state.
var resolved = payload;
resolved._status = Resolved;
resolved._result = moduleObject;
}
}, function (error) {
if (payload._status === Pending || payload._status === Uninitialized) {
// Transition to the next state.
var rejected = payload;
rejected._status = Rejected;
rejected._result = error;
}
});
if (payload._status === Uninitialized) {
// In case, we're still uninitialized, then we're waiting for the thenable
// to resolve. Set it as pending in the meantime.
var pending = payload;
pending._status = Pending;
pending._result = thenable;
}
}
if (payload._status === Resolved) {
var moduleObject = payload._result;
{
if (moduleObject === undefined) {
error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies.
'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))\n\n" + 'Did you accidentally put curly braces around the import?', moduleObject);
}
}
{
if (!('default' in moduleObject)) {
error('lazy: Expected the result of a dynamic imp' + 'ort() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + // Break up imports to avoid accidentally parsing them as dependencies.
'const MyComponent = lazy(() => imp' + "ort('./MyComponent'))", moduleObject);
}
}
return moduleObject.default;
} else {
throw payload._result;
}
}
function lazy(ctor) {
var payload = {
// We use these fields to store the result.
_status: Uninitialized,
_result: ctor
};
var lazyType = {
$$typeof: REACT_LAZY_TYPE,
_payload: payload,
_init: lazyInitializer
};
{
// In production, this would just set it on the object.
var defaultProps;
var propTypes; // $FlowFixMe
Object.defineProperties(lazyType, {
defaultProps: {
configurable: true,
get: function () {
return defaultProps;
},
set: function (newDefaultProps) {
error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
defaultProps = newDefaultProps; // Match production behavior more closely:
// $FlowFixMe
Object.defineProperty(lazyType, 'defaultProps', {
enumerable: true
});
}
},
propTypes: {
configurable: true,
get: function () {
return propTypes;
},
set: function (newPropTypes) {
error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
propTypes = newPropTypes; // Match production behavior more closely:
// $FlowFixMe
Object.defineProperty(lazyType, 'propTypes', {
enumerable: true
});
}
}
});
}
return lazyType;
}
function forwardRef(render) {
{
if (render != null && render.$$typeof === REACT_MEMO_TYPE) {
error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).');
} else if (typeof render !== 'function') {
error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render);
} else {
if (render.length !== 0 && render.length !== 2) {
error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.');
}
}
if (render != null) {
if (render.defaultProps != null || render.propTypes != null) {
error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?');
}
}
}
var elementType = {
$$typeof: REACT_FORWARD_REF_TYPE,
render: render
};
{
var ownName;
Object.defineProperty(elementType, 'displayName', {
enumerable: false,
configurable: true,
get: function () {
return ownName;
},
set: function (name) {
ownName = name; // The inner component shouldn't inherit this display name in most cases,
// because the component may be used elsewhere.
// But it's nice for anonymous functions to inherit the name,
// so that our component-stack generation logic will display their frames.
// An anonymous function generally suggests a pattern like:
// React.forwardRef((props, ref) => {...});
// This kind of inner function is not used elsewhere so the side effect is okay.
if (!render.name && !render.displayName) {
render.displayName = name;
}
}
});
}
return elementType;
}
// Filter certain DOM attributes (e.g. src, href) if their values are empty strings.
var enableCache = false; // Only used in www builds.
var enableScopeAPI = false; // Experimental Create Event Handle API.
var warnOnSubscriptionInsideStartTransition = false;
var REACT_MODULE_REFERENCE = 0;
if (typeof Symbol === 'function') {
REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
}
function isValidElementType(type) {
if (typeof type === 'string' || typeof type === 'function') {
return true;
} // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
if (type === exports.Fragment || type === exports.Profiler || type === REACT_DEBUG_TRACING_MODE_TYPE || type === exports.StrictMode || type === exports.Suspense || type === exports.SuspenseList || type === REACT_LEGACY_HIDDEN_TYPE || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCache ) {
return true;
}
if (typeof type === 'object' && type !== null) {
if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
// types supported by any Flight configuration anywhere since
// we don't know which Flight build this will end up being used
// with.
type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
return true;
}
}
return false;
}
function memo(type, compare) {
{
if (!isValidElementType(type)) {
error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type);
}
}
var elementType = {
$$typeof: REACT_MEMO_TYPE,
type: type,
compare: compare === undefined ? null : compare
};
{
var ownName;
Object.defineProperty(elementType, 'displayName', {
enumerable: false,
configurable: true,
get: function () {
return ownName;
},
set: function (name) {
ownName = name; // The inner component shouldn't inherit this display name in most cases,
// because the component may be used elsewhere.
// But it's nice for anonymous functions to inherit the name,
// so that our component-stack generation logic will display their frames.
// An anonymous function generally suggests a pattern like:
// React.memo((props) => {...});
// This kind of inner function is not used elsewhere so the side effect is okay.
if (!type.name && !type.displayName) {
type.displayName = name;
}
}
});
}
return elementType;
}
function resolveDispatcher() {
var dispatcher = ReactCurrentDispatcher.current;
{
if (dispatcher === null) {
error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.');
}
} // Will result in a null access error if accessed outside render phase. We
// intentionally don't throw our own error because this is in a hot path.
// Also helps ensure this is inlined.
return dispatcher;
}
function useContext(Context) {
var dispatcher = resolveDispatcher();
{
// TODO: add a more generic warning for invalid values.
if (Context._context !== undefined) {
var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs
// and nobody should be using this in existing code.
if (realContext.Consumer === Context) {
error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?');
} else if (realContext.Provider === Context) {
error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?');
}
}
}
return dispatcher.useContext(Context);
}
function useState(initialState) {
var dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}
function useReducer(reducer, initialArg, init) {
var dispatcher = resolveDispatcher();
return dispatcher.useReducer(reducer, initialArg, init);
}
function useRef(initialValue) {
var dispatcher = resolveDispatcher();
return dispatcher.useRef(initialValue);
}
function useEffect(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useEffect(create, deps);
}
function useLayoutEffect(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useLayoutEffect(create, deps);
}
function useCallback(callback, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useCallback(callback, deps);
}
function useMemo(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useMemo(create, deps);
}
function useImperativeHandle(ref, create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useImperativeHandle(ref, create, deps);
}
function useDebugValue(value, formatterFn) {
{
var dispatcher = resolveDispatcher();
return dispatcher.useDebugValue(value, formatterFn);
}
}
function useTransition() {
var dispatcher = resolveDispatcher();
return dispatcher.useTransition();
}
function useDeferredValue(value) {
var dispatcher = resolveDispatcher();
return dispatcher.useDeferredValue(value);
}
function useOpaqueIdentifier() {
var dispatcher = resolveDispatcher();
return dispatcher.useOpaqueIdentifier();
}
function useMutableSource(source, getSnapshot, subscribe) {
var dispatcher = resolveDispatcher();
return dispatcher.useMutableSource(source, getSnapshot, subscribe);
}
// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth = 0;
var prevLog;
var prevInfo;
var prevWarn;
var prevError;
var prevGroup;
var prevGroupCollapsed;
var prevGroupEnd;
function disabledLog() {}
disabledLog.__reactDisabledLog = true;
function disableLogs() {
{
if (disabledDepth === 0) {
/* eslint-disable react-internal/no-production-logging */
prevLog = console.log;
prevInfo = console.info;
prevWarn = console.warn;
prevError = console.error;
prevGroup = console.group;
prevGroupCollapsed = console.groupCollapsed;
prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
var props = {
configurable: true,
enumerable: true,
value: disabledLog,
writable: true
}; // $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console, {
info: props,
log: props,
warn: props,
error: props,
group: props,
groupCollapsed: props,
groupEnd: props
});
/* eslint-enable react-internal/no-production-logging */
}
disabledDepth++;
}
}
function reenableLogs() {
{
disabledDepth--;
if (disabledDepth === 0) {
/* eslint-disable react-internal/no-production-logging */
var props = {
configurable: true,
enumerable: true,
writable: true
}; // $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console, {
log: assign({}, props, {
value: prevLog
}),
info: assign({}, props, {
value: prevInfo
}),
warn: assign({}, props, {
value: prevWarn
}),
error: assign({}, props, {
value: prevError
}),
group: assign({}, props, {
value: prevGroup
}),
groupCollapsed: assign({}, props, {
value: prevGroupCollapsed
}),
groupEnd: assign({}, props, {
value: prevGroupEnd
})
});
/* eslint-enable react-internal/no-production-logging */
}
if (disabledDepth < 0) {
error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
}
}
}
var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
var prefix;
function describeBuiltInComponentFrame(name, source, ownerFn) {
{
if (prefix === undefined) {
// Extract the VM specific prefix used by each line.
try {
throw Error();
} catch (x) {
var match = x.stack.trim().match(/\n( *(at )?)/);
prefix = match && match[1] || '';
}
} // We use the prefix to ensure our stacks line up with native stack frames.
return '\n' + prefix + name;
}
}
var reentry = false;
var componentFrameCache;
{
var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
componentFrameCache = new PossiblyWeakMap();
}
function describeNativeComponentFrame(fn, construct) {
// If something asked for a stack inside a fake render, it should get ignored.
if ( !fn || reentry) {
return '';
}
{
var frame = componentFrameCache.get(fn);
if (frame !== undefined) {
return frame;
}
}
var control;
reentry = true;
var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
Error.prepareStackTrace = undefined;
var previousDispatcher;
{
previousDispatcher = ReactCurrentDispatcher$1.current; // Set the dispatcher in DEV because this might be call in the render function
// for warnings.
ReactCurrentDispatcher$1.current = null;
disableLogs();
}
try {
// This should throw.
if (construct) {
// Something should be setting the props in the constructor.
var Fake = function () {
throw Error();
}; // $FlowFixMe
Object.defineProperty(Fake.prototype, 'props', {
set: function () {
// We use a throwing setter instead of frozen or non-writable props
// because that won't throw in a non-strict mode function.
throw Error();
}
});
if (typeof Reflect === 'object' && Reflect.construct) {
// We construct a different control for this case to include any extra
// frames added by the construct call.
try {
Reflect.construct(Fake, []);
} catch (x) {
control = x;
}
Reflect.construct(fn, [], Fake);
} else {
try {
Fake.call();
} catch (x) {
control = x;
}
fn.call(Fake.prototype);
}
} else {
try {
throw Error();
} catch (x) {
control = x;
}
fn();
}
} catch (sample) {
// This is inlined manually because closure doesn't do it for us.
if (sample && control && typeof sample.stack === 'string') {
// This extracts the first frame from the sample that isn't also in the control.
// Skipping one frame that we assume is the frame that calls the two.
var sampleLines = sample.stack.split('\n');
var controlLines = control.stack.split('\n');
var s = sampleLines.length - 1;
var c = controlLines.length - 1;
while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
// We expect at least one stack frame to be shared.
// Typically this will be the root most one. However, stack frames may be
// cut off due to maximum stack limits. In this case, one maybe cut off
// earlier than the other. We assume that the sample is longer or the same
// and there for cut off earlier. So we should find the root most frame in
// the sample somewhere in the control.
c--;
}
for (; s >= 1 && c >= 0; s--, c--) {
// Next we find the first one that isn't the same which should be the
// frame that called our sample function and the control.
if (sampleLines[s] !== controlLines[c]) {
// In V8, the first line is describing the message but other VMs don't.
// If we're about to return the first line, and the control is also on the same
// line, that's a pretty good indicator that our sample threw at same line as
// the control. I.e. before we entered the sample frame. So we ignore this result.
// This can happen if you passed a class to function component, or non-function.
if (s !== 1 || c !== 1) {
do {
s--;
c--; // We may still have similar intermediate frames from the construct call.
// The next one that isn't the same should be our match though.
if (c < 0 || sampleLines[s] !== controlLines[c]) {
// V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
var _frame = '\n' + sampleLines[s].replace(' at new ', ' at ');
{
if (typeof fn === 'function') {
componentFrameCache.set(fn, _frame);
}
} // Return the line we found.
return _frame;
}
} while (s >= 1 && c >= 0);
}
break;
}
}
}
} finally {
reentry = false;
{
ReactCurrentDispatcher$1.current = previousDispatcher;
reenableLogs();
}
Error.prepareStackTrace = previousPrepareStackTrace;
} // Fallback to just using the name if we couldn't make it throw.
var name = fn ? fn.displayName || fn.name : '';
var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
{
if (typeof fn === 'function') {
componentFrameCache.set(fn, syntheticFrame);
}
}
return syntheticFrame;
}
function describeFunctionComponentFrame(fn, source, ownerFn) {
{
return describeNativeComponentFrame(fn, false);
}
}
function shouldConstruct(Component) {
var prototype = Component.prototype;
return !!(prototype && prototype.isReactComponent);
}
function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
if (type == null) {
return '';
}
if (typeof type === 'function') {
{
return describeNativeComponentFrame(type, shouldConstruct(type));
}
}
if (typeof type === 'string') {
return describeBuiltInComponentFrame(type);
}
switch (type) {
case exports.Suspense:
return describeBuiltInComponentFrame('Suspense');
case exports.SuspenseList:
return describeBuiltInComponentFrame('SuspenseList');
}
if (typeof type === 'object') {
switch (type.$$typeof) {
case REACT_FORWARD_REF_TYPE:
return describeFunctionComponentFrame(type.render);
case REACT_MEMO_TYPE:
// Memo may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
case REACT_LAZY_TYPE:
{
var lazyComponent = type;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
// Lazy may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
} catch (x) {}
}
}
}
return '';
}
var loggedTypeFailures = {};
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
function setCurrentlyValidatingElement(element) {
{
if (element) {
var owner = element._owner;
var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
} else {
ReactDebugCurrentFrame$1.setExtraStackFrame(null);
}
}
}
function checkPropTypes(typeSpecs, values, location, componentName, element) {
{
// $FlowFixMe This is okay but Flow doesn't know it.
var has = Function.call.bind(hasOwnProperty$1);
for (var typeSpecName in typeSpecs) {
if (has(typeSpecs, typeSpecName)) {
var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if (typeof typeSpecs[typeSpecName] !== 'function') {
// eslint-disable-next-line react-internal/prod-error-codes
var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
err.name = 'Invariant Violation';
throw err;
}
error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
} catch (ex) {
error$1 = ex;
}
if (error$1 && !(error$1 instanceof Error)) {
setCurrentlyValidatingElement(element);
error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
setCurrentlyValidatingElement(null);
}
if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error$1.message] = true;
setCurrentlyValidatingElement(element);
error('Failed %s type: %s', location, error$1.message);
setCurrentlyValidatingElement(null);
}
}
}
}
}
function setCurrentlyValidatingElement$1(element) {
{
if (element) {
var owner = element._owner;
var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
setExtraStackFrame(stack);
} else {
setExtraStackFrame(null);
}
}
}
var propTypesMisspellWarningShown;
{
propTypesMisspellWarningShown = false;
}
function getDeclarationErrorAddendum() {
if (ReactCurrentOwner.current) {
var name = getComponentNameFromType(ReactCurrentOwner.current.type);
if (name) {
return '\n\nCheck the render method of `' + name + '`.';
}
}
return '';
}
function getSourceInfoErrorAddendum(source) {
if (source !== undefined) {
var fileName = source.fileName.replace(/^.*[\\\/]/, '');
var lineNumber = source.lineNumber;
return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
}
return '';
}
function getSourceInfoErrorAddendumForProps(elementProps) {
if (elementProps !== null && elementProps !== undefined) {
return getSourceInfoErrorAddendum(elementProps.__source);
}
return '';
}
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/
var ownerHasKeyUseWarning = {};
function getCurrentComponentErrorInfo(parentType) {
var info = getDeclarationErrorAddendum();
if (!info) {
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
if (parentName) {
info = "\n\nCheck the top-level render call using <" + parentName + ">.";
}
}
return info;
}
/**
* Warn if the element doesn't have an explicit key assigned to it.
* This element is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it. Error statuses are cached so a warning
* will only be shown once.
*
* @internal
* @param {ReactElement} element Element that requires a key.
* @param {*} parentType element's parent's type.
*/
function validateExplicitKey(element, parentType) {
if (!element._store || element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
return;
}
ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
var childOwner = '';
if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
// Give the component that originally created this child.
childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
}
{
setCurrentlyValidatingElement$1(element);
error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
setCurrentlyValidatingElement$1(null);
}
}
/**
* Ensure that every element either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {ReactNode} node Statically passed child of any type.
* @param {*} parentType node's parent's type.
*/
function validateChildKeys(node, parentType) {
if (typeof node !== 'object') {
return;
}
if (isArray(node)) {
for (var i = 0; i < node.length; i++) {
var child = node[i];
if (isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (isValidElement(node)) {
// This element was passed in a valid location.
if (node._store) {
node._store.validated = true;
}
} else if (node) {
var iteratorFn = getIteratorFn(node);
if (typeof iteratorFn === 'function') {
// Entry iterators used to provide implicit keys,
// but now we print a separate warning for them later.
if (iteratorFn !== node.entries) {
var iterator = iteratorFn.call(node);
var step;
while (!(step = iterator.next()).done) {
if (isValidElement(step.value)) {
validateExplicitKey(step.value, parentType);
}
}
}
}
}
}
/**
* Given an element, validate that its props follow the propTypes definition,
* provided by the type.
*
* @param {ReactElement} element
*/
function validatePropTypes(element) {
{
var type = element.type;
if (type === null || type === undefined || typeof type === 'string') {
return;
}
var propTypes;
if (typeof type === 'function') {
propTypes = type.propTypes;
} else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
// Inner props are checked in the reconciler.
type.$$typeof === REACT_MEMO_TYPE)) {
propTypes = type.propTypes;
} else {
return;
}
if (propTypes) {
// Intentionally inside to avoid triggering lazy initializers:
var name = getComponentNameFromType(type);
checkPropTypes(propTypes, element.props, 'prop', name, element);
} else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
var _name = getComponentNameFromType(type);
error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
}
if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
}
}
}
/**
* Given a fragment, validate that it can only be provided with fragment props
* @param {ReactElement} fragment
*/
function validateFragmentProps(fragment) {
{
var keys = Object.keys(fragment.props);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key !== 'children' && key !== 'key') {
setCurrentlyValidatingElement$1(fragment);
error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
setCurrentlyValidatingElement$1(null);
break;
}
}
if (fragment.ref !== null) {
setCurrentlyValidatingElement$1(fragment);
error('Invalid attribute `ref` supplied to `React.Fragment`.');
setCurrentlyValidatingElement$1(null);
}
}
}
function createElementWithValidation(type, props, children) {
var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
if (!validType) {
var info = '';
if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
}
var sourceInfo = getSourceInfoErrorAddendumForProps(props);
if (sourceInfo) {
info += sourceInfo;
} else {
info += getDeclarationErrorAddendum();
}
var typeString;
if (type === null) {
typeString = 'null';
} else if (isArray(type)) {
typeString = 'array';
} else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
info = ' Did you accidentally export a JSX literal instead of a component?';
} else {
typeString = typeof type;
}
{
error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
}
}
var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) {
return element;
} // Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if (validType) {
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], type);
}
}
if (type === exports.Fragment) {
validateFragmentProps(element);
} else {
validatePropTypes(element);
}
return element;
}
var didWarnAboutDeprecatedCreateFactory = false;
function createFactoryWithValidation(type) {
var validatedFactory = createElementWithValidation.bind(null, type);
validatedFactory.type = type;
{
if (!didWarnAboutDeprecatedCreateFactory) {
didWarnAboutDeprecatedCreateFactory = true;
warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.');
} // Legacy hook: remove it
Object.defineProperty(validatedFactory, 'type', {
enumerable: false,
get: function () {
warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');
Object.defineProperty(this, 'type', {
value: type
});
return type;
}
});
}
return validatedFactory;
}
function cloneElementWithValidation(element, props, children) {
var newElement = cloneElement.apply(this, arguments);
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], newElement.type);
}
validatePropTypes(newElement);
return newElement;
}
function createMutableSource(source, getVersion) {
var mutableSource = {
_getVersion: getVersion,
_source: source,
_workInProgressVersionPrimary: null,
_workInProgressVersionSecondary: null
};
{
mutableSource._currentPrimaryRenderer = null;
mutableSource._currentSecondaryRenderer = null; // Used to detect side effects that update a mutable source during render.
// See https://github.com/facebook/react/issues/19948
mutableSource._currentlyRenderingFiber = null;
mutableSource._initialVersionAsOfFirstRender = null;
}
return mutableSource;
}
var enableSchedulerDebugging = false;
var enableProfiling = false;
var frameYieldMs = 5;
function push(heap, node) {
var index = heap.length;
heap.push(node);
siftUp(heap, node, index);
}
function peek(heap) {
return heap.length === 0 ? null : heap[0];
}
function pop(heap) {
if (heap.length === 0) {
return null;
}
var first = heap[0];
var last = heap.pop();
if (last !== first) {
heap[0] = last;
siftDown(heap, last, 0);
}
return first;
}
function siftUp(heap, node, i) {
var index = i;
while (index > 0) {
var parentIndex = index - 1 >>> 1;
var parent = heap[parentIndex];
if (compare(parent, node) > 0) {
// The parent is larger. Swap positions.
heap[parentIndex] = node;
heap[index] = parent;
index = parentIndex;
} else {
// The parent is smaller. Exit.
return;
}
}
}
function siftDown(heap, node, i) {
var index = i;
var length = heap.length;
var halfLength = length >>> 1;
while (index < halfLength) {
var leftIndex = (index + 1) * 2 - 1;
var left = heap[leftIndex];
var rightIndex = leftIndex + 1;
var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those.
if (compare(left, node) < 0) {
if (rightIndex < length && compare(right, left) < 0) {
heap[index] = right;
heap[rightIndex] = node;
index = rightIndex;
} else {
heap[index] = left;
heap[leftIndex] = node;
index = leftIndex;
}
} else if (rightIndex < length && compare(right, node) < 0) {
heap[index] = right;
heap[rightIndex] = node;
index = rightIndex;
} else {
// Neither child is smaller. Exit.
return;
}
}
}
function compare(a, b) {
// Compare sort index first, then task id.
var diff = a.sortIndex - b.sortIndex;
return diff !== 0 ? diff : a.id - b.id;
}
// TODO: Use symbols?
var ImmediatePriority = 1;
var UserBlockingPriority = 2;
var NormalPriority = 3;
var LowPriority = 4;
var IdlePriority = 5;
function markTaskErrored(task, ms) {
}
/* eslint-disable no-var */
var getCurrentTime;
var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function';
if (hasPerformanceNow) {
var localPerformance = performance;
getCurrentTime = function () {
return localPerformance.now();
};
} else {
var localDate = Date;
var initialTime = localDate.now();
getCurrentTime = function () {
return localDate.now() - initialTime;
};
} // Max 31 bit integer. The max integer size in V8 for 32-bit systems.
// Math.pow(2, 30) - 1
// 0b111111111111111111111111111111
var maxSigned31BitInt = 1073741823; // Times out immediately
var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out
var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
var NORMAL_PRIORITY_TIMEOUT = 5000;
var LOW_PRIORITY_TIMEOUT = 10000; // Never times out
var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap
var taskQueue = [];
var timerQueue = []; // Incrementing id counter. Used to maintain insertion order.
var taskIdCounter = 1; // Pausing the scheduler is useful for debugging.
var currentTask = null;
var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance.
var isPerformingWork = false;
var isHostCallbackScheduled = false;
var isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them.
var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null;
var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null;
var localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom
var isInputPending = typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null;
function advanceTimers(currentTime) {
// Check for tasks that are no longer delayed and add them to the queue.
var timer = peek(timerQueue);
while (timer !== null) {
if (timer.callback === null) {
// Timer was cancelled.
pop(timerQueue);
} else if (timer.startTime <= currentTime) {
// Timer fired. Transfer to the task queue.
pop(timerQueue);
timer.sortIndex = timer.expirationTime;
push(taskQueue, timer);
} else {
// Remaining timers are pending.
return;
}
timer = peek(timerQueue);
}
}
function handleTimeout(currentTime) {
isHostTimeoutScheduled = false;
advanceTimers(currentTime);
if (!isHostCallbackScheduled) {
if (peek(taskQueue) !== null) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
} else {
var firstTimer = peek(timerQueue);
if (firstTimer !== null) {
requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
}
}
}
}
function flushWork(hasTimeRemaining, initialTime) {
isHostCallbackScheduled = false;
if (isHostTimeoutScheduled) {
// We scheduled a timeout but it's no longer needed. Cancel it.
isHostTimeoutScheduled = false;
cancelHostTimeout();
}
isPerformingWork = true;
var previousPriorityLevel = currentPriorityLevel;
try {
if (enableProfiling) {
try {
return workLoop(hasTimeRemaining, initialTime);
} catch (error) {
if (currentTask !== null) {
var currentTime = getCurrentTime();
markTaskErrored(currentTask, currentTime);
currentTask.isQueued = false;
}
throw error;
}
} else {
// No catch in prod code path.
return workLoop(hasTimeRemaining, initialTime);
}
} finally {
currentTask = null;
currentPriorityLevel = previousPriorityLevel;
isPerformingWork = false;
}
}
function workLoop(hasTimeRemaining, initialTime) {
var currentTime = initialTime;
advanceTimers(currentTime);
currentTask = peek(taskQueue);
while (currentTask !== null && !(enableSchedulerDebugging )) {
if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {
// This currentTask hasn't expired, and we've reached the deadline.
break;
}
var callback = currentTask.callback;
if (typeof callback === 'function') {
currentTask.callback = null;
currentPriorityLevel = currentTask.priorityLevel;
var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
var continuationCallback = callback(didUserCallbackTimeout);
currentTime = getCurrentTime();
if (typeof continuationCallback === 'function') {
currentTask.callback = continuationCallback;
} else {
if (currentTask === peek(taskQueue)) {
pop(taskQueue);
}
}
advanceTimers(currentTime);
} else {
pop(taskQueue);
}
currentTask = peek(taskQueue);
} // Return whether there's additional work
if (currentTask !== null) {
return true;
} else {
var firstTimer = peek(timerQueue);
if (firstTimer !== null) {
requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
}
return false;
}
}
function unstable_runWithPriority(priorityLevel, eventHandler) {
switch (priorityLevel) {
case ImmediatePriority:
case UserBlockingPriority:
case NormalPriority:
case LowPriority:
case IdlePriority:
break;
default:
priorityLevel = NormalPriority;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
}
function unstable_next(eventHandler) {
var priorityLevel;
switch (currentPriorityLevel) {
case ImmediatePriority:
case UserBlockingPriority:
case NormalPriority:
// Shift down to normal priority
priorityLevel = NormalPriority;
break;
default:
// Anything lower than normal priority should remain at the current level.
priorityLevel = currentPriorityLevel;
break;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
}
function unstable_wrapCallback(callback) {
var parentPriorityLevel = currentPriorityLevel;
return function () {
// This is a fork of runWithPriority, inlined for performance.
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = parentPriorityLevel;
try {
return callback.apply(this, arguments);
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
}
function unstable_scheduleCallback(priorityLevel, callback, options) {
var currentTime = getCurrentTime();
var startTime;
if (typeof options === 'object' && options !== null) {
var delay = options.delay;
if (typeof delay === 'number' && delay > 0) {
startTime = currentTime + delay;
} else {
startTime = currentTime;
}
} else {
startTime = currentTime;
}
var timeout;
switch (priorityLevel) {
case ImmediatePriority:
timeout = IMMEDIATE_PRIORITY_TIMEOUT;
break;
case UserBlockingPriority:
timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
break;
case IdlePriority:
timeout = IDLE_PRIORITY_TIMEOUT;
break;
case LowPriority:
timeout = LOW_PRIORITY_TIMEOUT;
break;
case NormalPriority:
default:
timeout = NORMAL_PRIORITY_TIMEOUT;
break;
}
var expirationTime = startTime + timeout;
var newTask = {
id: taskIdCounter++,
callback: callback,
priorityLevel: priorityLevel,
startTime: startTime,
expirationTime: expirationTime,
sortIndex: -1
};
if (startTime > currentTime) {
// This is a delayed task.
newTask.sortIndex = startTime;
push(timerQueue, newTask);
if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
// All tasks are delayed, and this is the task with the earliest delay.
if (isHostTimeoutScheduled) {
// Cancel an existing timeout.
cancelHostTimeout();
} else {
isHostTimeoutScheduled = true;
} // Schedule a timeout.
requestHostTimeout(handleTimeout, startTime - currentTime);
}
} else {
newTask.sortIndex = expirationTime;
push(taskQueue, newTask);
// wait until the next time we yield.
if (!isHostCallbackScheduled && !isPerformingWork) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
}
}
return newTask;
}
function unstable_pauseExecution() {
}
function unstable_continueExecution() {
if (!isHostCallbackScheduled && !isPerformingWork) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
}
}
function unstable_getFirstCallbackNode() {
return peek(taskQueue);
}
function unstable_cancelCallback(task) {
// remove from the queue because you can't remove arbitrary nodes from an
// array based heap, only the first one.)
task.callback = null;
}
function unstable_getCurrentPriorityLevel() {
return currentPriorityLevel;
}
var isMessageLoopRunning = false;
var scheduledHostCallback = null;
var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main
// thread, like user events. By default, it yields multiple times per frame.
// It does not attempt to align with frame boundaries, since most tasks don't
// need to be frame aligned; for those that do, use requestAnimationFrame.
var frameInterval = frameYieldMs;
var startTime = -1;
function shouldYieldToHost() {
var timeElapsed = getCurrentTime() - startTime;
if (timeElapsed < frameInterval) {
// The main thread has only been blocked for a really short amount of time;
// smaller than a single frame. Don't yield yet.
return false;
} // The main thread has been blocked for a non-negligible amount of time. We
return true;
}
function requestPaint() {
}
function forceFrameRate(fps) {
if (fps < 0 || fps > 125) {
// Using console['error'] to evade Babel and ESLint
console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported');
return;
}
if (fps > 0) {
frameInterval = Math.floor(1000 / fps);
} else {
// reset the framerate
frameInterval = frameYieldMs;
}
}
var performWorkUntilDeadline = function () {
if (scheduledHostCallback !== null) {
var currentTime = getCurrentTime(); // Keep track of the start time so we can measure how long the main thread
// has been blocked.
startTime = currentTime;
var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the
// error can be observed.
//
// Intentionally not using a try-catch, since that makes some debugging
// techniques harder. Instead, if `scheduledHostCallback` errors, then
// `hasMoreWork` will remain true, and we'll continue the work loop.
var hasMoreWork = true;
try {
hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
} finally {
if (hasMoreWork) {
// If there's more work, schedule the next message event at the end
// of the preceding one.
schedulePerformWorkUntilDeadline();
} else {
isMessageLoopRunning = false;
scheduledHostCallback = null;
}
}
} else {
isMessageLoopRunning = false;
} // Yielding to the browser will give it a chance to paint, so we can
};
var schedulePerformWorkUntilDeadline;
if (typeof localSetImmediate === 'function') {
// Node.js and old IE.
// There's a few reasons for why we prefer setImmediate.
//
// Unlike MessageChannel, it doesn't prevent a Node.js process from exiting.
// (Even though this is a DOM fork of the Scheduler, you could get here
// with a mix of Node.js 15+, which has a MessageChannel, and jsdom.)
// https://github.com/facebook/react/issues/20756
//
// But also, it runs earlier which is the semantic we want.
// If other browsers ever implement it, it's better to use it.
// Although both of these would be inferior to native scheduling.
schedulePerformWorkUntilDeadline = function () {
localSetImmediate(performWorkUntilDeadline);
};
} else if (typeof MessageChannel !== 'undefined') {
// DOM and Worker environments.
// We prefer MessageChannel because of the 4ms setTimeout clamping.
var channel = new MessageChannel();
var port = channel.port2;
channel.port1.onmessage = performWorkUntilDeadline;
schedulePerformWorkUntilDeadline = function () {
port.postMessage(null);
};
} else {
// We should only fallback here in non-browser environments.
schedulePerformWorkUntilDeadline = function () {
localSetTimeout(performWorkUntilDeadline, 0);
};
}
function requestHostCallback(callback) {
scheduledHostCallback = callback;
if (!isMessageLoopRunning) {
isMessageLoopRunning = true;
schedulePerformWorkUntilDeadline();
}
}
function requestHostTimeout(callback, ms) {
taskTimeoutID = localSetTimeout(function () {
callback(getCurrentTime());
}, ms);
}
function cancelHostTimeout() {
localClearTimeout(taskTimeoutID);
taskTimeoutID = -1;
}
var unstable_requestPaint = requestPaint;
var unstable_Profiling = null;
var Scheduler = /*#__PURE__*/Object.freeze({
__proto__: null,
unstable_ImmediatePriority: ImmediatePriority,
unstable_UserBlockingPriority: UserBlockingPriority,
unstable_NormalPriority: NormalPriority,
unstable_IdlePriority: IdlePriority,
unstable_LowPriority: LowPriority,
unstable_runWithPriority: unstable_runWithPriority,
unstable_next: unstable_next,
unstable_scheduleCallback: unstable_scheduleCallback,
unstable_cancelCallback: unstable_cancelCallback,
unstable_wrapCallback: unstable_wrapCallback,
unstable_getCurrentPriorityLevel: unstable_getCurrentPriorityLevel,
unstable_shouldYield: shouldYieldToHost,
unstable_requestPaint: unstable_requestPaint,
unstable_continueExecution: unstable_continueExecution,
unstable_pauseExecution: unstable_pauseExecution,
unstable_getFirstCallbackNode: unstable_getFirstCallbackNode,
get unstable_now () { return getCurrentTime; },
unstable_forceFrameRate: forceFrameRate,
unstable_Profiling: unstable_Profiling
});
var ReactSharedInternals$1 = {
ReactCurrentDispatcher: ReactCurrentDispatcher,
ReactCurrentOwner: ReactCurrentOwner,
ReactCurrentBatchConfig: ReactCurrentBatchConfig,
// Used by renderers to avoid bundling object-assign twice in UMD bundles:
assign: assign,
// Re-export the schedule API(s) for UMD bundles.
// This avoids introducing a dependency on a new UMD global in a minor update,
// Since that would be a breaking change (e.g. for all existing CodeSandboxes).
// This re-export is only required for UMD bundles;
// CJS bundles use the shared NPM package.
Scheduler: Scheduler
};
{
ReactSharedInternals$1.ReactCurrentActQueue = ReactCurrentActQueue;
ReactSharedInternals$1.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
}
function startTransition(scope) {
var prevTransition = ReactCurrentBatchConfig.transition;
ReactCurrentBatchConfig.transition = 1;
try {
scope();
} finally {
ReactCurrentBatchConfig.transition = prevTransition;
{
if (prevTransition !== 1 && warnOnSubscriptionInsideStartTransition && ReactCurrentBatchConfig._updatedFibers) {
var updatedFibersCount = ReactCurrentBatchConfig._updatedFibers.size;
if (updatedFibersCount > 10) {
warn('Detected a large number of updates inside startTransition. ' + 'If this is due to a subscription please re-write it to use React provided hooks. ' + 'Otherwise concurrent mode guarantees are off the table.');
}
ReactCurrentBatchConfig._updatedFibers.clear();
}
}
}
}
var didWarnAboutMessageChannel = false;
var enqueueTaskImpl = null;
function enqueueTask(task) {
if (enqueueTaskImpl === null) {
try {
// read require off the module object to get around the bundlers.
// we don't want them to detect a require and bundle a Node polyfill.
var requireString = ('require' + Math.random()).slice(0, 7);
var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's
// version of setImmediate, bypassing fake timers if any.
enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate;
} catch (_err) {
// we're in a browser
// we can't use regular timers because they may still be faked
// so we try MessageChannel+postMessage instead
enqueueTaskImpl = function (callback) {
{
if (didWarnAboutMessageChannel === false) {
didWarnAboutMessageChannel = true;
if (typeof MessageChannel === 'undefined') {
error('This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.');
}
}
}
var channel = new MessageChannel();
channel.port1.onmessage = callback;
channel.port2.postMessage(undefined);
};
}
}
return enqueueTaskImpl(task);
}
var actScopeDepth = 0;
var didWarnNoAwaitAct = false;
function act(callback) {
{
// `act` calls can be nested, so we track the depth. This represents the
// number of `act` scopes on the stack.
var prevActScopeDepth = actScopeDepth;
actScopeDepth++;
if (ReactCurrentActQueue.current === null) {
// This is the outermost `act` scope. Initialize the queue. The reconciler
// will detect the queue and use it instead of Scheduler.
ReactCurrentActQueue.current = [];
}
var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy;
var result;
try {
// Used to reproduce behavior of `batchedUpdates` in legacy mode. Only
// set to `true` while the given callback is executed, not for updates
// triggered during an async event, because this is how the legacy
// implementation of `act` behaved.
ReactCurrentActQueue.isBatchingLegacy = true;
result = callback(); // Replicate behavior of original `act` implementation in legacy mode,
// which flushed updates immediately after the scope function exits, even
// if it's an async function.
if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) {
var queue = ReactCurrentActQueue.current;
if (queue !== null) {
ReactCurrentActQueue.didScheduleLegacyUpdate = false;
flushActQueue(queue);
}
}
} catch (error) {
popActScope(prevActScopeDepth);
throw error;
} finally {
ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy;
}
if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
var thenableResult = result; // The callback is an async function (i.e. returned a promise). Wait
// for it to resolve before exiting the current scope.
var wasAwaited = false;
var thenable = {
then: function (resolve, reject) {
wasAwaited = true;
thenableResult.then(function (returnValue) {
popActScope(prevActScopeDepth);
if (actScopeDepth === 0) {
// We've exited the outermost act scope. Recursively flush the
// queue until there's no remaining work.
recursivelyFlushAsyncActWork(returnValue, resolve, reject);
} else {
resolve(returnValue);
}
}, function (error) {
// The callback threw an error.
popActScope(prevActScopeDepth);
reject(error);
});
}
};
{
if (!didWarnNoAwaitAct && typeof Promise !== 'undefined') {
// eslint-disable-next-line no-undef
Promise.resolve().then(function () {}).then(function () {
if (!wasAwaited) {
didWarnNoAwaitAct = true;
error('You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, ' + 'interleaving multiple act calls and mixing their ' + 'scopes. ' + 'You should - await act(async () => ...);');
}
});
}
}
return thenable;
} else {
var returnValue = result; // The callback is not an async function. Exit the current scope
// immediately, without awaiting.
popActScope(prevActScopeDepth);
if (actScopeDepth === 0) {
// Exiting the outermost act scope. Flush the queue.
var _queue = ReactCurrentActQueue.current;
if (_queue !== null) {
flushActQueue(_queue);
ReactCurrentActQueue.current = null;
} // Return a thenable. If the user awaits it, we'll flush again in
// case additional work was scheduled by a microtask.
var _thenable = {
then: function (resolve, reject) {
// Confirm we haven't re-entered another `act` scope, in case
// the user does something weird like await the thenable
// multiple times.
if (ReactCurrentActQueue.current === null) {
// Recursively flush the queue until there's no remaining work.
ReactCurrentActQueue.current = [];
recursivelyFlushAsyncActWork(returnValue, resolve, reject);
} else {
resolve(returnValue);
}
}
};
return _thenable;
} else {
// Since we're inside a nested `act` scope, the returned thenable
// immediately resolves. The outer scope will flush the queue.
var _thenable2 = {
then: function (resolve, reject) {
resolve(returnValue);
}
};
return _thenable2;
}
}
}
}
function popActScope(prevActScopeDepth) {
{
if (prevActScopeDepth !== actScopeDepth - 1) {
error('You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ');
}
actScopeDepth = prevActScopeDepth;
}
}
function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
{
var queue = ReactCurrentActQueue.current;
if (queue !== null) {
try {
flushActQueue(queue);
enqueueTask(function () {
if (queue.length === 0) {
// No additional work was scheduled. Finish.
ReactCurrentActQueue.current = null;
resolve(returnValue);
} else {
// Keep flushing work until there's none left.
recursivelyFlushAsyncActWork(returnValue, resolve, reject);
}
});
} catch (error) {
reject(error);
}
} else {
resolve(returnValue);
}
}
}
var isFlushing = false;
function flushActQueue(queue) {
{
if (!isFlushing) {
// Prevent re-entrance.
isFlushing = true;
var i = 0;
try {
for (; i < queue.length; i++) {
var callback = queue[i];
do {
callback = callback(true);
} while (callback !== null);
}
queue.length = 0;
} catch (error) {
// If something throws, leave the remaining callbacks on the queue.
queue = queue.slice(i + 1);
throw error;
} finally {
isFlushing = false;
}
}
}
}
var createElement$1 = createElementWithValidation ;
var cloneElement$1 = cloneElementWithValidation ;
var createFactory = createFactoryWithValidation ;
var Children = {
map: mapChildren,
forEach: forEachChildren,
count: countChildren,
toArray: toArray,
only: onlyChild
};
exports.Children = Children;
exports.Component = Component;
exports.PureComponent = PureComponent;
exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals$1;
exports.cloneElement = cloneElement$1;
exports.createContext = createContext;
exports.createElement = createElement$1;
exports.createFactory = createFactory;
exports.createRef = createRef;
exports.forwardRef = forwardRef;
exports.isValidElement = isValidElement;
exports.lazy = lazy;
exports.memo = memo;
exports.startTransition = startTransition;
exports.unstable_act = act;
exports.unstable_createMutableSource = createMutableSource;
exports.unstable_useMutableSource = useMutableSource;
exports.unstable_useOpaqueIdentifier = useOpaqueIdentifier;
exports.useCallback = useCallback;
exports.useContext = useContext;
exports.useDebugValue = useDebugValue;
exports.useDeferredValue = useDeferredValue;
exports.useEffect = useEffect;
exports.useImperativeHandle = useImperativeHandle;
exports.useLayoutEffect = useLayoutEffect;
exports.useMemo = useMemo;
exports.useReducer = useReducer;
exports.useRef = useRef;
exports.useState = useState;
exports.useTransition = useTransition;
exports.version = ReactVersion;
})));
|
"use strict";
var _extends = require("@babel/runtime/helpers/extends"), react = require("@emotion/react"), _taggedTemplateLiteral = require("@babel/runtime/helpers/taggedTemplateLiteral"), _objectWithoutProperties = require("@babel/runtime/helpers/objectWithoutProperties"), AutosizeInput = require("react-input-autosize"), _classCallCheck = require("@babel/runtime/helpers/classCallCheck"), _createClass = require("@babel/runtime/helpers/createClass"), _inherits = require("@babel/runtime/helpers/inherits"), _defineProperty$1 = require("@babel/runtime/helpers/defineProperty"), React = require("react"), reactDom = require("react-dom"), _typeof = require("@babel/runtime/helpers/typeof");
function _interopDefault(e) {
return e && e.__esModule ? e : {
default: e
};
}
var _extends__default = _interopDefault(_extends), _taggedTemplateLiteral__default = _interopDefault(_taggedTemplateLiteral), _objectWithoutProperties__default = _interopDefault(_objectWithoutProperties), AutosizeInput__default = _interopDefault(AutosizeInput), _classCallCheck__default = _interopDefault(_classCallCheck), _createClass__default = _interopDefault(_createClass), _inherits__default = _interopDefault(_inherits), _defineProperty__default = _interopDefault(_defineProperty$1), _typeof__default = _interopDefault(_typeof);
function _defineProperty(obj, key, value) {
return key in obj ? Object.defineProperty(obj, key, {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}) : obj[key] = value, obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter((function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
}))), keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? ownKeys(Object(source), !0).forEach((function(key) {
_defineProperty(target, key, source[key]);
})) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach((function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
}));
}
return target;
}
function _getPrototypeOf(o) {
return (_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function(o) {
return o.__proto__ || Object.getPrototypeOf(o);
})(o);
}
function _isNativeReflectConstruct() {
if ("undefined" == typeof Reflect || !Reflect.construct) return !1;
if (Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Date.prototype.toString.call(Reflect.construct(Date, [], (function() {}))),
!0;
} catch (e) {
return !1;
}
}
function _assertThisInitialized(self) {
if (void 0 === self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return self;
}
function _possibleConstructorReturn(self, call) {
return !call || "object" != typeof call && "function" != typeof call ? _assertThisInitialized(self) : call;
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function() {
var result, Super = _getPrototypeOf(Derived);
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else result = Super.apply(this, arguments);
return _possibleConstructorReturn(this, result);
};
}
var noop = function() {};
function applyPrefixToName(prefix, name) {
return name ? "-" === name[0] ? prefix + name : prefix + "__" + name : prefix;
}
function classNames(prefix, state, className) {
var arr = [ className ];
if (state && prefix) for (var key in state) state.hasOwnProperty(key) && state[key] && arr.push("".concat(applyPrefixToName(prefix, key)));
return arr.filter((function(i) {
return i;
})).map((function(i) {
return String(i).trim();
})).join(" ");
}
var cleanValue = function(value) {
return Array.isArray(value) ? value.filter(Boolean) : "object" === _typeof__default.default(value) && null !== value ? [ value ] : [];
};
function handleInputChange(inputValue, actionMeta, onInputChange) {
if (onInputChange) {
var newValue = onInputChange(inputValue, actionMeta);
if ("string" == typeof newValue) return newValue;
}
return inputValue;
}
function isDocumentElement(el) {
return [ document.documentElement, document.body, window ].indexOf(el) > -1;
}
function getScrollTop(el) {
return isDocumentElement(el) ? window.pageYOffset : el.scrollTop;
}
function scrollTo(el, top) {
isDocumentElement(el) ? window.scrollTo(0, top) : el.scrollTop = top;
}
function getScrollParent(element) {
var style = getComputedStyle(element), excludeStaticParent = "absolute" === style.position, overflowRx = /(auto|scroll)/, docEl = document.documentElement;
if ("fixed" === style.position) return docEl;
for (var parent = element; parent = parent.parentElement; ) if (style = getComputedStyle(parent),
(!excludeStaticParent || "static" !== style.position) && overflowRx.test(style.overflow + style.overflowY + style.overflowX)) return parent;
return docEl;
}
function easeOutCubic(t, b, c, d) {
return c * ((t = t / d - 1) * t * t + 1) + b;
}
function animatedScrollTo(element, to) {
var duration = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 200, callback = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : noop, start = getScrollTop(element), change = to - start, increment = 10, currentTime = 0;
function animateScroll() {
var val = easeOutCubic(currentTime += increment, start, change, duration);
scrollTo(element, val), currentTime < duration ? window.requestAnimationFrame(animateScroll) : callback(element);
}
animateScroll();
}
function scrollIntoView(menuEl, focusedEl) {
var menuRect = menuEl.getBoundingClientRect(), focusedRect = focusedEl.getBoundingClientRect(), overScroll = focusedEl.offsetHeight / 3;
focusedRect.bottom + overScroll > menuRect.bottom ? scrollTo(menuEl, Math.min(focusedEl.offsetTop + focusedEl.clientHeight - menuEl.offsetHeight + overScroll, menuEl.scrollHeight)) : focusedRect.top - overScroll < menuRect.top && scrollTo(menuEl, Math.max(focusedEl.offsetTop - overScroll, 0));
}
function getBoundingClientObj(element) {
var rect = element.getBoundingClientRect();
return {
bottom: rect.bottom,
height: rect.height,
left: rect.left,
right: rect.right,
top: rect.top,
width: rect.width
};
}
function isTouchCapable() {
try {
return document.createEvent("TouchEvent"), !0;
} catch (e) {
return !1;
}
}
function isMobileDevice() {
try {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
} catch (e) {
return !1;
}
}
function getMenuPlacement(_ref) {
var maxHeight = _ref.maxHeight, menuEl = _ref.menuEl, minHeight = _ref.minHeight, placement = _ref.placement, shouldScroll = _ref.shouldScroll, isFixedPosition = _ref.isFixedPosition, spacing = _ref.theme.spacing, scrollParent = getScrollParent(menuEl), defaultState = {
placement: "bottom",
maxHeight: maxHeight
};
if (!menuEl || !menuEl.offsetParent) return defaultState;
var scrollHeight = scrollParent.getBoundingClientRect().height, _menuEl$getBoundingCl = menuEl.getBoundingClientRect(), menuBottom = _menuEl$getBoundingCl.bottom, menuHeight = _menuEl$getBoundingCl.height, menuTop = _menuEl$getBoundingCl.top, containerTop = menuEl.offsetParent.getBoundingClientRect().top, viewHeight = window.innerHeight, scrollTop = getScrollTop(scrollParent), marginBottom = parseInt(getComputedStyle(menuEl).marginBottom, 10), marginTop = parseInt(getComputedStyle(menuEl).marginTop, 10), viewSpaceAbove = containerTop - marginTop, viewSpaceBelow = viewHeight - menuTop, scrollSpaceAbove = viewSpaceAbove + scrollTop, scrollSpaceBelow = scrollHeight - scrollTop - menuTop, scrollDown = menuBottom - viewHeight + scrollTop + marginBottom, scrollUp = scrollTop + menuTop - marginTop;
switch (placement) {
case "auto":
case "bottom":
if (viewSpaceBelow >= menuHeight) return {
placement: "bottom",
maxHeight: maxHeight
};
if (scrollSpaceBelow >= menuHeight && !isFixedPosition) return shouldScroll && animatedScrollTo(scrollParent, scrollDown, 160),
{
placement: "bottom",
maxHeight: maxHeight
};
if (!isFixedPosition && scrollSpaceBelow >= minHeight || isFixedPosition && viewSpaceBelow >= minHeight) return shouldScroll && animatedScrollTo(scrollParent, scrollDown, 160),
{
placement: "bottom",
maxHeight: isFixedPosition ? viewSpaceBelow - marginBottom : scrollSpaceBelow - marginBottom
};
if ("auto" === placement || isFixedPosition) {
var _constrainedHeight = maxHeight, spaceAbove = isFixedPosition ? viewSpaceAbove : scrollSpaceAbove;
return spaceAbove >= minHeight && (_constrainedHeight = Math.min(spaceAbove - marginBottom - spacing.controlHeight, maxHeight)),
{
placement: "top",
maxHeight: _constrainedHeight
};
}
if ("bottom" === placement) return scrollTo(scrollParent, scrollDown), {
placement: "bottom",
maxHeight: maxHeight
};
break;
case "top":
if (viewSpaceAbove >= menuHeight) return {
placement: "top",
maxHeight: maxHeight
};
if (scrollSpaceAbove >= menuHeight && !isFixedPosition) return shouldScroll && animatedScrollTo(scrollParent, scrollUp, 160),
{
placement: "top",
maxHeight: maxHeight
};
if (!isFixedPosition && scrollSpaceAbove >= minHeight || isFixedPosition && viewSpaceAbove >= minHeight) {
var _constrainedHeight2 = maxHeight;
return (!isFixedPosition && scrollSpaceAbove >= minHeight || isFixedPosition && viewSpaceAbove >= minHeight) && (_constrainedHeight2 = isFixedPosition ? viewSpaceAbove - marginTop : scrollSpaceAbove - marginTop),
shouldScroll && animatedScrollTo(scrollParent, scrollUp, 160), {
placement: "top",
maxHeight: _constrainedHeight2
};
}
return {
placement: "bottom",
maxHeight: maxHeight
};
default:
throw new Error('Invalid placement provided "'.concat(placement, '".'));
}
return defaultState;
}
function alignToControl(placement) {
return placement ? {
bottom: "top",
top: "bottom"
}[placement] : "bottom";
}
var coercePlacement = function(p) {
return "auto" === p ? "bottom" : p;
}, menuCSS = function(_ref2) {
var _ref3, placement = _ref2.placement, _ref2$theme = _ref2.theme, borderRadius = _ref2$theme.borderRadius, spacing = _ref2$theme.spacing, colors = _ref2$theme.colors;
return _ref3 = {
label: "menu"
}, _defineProperty__default.default(_ref3, alignToControl(placement), "100%"), _defineProperty__default.default(_ref3, "backgroundColor", colors.neutral0),
_defineProperty__default.default(_ref3, "borderRadius", borderRadius), _defineProperty__default.default(_ref3, "boxShadow", "0 0 0 1px hsla(0, 0%, 0%, 0.1), 0 4px 11px hsla(0, 0%, 0%, 0.1)"),
_defineProperty__default.default(_ref3, "marginBottom", spacing.menuGutter), _defineProperty__default.default(_ref3, "marginTop", spacing.menuGutter),
_defineProperty__default.default(_ref3, "position", "absolute"), _defineProperty__default.default(_ref3, "width", "100%"),
_defineProperty__default.default(_ref3, "zIndex", 1), _ref3;
}, PortalPlacementContext = React.createContext({
getPortalPlacement: null
}), MenuPlacer = function(_Component) {
_inherits__default.default(MenuPlacer, _Component);
var _super = _createSuper(MenuPlacer);
function MenuPlacer() {
var _this;
_classCallCheck__default.default(this, MenuPlacer);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
return (_this = _super.call.apply(_super, [ this ].concat(args))).state = {
maxHeight: _this.props.maxMenuHeight,
placement: null
}, _this.getPlacement = function(ref) {
var _this$props = _this.props, minMenuHeight = _this$props.minMenuHeight, maxMenuHeight = _this$props.maxMenuHeight, menuPlacement = _this$props.menuPlacement, menuPosition = _this$props.menuPosition, menuShouldScrollIntoView = _this$props.menuShouldScrollIntoView, theme = _this$props.theme;
if (ref) {
var isFixedPosition = "fixed" === menuPosition, state = getMenuPlacement({
maxHeight: maxMenuHeight,
menuEl: ref,
minHeight: minMenuHeight,
placement: menuPlacement,
shouldScroll: menuShouldScrollIntoView && !isFixedPosition,
isFixedPosition: isFixedPosition,
theme: theme
}), getPortalPlacement = _this.context.getPortalPlacement;
getPortalPlacement && getPortalPlacement(state), _this.setState(state);
}
}, _this.getUpdatedProps = function() {
var menuPlacement = _this.props.menuPlacement, placement = _this.state.placement || coercePlacement(menuPlacement);
return _objectSpread2(_objectSpread2({}, _this.props), {}, {
placement: placement,
maxHeight: _this.state.maxHeight
});
}, _this;
}
return _createClass__default.default(MenuPlacer, [ {
key: "render",
value: function() {
return (0, this.props.children)({
ref: this.getPlacement,
placerProps: this.getUpdatedProps()
});
}
} ]), MenuPlacer;
}(React.Component);
MenuPlacer.contextType = PortalPlacementContext;
var Menu = function(props) {
var children = props.children, className = props.className, cx = props.cx, getStyles = props.getStyles, innerRef = props.innerRef, innerProps = props.innerProps;
return react.jsx("div", _extends__default.default({
css: getStyles("menu", props),
className: cx({
menu: !0
}, className),
ref: innerRef
}, innerProps), children);
}, menuListCSS = function(_ref4) {
var maxHeight = _ref4.maxHeight, baseUnit = _ref4.theme.spacing.baseUnit;
return {
maxHeight: maxHeight,
overflowY: "auto",
paddingBottom: baseUnit,
paddingTop: baseUnit,
position: "relative",
WebkitOverflowScrolling: "touch"
};
}, MenuList = function(props) {
var children = props.children, className = props.className, cx = props.cx, getStyles = props.getStyles, innerProps = props.innerProps, innerRef = props.innerRef, isMulti = props.isMulti;
return react.jsx("div", _extends__default.default({
css: getStyles("menuList", props),
className: cx({
"menu-list": !0,
"menu-list--is-multi": isMulti
}, className),
ref: innerRef
}, innerProps), children);
}, noticeCSS = function(_ref5) {
var _ref5$theme = _ref5.theme, baseUnit = _ref5$theme.spacing.baseUnit;
return {
color: _ref5$theme.colors.neutral40,
padding: "".concat(2 * baseUnit, "px ").concat(3 * baseUnit, "px"),
textAlign: "center"
};
}, noOptionsMessageCSS = noticeCSS, loadingMessageCSS = noticeCSS, NoOptionsMessage = function(props) {
var children = props.children, className = props.className, cx = props.cx, getStyles = props.getStyles, innerProps = props.innerProps;
return react.jsx("div", _extends__default.default({
css: getStyles("noOptionsMessage", props),
className: cx({
"menu-notice": !0,
"menu-notice--no-options": !0
}, className)
}, innerProps), children);
};
NoOptionsMessage.defaultProps = {
children: "No options"
};
var LoadingMessage = function(props) {
var children = props.children, className = props.className, cx = props.cx, getStyles = props.getStyles, innerProps = props.innerProps;
return react.jsx("div", _extends__default.default({
css: getStyles("loadingMessage", props),
className: cx({
"menu-notice": !0,
"menu-notice--loading": !0
}, className)
}, innerProps), children);
};
LoadingMessage.defaultProps = {
children: "Loading..."
};
var _templateObject, menuPortalCSS = function(_ref6) {
var rect = _ref6.rect, offset = _ref6.offset, position = _ref6.position;
return {
left: rect.left,
position: position,
top: offset,
width: rect.width,
zIndex: 1
};
}, MenuPortal = function(_Component2) {
_inherits__default.default(MenuPortal, _Component2);
var _super2 = _createSuper(MenuPortal);
function MenuPortal() {
var _this2;
_classCallCheck__default.default(this, MenuPortal);
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) args[_key2] = arguments[_key2];
return (_this2 = _super2.call.apply(_super2, [ this ].concat(args))).state = {
placement: null
}, _this2.getPortalPlacement = function(_ref7) {
var placement = _ref7.placement;
placement !== coercePlacement(_this2.props.menuPlacement) && _this2.setState({
placement: placement
});
}, _this2;
}
return _createClass__default.default(MenuPortal, [ {
key: "render",
value: function() {
var _this$props2 = this.props, appendTo = _this$props2.appendTo, children = _this$props2.children, className = _this$props2.className, controlElement = _this$props2.controlElement, cx = _this$props2.cx, innerProps = _this$props2.innerProps, menuPlacement = _this$props2.menuPlacement, position = _this$props2.menuPosition, getStyles = _this$props2.getStyles, isFixed = "fixed" === position;
if (!appendTo && !isFixed || !controlElement) return null;
var placement = this.state.placement || coercePlacement(menuPlacement), rect = getBoundingClientObj(controlElement), scrollDistance = isFixed ? 0 : window.pageYOffset, state = {
offset: rect[placement] + scrollDistance,
position: position,
rect: rect
}, menuWrapper = react.jsx("div", _extends__default.default({
css: getStyles("menuPortal", state),
className: cx({
"menu-portal": !0
}, className)
}, innerProps), children);
return react.jsx(PortalPlacementContext.Provider, {
value: {
getPortalPlacement: this.getPortalPlacement
}
}, appendTo ? reactDom.createPortal(menuWrapper, appendTo) : menuWrapper);
}
} ]), MenuPortal;
}(React.Component), containerCSS = function(_ref) {
var isDisabled = _ref.isDisabled;
return {
label: "container",
direction: _ref.isRtl ? "rtl" : null,
pointerEvents: isDisabled ? "none" : null,
position: "relative"
};
}, SelectContainer = function(props) {
var children = props.children, className = props.className, cx = props.cx, getStyles = props.getStyles, innerProps = props.innerProps, isDisabled = props.isDisabled, isRtl = props.isRtl;
return react.jsx("div", _extends__default.default({
css: getStyles("container", props),
className: cx({
"--is-disabled": isDisabled,
"--is-rtl": isRtl
}, className)
}, innerProps), children);
}, valueContainerCSS = function(_ref2) {
var spacing = _ref2.theme.spacing;
return {
alignItems: "center",
display: "flex",
flex: 1,
flexWrap: "wrap",
padding: "".concat(spacing.baseUnit / 2, "px ").concat(2 * spacing.baseUnit, "px"),
WebkitOverflowScrolling: "touch",
position: "relative",
overflow: "hidden"
};
}, ValueContainer = function(props) {
var children = props.children, className = props.className, cx = props.cx, innerProps = props.innerProps, isMulti = props.isMulti, getStyles = props.getStyles, hasValue = props.hasValue;
return react.jsx("div", _extends__default.default({
css: getStyles("valueContainer", props),
className: cx({
"value-container": !0,
"value-container--is-multi": isMulti,
"value-container--has-value": hasValue
}, className)
}, innerProps), children);
}, indicatorsContainerCSS = function() {
return {
alignItems: "center",
alignSelf: "stretch",
display: "flex",
flexShrink: 0
};
}, IndicatorsContainer = function(props) {
var children = props.children, className = props.className, cx = props.cx, innerProps = props.innerProps, getStyles = props.getStyles;
return react.jsx("div", _extends__default.default({
css: getStyles("indicatorsContainer", props),
className: cx({
indicators: !0
}, className)
}, innerProps), children);
};
function _EMOTION_STRINGIFIED_CSS_ERROR__() {
return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop).";
}
var _ref2 = {
name: "8mmkcg",
styles: "display:inline-block;fill:currentColor;line-height:1;stroke:currentColor;stroke-width:0"
}, Svg = function(_ref) {
var size = _ref.size, props = _objectWithoutProperties__default.default(_ref, [ "size" ]);
return react.jsx("svg", _extends__default.default({
height: size,
width: size,
viewBox: "0 0 20 20",
"aria-hidden": "true",
focusable: "false",
css: _ref2
}, props));
}, CrossIcon = function(props) {
return react.jsx(Svg, _extends__default.default({
size: 20
}, props), react.jsx("path", {
d: "M14.348 14.849c-0.469 0.469-1.229 0.469-1.697 0l-2.651-3.030-2.651 3.029c-0.469 0.469-1.229 0.469-1.697 0-0.469-0.469-0.469-1.229 0-1.697l2.758-3.15-2.759-3.152c-0.469-0.469-0.469-1.228 0-1.697s1.228-0.469 1.697 0l2.652 3.031 2.651-3.031c0.469-0.469 1.228-0.469 1.697 0s0.469 1.229 0 1.697l-2.758 3.152 2.758 3.15c0.469 0.469 0.469 1.229 0 1.698z"
}));
}, DownChevron = function(props) {
return react.jsx(Svg, _extends__default.default({
size: 20
}, props), react.jsx("path", {
d: "M4.516 7.548c0.436-0.446 1.043-0.481 1.576 0l3.908 3.747 3.908-3.747c0.533-0.481 1.141-0.446 1.574 0 0.436 0.445 0.408 1.197 0 1.615-0.406 0.418-4.695 4.502-4.695 4.502-0.217 0.223-0.502 0.335-0.787 0.335s-0.57-0.112-0.789-0.335c0 0-4.287-4.084-4.695-4.502s-0.436-1.17 0-1.615z"
}));
}, baseCSS = function(_ref3) {
var isFocused = _ref3.isFocused, _ref3$theme = _ref3.theme, baseUnit = _ref3$theme.spacing.baseUnit, colors = _ref3$theme.colors;
return {
label: "indicatorContainer",
color: isFocused ? colors.neutral60 : colors.neutral20,
display: "flex",
padding: 2 * baseUnit,
transition: "color 150ms",
":hover": {
color: isFocused ? colors.neutral80 : colors.neutral40
}
};
}, dropdownIndicatorCSS = baseCSS, DropdownIndicator = function(props) {
var children = props.children, className = props.className, cx = props.cx, getStyles = props.getStyles, innerProps = props.innerProps;
return react.jsx("div", _extends__default.default({
css: getStyles("dropdownIndicator", props),
className: cx({
indicator: !0,
"dropdown-indicator": !0
}, className)
}, innerProps), children || react.jsx(DownChevron, null));
}, clearIndicatorCSS = baseCSS, ClearIndicator = function(props) {
var children = props.children, className = props.className, cx = props.cx, getStyles = props.getStyles, innerProps = props.innerProps;
return react.jsx("div", _extends__default.default({
css: getStyles("clearIndicator", props),
className: cx({
indicator: !0,
"clear-indicator": !0
}, className)
}, innerProps), children || react.jsx(CrossIcon, null));
}, indicatorSeparatorCSS = function(_ref4) {
var isDisabled = _ref4.isDisabled, _ref4$theme = _ref4.theme, baseUnit = _ref4$theme.spacing.baseUnit, colors = _ref4$theme.colors;
return {
label: "indicatorSeparator",
alignSelf: "stretch",
backgroundColor: isDisabled ? colors.neutral10 : colors.neutral20,
marginBottom: 2 * baseUnit,
marginTop: 2 * baseUnit,
width: 1
};
}, IndicatorSeparator = function(props) {
var className = props.className, cx = props.cx, getStyles = props.getStyles, innerProps = props.innerProps;
return react.jsx("span", _extends__default.default({}, innerProps, {
css: getStyles("indicatorSeparator", props),
className: cx({
"indicator-separator": !0
}, className)
}));
}, loadingDotAnimations = react.keyframes(_templateObject || (_templateObject = _taggedTemplateLiteral__default.default([ "\n 0%, 80%, 100% { opacity: 0; }\n 40% { opacity: 1; }\n" ]))), loadingIndicatorCSS = function(_ref5) {
var isFocused = _ref5.isFocused, size = _ref5.size, _ref5$theme = _ref5.theme, colors = _ref5$theme.colors, baseUnit = _ref5$theme.spacing.baseUnit;
return {
label: "loadingIndicator",
color: isFocused ? colors.neutral60 : colors.neutral20,
display: "flex",
padding: 2 * baseUnit,
transition: "color 150ms",
alignSelf: "center",
fontSize: size,
lineHeight: 1,
marginRight: size,
textAlign: "center",
verticalAlign: "middle"
};
}, LoadingDot = function(_ref6) {
var delay = _ref6.delay, offset = _ref6.offset;
return react.jsx("span", {
css: react.css({
animation: "".concat(loadingDotAnimations, " 1s ease-in-out ").concat(delay, "ms infinite;"),
backgroundColor: "currentColor",
borderRadius: "1em",
display: "inline-block",
marginLeft: offset ? "1em" : null,
height: "1em",
verticalAlign: "top",
width: "1em"
}, "", "")
});
}, LoadingIndicator = function(props) {
var className = props.className, cx = props.cx, getStyles = props.getStyles, innerProps = props.innerProps, isRtl = props.isRtl;
return react.jsx("div", _extends__default.default({
css: getStyles("loadingIndicator", props),
className: cx({
indicator: !0,
"loading-indicator": !0
}, className)
}, innerProps), react.jsx(LoadingDot, {
delay: 0,
offset: isRtl
}), react.jsx(LoadingDot, {
delay: 160,
offset: !0
}), react.jsx(LoadingDot, {
delay: 320,
offset: !isRtl
}));
};
LoadingIndicator.defaultProps = {
size: 4
};
var css = function(_ref) {
var isDisabled = _ref.isDisabled, isFocused = _ref.isFocused, _ref$theme = _ref.theme, colors = _ref$theme.colors, borderRadius = _ref$theme.borderRadius, spacing = _ref$theme.spacing;
return {
label: "control",
alignItems: "center",
backgroundColor: isDisabled ? colors.neutral5 : colors.neutral0,
borderColor: isDisabled ? colors.neutral10 : isFocused ? colors.primary : colors.neutral20,
borderRadius: borderRadius,
borderStyle: "solid",
borderWidth: 1,
boxShadow: isFocused ? "0 0 0 1px ".concat(colors.primary) : null,
cursor: "default",
display: "flex",
flexWrap: "wrap",
justifyContent: "space-between",
minHeight: spacing.controlHeight,
outline: "0 !important",
position: "relative",
transition: "all 100ms",
"&:hover": {
borderColor: isFocused ? colors.primary : colors.neutral30
}
};
}, Control = function(props) {
var children = props.children, cx = props.cx, getStyles = props.getStyles, className = props.className, isDisabled = props.isDisabled, isFocused = props.isFocused, innerRef = props.innerRef, innerProps = props.innerProps, menuIsOpen = props.menuIsOpen;
return react.jsx("div", _extends__default.default({
ref: innerRef,
css: getStyles("control", props),
className: cx({
control: !0,
"control--is-disabled": isDisabled,
"control--is-focused": isFocused,
"control--menu-is-open": menuIsOpen
}, className)
}, innerProps), children);
}, groupCSS = function(_ref) {
var spacing = _ref.theme.spacing;
return {
paddingBottom: 2 * spacing.baseUnit,
paddingTop: 2 * spacing.baseUnit
};
}, Group = function(props) {
var children = props.children, className = props.className, cx = props.cx, getStyles = props.getStyles, Heading = props.Heading, headingProps = props.headingProps, innerProps = props.innerProps, label = props.label, theme = props.theme, selectProps = props.selectProps;
return react.jsx("div", _extends__default.default({
css: getStyles("group", props),
className: cx({
group: !0
}, className)
}, innerProps), react.jsx(Heading, _extends__default.default({}, headingProps, {
selectProps: selectProps,
theme: theme,
getStyles: getStyles,
cx: cx
}), label), react.jsx("div", null, children));
}, groupHeadingCSS = function(_ref2) {
var spacing = _ref2.theme.spacing;
return {
label: "group",
color: "#999",
cursor: "default",
display: "block",
fontSize: "75%",
fontWeight: "500",
marginBottom: "0.25em",
paddingLeft: 3 * spacing.baseUnit,
paddingRight: 3 * spacing.baseUnit,
textTransform: "uppercase"
};
}, GroupHeading = function(props) {
var className = props.className, cx = props.cx, getStyles = props.getStyles, theme = props.theme;
props.selectProps;
var cleanProps = _objectWithoutProperties__default.default(props, [ "className", "cx", "getStyles", "theme", "selectProps" ]);
return react.jsx("div", _extends__default.default({
css: getStyles("groupHeading", _objectSpread2({
theme: theme
}, cleanProps)),
className: cx({
"group-heading": !0
}, className)
}, cleanProps));
}, inputCSS = function(_ref) {
var isDisabled = _ref.isDisabled, _ref$theme = _ref.theme, spacing = _ref$theme.spacing, colors = _ref$theme.colors;
return {
margin: spacing.baseUnit / 2,
paddingBottom: spacing.baseUnit / 2,
paddingTop: spacing.baseUnit / 2,
visibility: isDisabled ? "hidden" : "visible",
color: colors.neutral80
};
}, inputStyle = function(isHidden) {
return {
label: "input",
background: 0,
border: 0,
fontSize: "inherit",
opacity: isHidden ? 0 : 1,
outline: 0,
padding: 0,
color: "inherit"
};
}, Input = function(_ref2) {
var className = _ref2.className, cx = _ref2.cx, getStyles = _ref2.getStyles, innerRef = _ref2.innerRef, isHidden = _ref2.isHidden, isDisabled = _ref2.isDisabled, theme = _ref2.theme;
_ref2.selectProps;
var props = _objectWithoutProperties__default.default(_ref2, [ "className", "cx", "getStyles", "innerRef", "isHidden", "isDisabled", "theme", "selectProps" ]);
return react.jsx("div", {
css: getStyles("input", _objectSpread2({
theme: theme
}, props))
}, react.jsx(AutosizeInput__default.default, _extends__default.default({
className: cx({
input: !0
}, className),
inputRef: innerRef,
inputStyle: inputStyle(isHidden),
disabled: isDisabled
}, props)));
}, multiValueCSS = function(_ref) {
var _ref$theme = _ref.theme, spacing = _ref$theme.spacing, borderRadius = _ref$theme.borderRadius;
return {
label: "multiValue",
backgroundColor: _ref$theme.colors.neutral10,
borderRadius: borderRadius / 2,
display: "flex",
margin: spacing.baseUnit / 2,
minWidth: 0
};
}, multiValueLabelCSS = function(_ref2) {
var _ref2$theme = _ref2.theme, borderRadius = _ref2$theme.borderRadius, colors = _ref2$theme.colors, cropWithEllipsis = _ref2.cropWithEllipsis;
return {
borderRadius: borderRadius / 2,
color: colors.neutral80,
fontSize: "85%",
overflow: "hidden",
padding: 3,
paddingLeft: 6,
textOverflow: cropWithEllipsis ? "ellipsis" : null,
whiteSpace: "nowrap"
};
}, multiValueRemoveCSS = function(_ref3) {
var _ref3$theme = _ref3.theme, spacing = _ref3$theme.spacing, borderRadius = _ref3$theme.borderRadius, colors = _ref3$theme.colors;
return {
alignItems: "center",
borderRadius: borderRadius / 2,
backgroundColor: _ref3.isFocused && colors.dangerLight,
display: "flex",
paddingLeft: spacing.baseUnit,
paddingRight: spacing.baseUnit,
":hover": {
backgroundColor: colors.dangerLight,
color: colors.danger
}
};
}, MultiValueGeneric = function(_ref4) {
var children = _ref4.children, innerProps = _ref4.innerProps;
return react.jsx("div", innerProps, children);
}, MultiValueContainer = MultiValueGeneric, MultiValueLabel = MultiValueGeneric;
function MultiValueRemove(_ref5) {
var children = _ref5.children, innerProps = _ref5.innerProps;
return react.jsx("div", innerProps, children || react.jsx(CrossIcon, {
size: 14
}));
}
var MultiValue = function(props) {
var children = props.children, className = props.className, components = props.components, cx = props.cx, data = props.data, getStyles = props.getStyles, innerProps = props.innerProps, isDisabled = props.isDisabled, removeProps = props.removeProps, selectProps = props.selectProps, Container = components.Container, Label = components.Label, Remove = components.Remove;
return react.jsx(react.ClassNames, null, (function(_ref6) {
var css = _ref6.css, emotionCx = _ref6.cx;
return react.jsx(Container, {
data: data,
innerProps: _objectSpread2({
className: emotionCx(css(getStyles("multiValue", props)), cx({
"multi-value": !0,
"multi-value--is-disabled": isDisabled
}, className))
}, innerProps),
selectProps: selectProps
}, react.jsx(Label, {
data: data,
innerProps: {
className: emotionCx(css(getStyles("multiValueLabel", props)), cx({
"multi-value__label": !0
}, className))
},
selectProps: selectProps
}, children), react.jsx(Remove, {
data: data,
innerProps: _objectSpread2({
className: emotionCx(css(getStyles("multiValueRemove", props)), cx({
"multi-value__remove": !0
}, className))
}, removeProps),
selectProps: selectProps
}));
}));
};
MultiValue.defaultProps = {
cropWithEllipsis: !0
};
var optionCSS = function(_ref) {
var isDisabled = _ref.isDisabled, isFocused = _ref.isFocused, isSelected = _ref.isSelected, _ref$theme = _ref.theme, spacing = _ref$theme.spacing, colors = _ref$theme.colors;
return {
label: "option",
backgroundColor: isSelected ? colors.primary : isFocused ? colors.primary25 : "transparent",
color: isDisabled ? colors.neutral20 : isSelected ? colors.neutral0 : "inherit",
cursor: "default",
display: "block",
fontSize: "inherit",
padding: "".concat(2 * spacing.baseUnit, "px ").concat(3 * spacing.baseUnit, "px"),
width: "100%",
userSelect: "none",
WebkitTapHighlightColor: "rgba(0, 0, 0, 0)",
":active": {
backgroundColor: !isDisabled && (isSelected ? colors.primary : colors.primary50)
}
};
}, Option = function(props) {
var children = props.children, className = props.className, cx = props.cx, getStyles = props.getStyles, isDisabled = props.isDisabled, isFocused = props.isFocused, isSelected = props.isSelected, innerRef = props.innerRef, innerProps = props.innerProps;
return react.jsx("div", _extends__default.default({
css: getStyles("option", props),
className: cx({
option: !0,
"option--is-disabled": isDisabled,
"option--is-focused": isFocused,
"option--is-selected": isSelected
}, className),
ref: innerRef
}, innerProps), children);
}, placeholderCSS = function(_ref) {
var _ref$theme = _ref.theme, spacing = _ref$theme.spacing;
return {
label: "placeholder",
color: _ref$theme.colors.neutral50,
marginLeft: spacing.baseUnit / 2,
marginRight: spacing.baseUnit / 2,
position: "absolute",
top: "50%",
transform: "translateY(-50%)"
};
}, Placeholder = function(props) {
var children = props.children, className = props.className, cx = props.cx, getStyles = props.getStyles, innerProps = props.innerProps;
return react.jsx("div", _extends__default.default({
css: getStyles("placeholder", props),
className: cx({
placeholder: !0
}, className)
}, innerProps), children);
}, css$1 = function(_ref) {
var isDisabled = _ref.isDisabled, _ref$theme = _ref.theme, spacing = _ref$theme.spacing, colors = _ref$theme.colors;
return {
label: "singleValue",
color: isDisabled ? colors.neutral40 : colors.neutral80,
marginLeft: spacing.baseUnit / 2,
marginRight: spacing.baseUnit / 2,
maxWidth: "calc(100% - ".concat(2 * spacing.baseUnit, "px)"),
overflow: "hidden",
position: "absolute",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
top: "50%",
transform: "translateY(-50%)"
};
}, SingleValue = function(props) {
var children = props.children, className = props.className, cx = props.cx, getStyles = props.getStyles, isDisabled = props.isDisabled, innerProps = props.innerProps;
return react.jsx("div", _extends__default.default({
css: getStyles("singleValue", props),
className: cx({
"single-value": !0,
"single-value--is-disabled": isDisabled
}, className)
}, innerProps), children);
}, components = {
ClearIndicator: ClearIndicator,
Control: Control,
DropdownIndicator: DropdownIndicator,
DownChevron: DownChevron,
CrossIcon: CrossIcon,
Group: Group,
GroupHeading: GroupHeading,
IndicatorsContainer: IndicatorsContainer,
IndicatorSeparator: IndicatorSeparator,
Input: Input,
LoadingIndicator: LoadingIndicator,
Menu: Menu,
MenuList: MenuList,
MenuPortal: MenuPortal,
LoadingMessage: LoadingMessage,
NoOptionsMessage: NoOptionsMessage,
MultiValue: MultiValue,
MultiValueContainer: MultiValueContainer,
MultiValueLabel: MultiValueLabel,
MultiValueRemove: MultiValueRemove,
Option: Option,
Placeholder: Placeholder,
SelectContainer: SelectContainer,
SingleValue: SingleValue,
ValueContainer: ValueContainer
}, defaultComponents = function(props) {
return _objectSpread2(_objectSpread2({}, components), props.components);
};
exports.MenuPlacer = MenuPlacer, exports._createSuper = _createSuper, exports._objectSpread2 = _objectSpread2,
exports.classNames = classNames, exports.cleanValue = cleanValue, exports.clearIndicatorCSS = clearIndicatorCSS,
exports.components = components, exports.containerCSS = containerCSS, exports.css = css,
exports.css$1 = css$1, exports.defaultComponents = defaultComponents, exports.dropdownIndicatorCSS = dropdownIndicatorCSS,
exports.groupCSS = groupCSS, exports.groupHeadingCSS = groupHeadingCSS, exports.handleInputChange = handleInputChange,
exports.indicatorSeparatorCSS = indicatorSeparatorCSS, exports.indicatorsContainerCSS = indicatorsContainerCSS,
exports.inputCSS = inputCSS, exports.isDocumentElement = isDocumentElement, exports.isMobileDevice = isMobileDevice,
exports.isTouchCapable = isTouchCapable, exports.loadingIndicatorCSS = loadingIndicatorCSS,
exports.loadingMessageCSS = loadingMessageCSS, exports.menuCSS = menuCSS, exports.menuListCSS = menuListCSS,
exports.menuPortalCSS = menuPortalCSS, exports.multiValueCSS = multiValueCSS, exports.multiValueLabelCSS = multiValueLabelCSS,
exports.multiValueRemoveCSS = multiValueRemoveCSS, exports.noOptionsMessageCSS = noOptionsMessageCSS,
exports.noop = noop, exports.optionCSS = optionCSS, exports.placeholderCSS = placeholderCSS,
exports.scrollIntoView = scrollIntoView, exports.valueContainerCSS = valueContainerCSS;
|
/**
* vee-validate v3.1.0
* (c) 2019 Abdelrahman Awad
* @license MIT
*/
/**
* Some Alpha Regex helpers.
* https://github.com/chriso/validator.js/blob/master/src/lib/alpha.js
*/
var alpha = {
en: /^[A-Z]*$/i,
cs: /^[A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]*$/i,
da: /^[A-ZÆØÅ]*$/i,
de: /^[A-ZÄÖÜß]*$/i,
es: /^[A-ZÁÉÍÑÓÚÜ]*$/i,
fr: /^[A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]*$/i,
it: /^[A-Z\xC0-\xFF]*$/i,
lt: /^[A-ZĄČĘĖĮŠŲŪŽ]*$/i,
nl: /^[A-ZÉËÏÓÖÜ]*$/i,
hu: /^[A-ZÁÉÍÓÖŐÚÜŰ]*$/i,
pl: /^[A-ZĄĆĘŚŁŃÓŻŹ]*$/i,
pt: /^[A-ZÃÁÀÂÇÉÊÍÕÓÔÚÜ]*$/i,
ru: /^[А-ЯЁ]*$/i,
sk: /^[A-ZÁÄČĎÉÍĹĽŇÓŔŠŤÚÝŽ]*$/i,
sr: /^[A-ZČĆŽŠĐ]*$/i,
sv: /^[A-ZÅÄÖ]*$/i,
tr: /^[A-ZÇĞİıÖŞÜ]*$/i,
uk: /^[А-ЩЬЮЯЄІЇҐ]*$/i,
ar: /^[ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]*$/,
az: /^[A-ZÇƏĞİıÖŞÜ]*$/i
};
var alphaSpaces = {
en: /^[A-Z\s]*$/i,
cs: /^[A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ\s]*$/i,
da: /^[A-ZÆØÅ\s]*$/i,
de: /^[A-ZÄÖÜß\s]*$/i,
es: /^[A-ZÁÉÍÑÓÚÜ\s]*$/i,
fr: /^[A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ\s]*$/i,
it: /^[A-Z\xC0-\xFF\s]*$/i,
lt: /^[A-ZĄČĘĖĮŠŲŪŽ\s]*$/i,
nl: /^[A-ZÉËÏÓÖÜ\s]*$/i,
hu: /^[A-ZÁÉÍÓÖŐÚÜŰ\s]*$/i,
pl: /^[A-ZĄĆĘŚŁŃÓŻŹ\s]*$/i,
pt: /^[A-ZÃÁÀÂÇÉÊÍÕÓÔÚÜ\s]*$/i,
ru: /^[А-ЯЁ\s]*$/i,
sk: /^[A-ZÁÄČĎÉÍĹĽŇÓŔŠŤÚÝŽ\s]*$/i,
sr: /^[A-ZČĆŽŠĐ\s]*$/i,
sv: /^[A-ZÅÄÖ\s]*$/i,
tr: /^[A-ZÇĞİıÖŞÜ\s]*$/i,
uk: /^[А-ЩЬЮЯЄІЇҐ\s]*$/i,
ar: /^[ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ\s]*$/,
az: /^[A-ZÇƏĞİıÖŞÜ\s]*$/i
};
var alphanumeric = {
en: /^[0-9A-Z]*$/i,
cs: /^[0-9A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]*$/i,
da: /^[0-9A-ZÆØÅ]$/i,
de: /^[0-9A-ZÄÖÜß]*$/i,
es: /^[0-9A-ZÁÉÍÑÓÚÜ]*$/i,
fr: /^[0-9A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]*$/i,
it: /^[0-9A-Z\xC0-\xFF]*$/i,
lt: /^[0-9A-ZĄČĘĖĮŠŲŪŽ]*$/i,
hu: /^[0-9A-ZÁÉÍÓÖŐÚÜŰ]*$/i,
nl: /^[0-9A-ZÉËÏÓÖÜ]*$/i,
pl: /^[0-9A-ZĄĆĘŚŁŃÓŻŹ]*$/i,
pt: /^[0-9A-ZÃÁÀÂÇÉÊÍÕÓÔÚÜ]*$/i,
ru: /^[0-9А-ЯЁ]*$/i,
sk: /^[0-9A-ZÁÄČĎÉÍĹĽŇÓŔŠŤÚÝŽ]*$/i,
sr: /^[0-9A-ZČĆŽŠĐ]*$/i,
sv: /^[0-9A-ZÅÄÖ]*$/i,
tr: /^[0-9A-ZÇĞİıÖŞÜ]*$/i,
uk: /^[0-9А-ЩЬЮЯЄІЇҐ]*$/i,
ar: /^[٠١٢٣٤٥٦٧٨٩0-9ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]*$/,
az: /^[0-9A-ZÇƏĞİıÖŞÜ]*$/i
};
var alphaDash = {
en: /^[0-9A-Z_-]*$/i,
cs: /^[0-9A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ_-]*$/i,
da: /^[0-9A-ZÆØÅ_-]*$/i,
de: /^[0-9A-ZÄÖÜß_-]*$/i,
es: /^[0-9A-ZÁÉÍÑÓÚÜ_-]*$/i,
fr: /^[0-9A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ_-]*$/i,
it: /^[0-9A-Z\xC0-\xFF_-]*$/i,
lt: /^[0-9A-ZĄČĘĖĮŠŲŪŽ_-]*$/i,
nl: /^[0-9A-ZÉËÏÓÖÜ_-]*$/i,
hu: /^[0-9A-ZÁÉÍÓÖŐÚÜŰ_-]*$/i,
pl: /^[0-9A-ZĄĆĘŚŁŃÓŻŹ_-]*$/i,
pt: /^[0-9A-ZÃÁÀÂÇÉÊÍÕÓÔÚÜ_-]*$/i,
ru: /^[0-9А-ЯЁ_-]*$/i,
sk: /^[0-9A-ZÁÄČĎÉÍĹĽŇÓŔŠŤÚÝŽ_-]*$/i,
sr: /^[0-9A-ZČĆŽŠĐ_-]*$/i,
sv: /^[0-9A-ZÅÄÖ_-]*$/i,
tr: /^[0-9A-ZÇĞİıÖŞÜ_-]*$/i,
uk: /^[0-9А-ЩЬЮЯЄІЇҐ_-]*$/i,
ar: /^[٠١٢٣٤٥٦٧٨٩0-9ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ_-]*$/,
az: /^[0-9A-ZÇƏĞİıÖŞÜ_-]*$/i
};
var validate = function (value, _a) {
var _b = (_a === void 0 ? {} : _a).locale, locale = _b === void 0 ? '' : _b;
if (Array.isArray(value)) {
return value.every(function (val) { return validate(val, { locale: locale }); });
}
// Match at least one locale.
if (!locale) {
return Object.keys(alpha).some(function (loc) { return alpha[loc].test(value); });
}
return (alpha[locale] || alpha.en).test(value);
};
var params = [
{
name: 'locale'
}
];
var alpha$1 = {
validate: validate,
params: params
};
var validate$1 = function (value, _a) {
var _b = (_a === void 0 ? {} : _a).locale, locale = _b === void 0 ? '' : _b;
if (Array.isArray(value)) {
return value.every(function (val) { return validate$1(val, { locale: locale }); });
}
// Match at least one locale.
if (!locale) {
return Object.keys(alphaDash).some(function (loc) { return alphaDash[loc].test(value); });
}
return (alphaDash[locale] || alphaDash.en).test(value);
};
var params$1 = [
{
name: 'locale'
}
];
var alpha_dash = {
validate: validate$1,
params: params$1
};
var validate$2 = function (value, _a) {
var _b = (_a === void 0 ? {} : _a).locale, locale = _b === void 0 ? '' : _b;
if (Array.isArray(value)) {
return value.every(function (val) { return validate$2(val, { locale: locale }); });
}
// Match at least one locale.
if (!locale) {
return Object.keys(alphanumeric).some(function (loc) { return alphanumeric[loc].test(value); });
}
return (alphanumeric[locale] || alphanumeric.en).test(value);
};
var params$2 = [
{
name: 'locale'
}
];
var alpha_num = {
validate: validate$2,
params: params$2
};
var validate$3 = function (value, _a) {
var _b = (_a === void 0 ? {} : _a).locale, locale = _b === void 0 ? '' : _b;
if (Array.isArray(value)) {
return value.every(function (val) { return validate$3(val, { locale: locale }); });
}
// Match at least one locale.
if (!locale) {
return Object.keys(alphaSpaces).some(function (loc) { return alphaSpaces[loc].test(value); });
}
return (alphaSpaces[locale] || alphaSpaces.en).test(value);
};
var params$3 = [
{
name: 'locale'
}
];
var alpha_spaces = {
validate: validate$3,
params: params$3
};
var validate$4 = function (value, _a) {
var _b = _a === void 0 ? {} : _a, min = _b.min, max = _b.max;
if (Array.isArray(value)) {
return value.every(function (val) { return !!validate$4(val, { min: min, max: max }); });
}
return Number(min) <= value && Number(max) >= value;
};
var params$4 = [
{
name: 'min'
},
{
name: 'max'
}
];
var between = {
validate: validate$4,
params: params$4
};
var validate$5 = function (value, _a) {
var target = _a.target;
return String(value) === String(target);
};
var params$5 = [
{
name: 'target',
isTarget: true
}
];
var confirmed = {
validate: validate$5,
params: params$5
};
var validate$6 = function (value, _a) {
var length = _a.length;
if (Array.isArray(value)) {
return value.every(function (val) { return validate$6(val, { length: length }); });
}
var strVal = String(value);
return /^[0-9]*$/.test(strVal) && strVal.length === length;
};
var params$6 = [
{
name: 'length',
cast: function (value) {
return Number(value);
}
}
];
var digits = {
validate: validate$6,
params: params$6
};
var validateImage = function (file, width, height) {
var URL = window.URL || window.webkitURL;
return new Promise(function (resolve) {
var image = new Image();
image.onerror = function () { return resolve(false); };
image.onload = function () { return resolve(image.width === width && image.height === height); };
image.src = URL.createObjectURL(file);
});
};
var validate$7 = function (files, _a) {
var width = _a.width, height = _a.height;
var list = [];
files = Array.isArray(files) ? files : [files];
for (var i = 0; i < files.length; i++) {
// if file is not an image, reject.
if (!/\.(jpg|svg|jpeg|png|bmp|gif)$/i.test(files[i].name)) {
return Promise.resolve(false);
}
list.push(files[i]);
}
return Promise.all(list.map(function (file) { return validateImage(file, width, height); })).then(function (values) {
return values.every(function (v) { return v; });
});
};
var params$7 = [
{
name: 'width',
cast: function (value) {
return Number(value);
}
},
{
name: 'height',
cast: function (value) {
return Number(value);
}
}
];
var dimensions = {
validate: validate$7,
params: params$7
};
var validate$8 = function (value, _a) {
var multiple = (_a === void 0 ? {} : _a).multiple;
// eslint-disable-next-line
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (multiple && !Array.isArray(value)) {
value = String(value)
.split(',')
.map(function (emailStr) { return emailStr.trim(); });
}
if (Array.isArray(value)) {
return value.every(function (val) { return re.test(String(val)); });
}
return re.test(String(value));
};
var params$8 = [
{
name: 'multiple',
default: false
}
];
var email = {
validate: validate$8,
params: params$8
};
function isNullOrUndefined(value) {
return value === null || value === undefined;
}
function isEmptyArray(arr) {
return Array.isArray(arr) && arr.length === 0;
}
function isCallable(fn) {
return typeof fn === 'function';
}
function includes(collection, item) {
return collection.indexOf(item) !== -1;
}
/**
* Converts an array-like object to array, provides a simple polyfill for Array.from
*/
function toArray(arrayLike) {
if (isCallable(Array.from)) {
return Array.from(arrayLike);
}
/* istanbul ignore next */
return _copyArray(arrayLike);
}
/* istanbul ignore next */
function _copyArray(arrayLike) {
var array = [];
var length = arrayLike.length;
for (var i = 0; i < length; i++) {
array.push(arrayLike[i]);
}
return array;
}
var validate$9 = function (value, options) {
if (Array.isArray(value)) {
return value.every(function (val) { return validate$9(val, options); });
}
return toArray(options).some(function (item) {
// eslint-disable-next-line
return item == value;
});
};
var oneOf = {
validate: validate$9
};
var validate$a = function (value, args) {
return !validate$9(value, args);
};
var excluded = {
validate: validate$a
};
var validate$b = function (files, extensions) {
var regex = new RegExp(".(" + extensions.join('|') + ")$", 'i');
if (Array.isArray(files)) {
return files.every(function (file) { return regex.test(file.name); });
}
return regex.test(files.name);
};
var ext = {
validate: validate$b
};
var validate$c = function (files) {
var regex = /\.(jpg|svg|jpeg|png|bmp|gif)$/i;
if (Array.isArray(files)) {
return files.every(function (file) { return regex.test(file.name); });
}
return regex.test(files.name);
};
var image = {
validate: validate$c
};
var validate$d = function (value) {
if (Array.isArray(value)) {
return value.every(function (val) { return /^-?[0-9]+$/.test(String(val)); });
}
return /^-?[0-9]+$/.test(String(value));
};
var integer = {
validate: validate$d
};
var validate$e = function (value, _a) {
var other = _a.other;
return value === other;
};
var params$9 = [
{
name: 'other'
}
];
var is = {
validate: validate$e,
params: params$9
};
var validate$f = function (value, _a) {
var other = _a.other;
return value !== other;
};
var params$a = [
{
name: 'other'
}
];
var is_not = {
validate: validate$f,
params: params$a
};
var validate$g = function (value, _a) {
var length = _a.length;
if (isNullOrUndefined(value)) {
return false;
}
if (typeof value === 'number') {
value = String(value);
}
if (!value.length) {
value = toArray(value);
}
return value.length === length;
};
var params$b = [
{
name: 'length',
cast: function (value) { return Number(value); }
}
];
var length = {
validate: validate$g,
params: params$b
};
var validate$h = function (value, _a) {
var length = _a.length;
if (isNullOrUndefined(value)) {
return length >= 0;
}
if (Array.isArray(value)) {
return value.every(function (val) { return validate$h(val, { length: length }); });
}
return String(value).length <= length;
};
var params$c = [
{
name: 'length',
cast: function (value) {
return Number(value);
}
}
];
var max = {
validate: validate$h,
params: params$c
};
var validate$i = function (value, _a) {
var max = _a.max;
if (isNullOrUndefined(value) || value === '') {
return false;
}
if (Array.isArray(value)) {
return value.length > 0 && value.every(function (val) { return validate$i(val, { max: max }); });
}
return Number(value) <= max;
};
var params$d = [
{
name: 'max',
cast: function (value) {
return Number(value);
}
}
];
var max_value = {
validate: validate$i,
params: params$d
};
var validate$j = function (files, mimes) {
var regex = new RegExp(mimes.join('|').replace('*', '.+') + "$", 'i');
if (Array.isArray(files)) {
return files.every(function (file) { return regex.test(file.type); });
}
return regex.test(files.type);
};
var mimes = {
validate: validate$j
};
var validate$k = function (value, _a) {
var length = _a.length;
if (isNullOrUndefined(value)) {
return false;
}
if (Array.isArray(value)) {
return value.every(function (val) { return validate$k(val, { length: length }); });
}
return String(value).length >= length;
};
var params$e = [
{
name: 'length',
cast: function (value) {
return Number(value);
}
}
];
var min = {
validate: validate$k,
params: params$e
};
var validate$l = function (value, _a) {
var min = _a.min;
if (isNullOrUndefined(value) || value === '') {
return false;
}
if (Array.isArray(value)) {
return value.length > 0 && value.every(function (val) { return validate$l(val, { min: min }); });
}
return Number(value) >= min;
};
var params$f = [
{
name: 'min',
cast: function (value) {
return Number(value);
}
}
];
var min_value = {
validate: validate$l,
params: params$f
};
var ar = /^[٠١٢٣٤٥٦٧٨٩]+$/;
var en = /^[0-9]+$/;
var validate$m = function (value) {
var testValue = function (val) {
var strValue = String(val);
return en.test(strValue) || ar.test(strValue);
};
if (Array.isArray(value)) {
return value.every(testValue);
}
return testValue(value);
};
var numeric = {
validate: validate$m
};
var validate$n = function (value, _a) {
var regex = _a.regex;
if (Array.isArray(value)) {
return value.every(function (val) { return validate$n(val, { regex: regex }); });
}
return regex.test(String(value));
};
var params$g = [
{
name: 'regex',
cast: function (value) {
if (typeof value === 'string') {
return new RegExp(value);
}
return value;
}
}
];
var regex = {
validate: validate$n,
params: params$g
};
var validate$o = function (value, _a) {
var allowFalse = (_a === void 0 ? { allowFalse: true } : _a).allowFalse;
var result = {
valid: false,
required: true
};
if (isNullOrUndefined(value) || isEmptyArray(value)) {
return result;
}
// incase a field considers `false` as an empty value like checkboxes.
if (value === false && !allowFalse) {
return result;
}
result.valid = !!String(value).trim().length;
return result;
};
var computesRequired = true;
var params$h = [
{
name: 'allowFalse',
default: true
}
];
var required = {
validate: validate$o,
params: params$h,
computesRequired: computesRequired
};
var testEmpty = function (value) {
return isEmptyArray(value) || includes([false, null, undefined], value) || !String(value).trim().length;
};
var validate$p = function (value, _a) {
var target = _a.target, values = _a.values;
var required;
if (values && values.length) {
if (!Array.isArray(values) && typeof values === 'string') {
values = [values];
}
// eslint-disable-next-line
required = values.some(function (val) { return val == String(target).trim(); });
}
else {
required = !testEmpty(target);
}
if (!required) {
return {
valid: true,
required: required
};
}
return {
valid: !testEmpty(value),
required: required
};
};
var params$i = [
{
name: 'target',
isTarget: true
},
{
name: 'values'
}
];
var computesRequired$1 = true;
var required_if = {
validate: validate$p,
params: params$i,
computesRequired: computesRequired$1
};
var validate$q = function (files, _a) {
var size = _a.size;
if (isNaN(size)) {
return false;
}
var nSize = size * 1024;
if (!Array.isArray(files)) {
return files.size <= nSize;
}
for (var i = 0; i < files.length; i++) {
if (files[i].size > nSize) {
return false;
}
}
return true;
};
var params$j = [
{
name: 'size',
cast: function (value) {
return Number(value);
}
}
];
var size = {
validate: validate$q,
params: params$j
};
export { alpha$1 as alpha, alpha_dash, alpha_num, alpha_spaces, between, confirmed, digits, dimensions, email, excluded, ext, image, integer, is, is_not, length, max, max_value, mimes, min, min_value, numeric, oneOf, regex, required, required_if, size };
|
/*!
* chartjs-plugin-datalabels v2.0.0
* https://chartjs-plugin-datalabels.netlify.app
* (c) 2017-2021 chartjs-plugin-datalabels contributors
* Released under the MIT license
*/
import { isNullOrUndef, merge, toFont, resolve, toPadding, valueOrDefault, callback, isObject, each } from 'chart.js/helpers';
import { defaults as defaults$1, ArcElement, PointElement, BarElement } from 'chart.js';
var devicePixelRatio = (function() {
if (typeof window !== 'undefined') {
if (window.devicePixelRatio) {
return window.devicePixelRatio;
}
// devicePixelRatio is undefined on IE10
// https://stackoverflow.com/a/20204180/8837887
// https://github.com/chartjs/chartjs-plugin-datalabels/issues/85
var screen = window.screen;
if (screen) {
return (screen.deviceXDPI || 1) / (screen.logicalXDPI || 1);
}
}
return 1;
}());
var utils = {
// @todo move this in Chart.helpers.toTextLines
toTextLines: function(inputs) {
var lines = [];
var input;
inputs = [].concat(inputs);
while (inputs.length) {
input = inputs.pop();
if (typeof input === 'string') {
lines.unshift.apply(lines, input.split('\n'));
} else if (Array.isArray(input)) {
inputs.push.apply(inputs, input);
} else if (!isNullOrUndef(inputs)) {
lines.unshift('' + input);
}
}
return lines;
},
// @todo move this in Chart.helpers.canvas.textSize
// @todo cache calls of measureText if font doesn't change?!
textSize: function(ctx, lines, font) {
var items = [].concat(lines);
var ilen = items.length;
var prev = ctx.font;
var width = 0;
var i;
ctx.font = font.string;
for (i = 0; i < ilen; ++i) {
width = Math.max(ctx.measureText(items[i]).width, width);
}
ctx.font = prev;
return {
height: ilen * font.lineHeight,
width: width
};
},
/**
* Returns value bounded by min and max. This is equivalent to max(min, min(value, max)).
* @todo move this method in Chart.helpers.bound
* https://doc.qt.io/qt-5/qtglobal.html#qBound
*/
bound: function(min, value, max) {
return Math.max(min, Math.min(value, max));
},
/**
* Returns an array of pair [value, state] where state is:
* * -1: value is only in a0 (removed)
* * 1: value is only in a1 (added)
*/
arrayDiff: function(a0, a1) {
var prev = a0.slice();
var updates = [];
var i, j, ilen, v;
for (i = 0, ilen = a1.length; i < ilen; ++i) {
v = a1[i];
j = prev.indexOf(v);
if (j === -1) {
updates.push([v, 1]);
} else {
prev.splice(j, 1);
}
}
for (i = 0, ilen = prev.length; i < ilen; ++i) {
updates.push([prev[i], -1]);
}
return updates;
},
/**
* https://github.com/chartjs/chartjs-plugin-datalabels/issues/70
*/
rasterize: function(v) {
return Math.round(v * devicePixelRatio) / devicePixelRatio;
}
};
function orient(point, origin) {
var x0 = origin.x;
var y0 = origin.y;
if (x0 === null) {
return {x: 0, y: -1};
}
if (y0 === null) {
return {x: 1, y: 0};
}
var dx = point.x - x0;
var dy = point.y - y0;
var ln = Math.sqrt(dx * dx + dy * dy);
return {
x: ln ? dx / ln : 0,
y: ln ? dy / ln : -1
};
}
function aligned(x, y, vx, vy, align) {
switch (align) {
case 'center':
vx = vy = 0;
break;
case 'bottom':
vx = 0;
vy = 1;
break;
case 'right':
vx = 1;
vy = 0;
break;
case 'left':
vx = -1;
vy = 0;
break;
case 'top':
vx = 0;
vy = -1;
break;
case 'start':
vx = -vx;
vy = -vy;
break;
case 'end':
// keep natural orientation
break;
default:
// clockwise rotation (in degree)
align *= (Math.PI / 180);
vx = Math.cos(align);
vy = Math.sin(align);
break;
}
return {
x: x,
y: y,
vx: vx,
vy: vy
};
}
// Line clipping (Cohen–Sutherland algorithm)
// https://en.wikipedia.org/wiki/Cohen–Sutherland_algorithm
var R_INSIDE = 0;
var R_LEFT = 1;
var R_RIGHT = 2;
var R_BOTTOM = 4;
var R_TOP = 8;
function region(x, y, rect) {
var res = R_INSIDE;
if (x < rect.left) {
res |= R_LEFT;
} else if (x > rect.right) {
res |= R_RIGHT;
}
if (y < rect.top) {
res |= R_TOP;
} else if (y > rect.bottom) {
res |= R_BOTTOM;
}
return res;
}
function clipped(segment, area) {
var x0 = segment.x0;
var y0 = segment.y0;
var x1 = segment.x1;
var y1 = segment.y1;
var r0 = region(x0, y0, area);
var r1 = region(x1, y1, area);
var r, x, y;
// eslint-disable-next-line no-constant-condition
while (true) {
if (!(r0 | r1) || (r0 & r1)) {
// both points inside or on the same side: no clipping
break;
}
// at least one point is outside
r = r0 || r1;
if (r & R_TOP) {
x = x0 + (x1 - x0) * (area.top - y0) / (y1 - y0);
y = area.top;
} else if (r & R_BOTTOM) {
x = x0 + (x1 - x0) * (area.bottom - y0) / (y1 - y0);
y = area.bottom;
} else if (r & R_RIGHT) {
y = y0 + (y1 - y0) * (area.right - x0) / (x1 - x0);
x = area.right;
} else if (r & R_LEFT) {
y = y0 + (y1 - y0) * (area.left - x0) / (x1 - x0);
x = area.left;
}
if (r === r0) {
x0 = x;
y0 = y;
r0 = region(x0, y0, area);
} else {
x1 = x;
y1 = y;
r1 = region(x1, y1, area);
}
}
return {
x0: x0,
x1: x1,
y0: y0,
y1: y1
};
}
function compute$1(range, config) {
var anchor = config.anchor;
var segment = range;
var x, y;
if (config.clamp) {
segment = clipped(segment, config.area);
}
if (anchor === 'start') {
x = segment.x0;
y = segment.y0;
} else if (anchor === 'end') {
x = segment.x1;
y = segment.y1;
} else {
x = (segment.x0 + segment.x1) / 2;
y = (segment.y0 + segment.y1) / 2;
}
return aligned(x, y, range.vx, range.vy, config.align);
}
var positioners = {
arc: function(el, config) {
var angle = (el.startAngle + el.endAngle) / 2;
var vx = Math.cos(angle);
var vy = Math.sin(angle);
var r0 = el.innerRadius;
var r1 = el.outerRadius;
return compute$1({
x0: el.x + vx * r0,
y0: el.y + vy * r0,
x1: el.x + vx * r1,
y1: el.y + vy * r1,
vx: vx,
vy: vy
}, config);
},
point: function(el, config) {
var v = orient(el, config.origin);
var rx = v.x * el.options.radius;
var ry = v.y * el.options.radius;
return compute$1({
x0: el.x - rx,
y0: el.y - ry,
x1: el.x + rx,
y1: el.y + ry,
vx: v.x,
vy: v.y
}, config);
},
bar: function(el, config) {
var v = orient(el, config.origin);
var x = el.x;
var y = el.y;
var sx = 0;
var sy = 0;
if (el.horizontal) {
x = Math.min(el.x, el.base);
sx = Math.abs(el.base - el.x);
} else {
y = Math.min(el.y, el.base);
sy = Math.abs(el.base - el.y);
}
return compute$1({
x0: x,
y0: y + sy,
x1: x + sx,
y1: y,
vx: v.x,
vy: v.y
}, config);
},
fallback: function(el, config) {
var v = orient(el, config.origin);
return compute$1({
x0: el.x,
y0: el.y,
x1: el.x,
y1: el.y,
vx: v.x,
vy: v.y
}, config);
}
};
var rasterize = utils.rasterize;
function boundingRects(model) {
var borderWidth = model.borderWidth || 0;
var padding = model.padding;
var th = model.size.height;
var tw = model.size.width;
var tx = -tw / 2;
var ty = -th / 2;
return {
frame: {
x: tx - padding.left - borderWidth,
y: ty - padding.top - borderWidth,
w: tw + padding.width + borderWidth * 2,
h: th + padding.height + borderWidth * 2
},
text: {
x: tx,
y: ty,
w: tw,
h: th
}
};
}
function getScaleOrigin(el, context) {
var scale = context.chart.getDatasetMeta(context.datasetIndex).vScale;
if (!scale) {
return null;
}
if (scale.xCenter !== undefined && scale.yCenter !== undefined) {
return {x: scale.xCenter, y: scale.yCenter};
}
var pixel = scale.getBasePixel();
return el.horizontal ?
{x: pixel, y: null} :
{x: null, y: pixel};
}
function getPositioner(el) {
if (el instanceof ArcElement) {
return positioners.arc;
}
if (el instanceof PointElement) {
return positioners.point;
}
if (el instanceof BarElement) {
return positioners.bar;
}
return positioners.fallback;
}
function drawRoundedRect(ctx, x, y, w, h, radius) {
var HALF_PI = Math.PI / 2;
if (radius) {
var r = Math.min(radius, h / 2, w / 2);
var left = x + r;
var top = y + r;
var right = x + w - r;
var bottom = y + h - r;
ctx.moveTo(x, top);
if (left < right && top < bottom) {
ctx.arc(left, top, r, -Math.PI, -HALF_PI);
ctx.arc(right, top, r, -HALF_PI, 0);
ctx.arc(right, bottom, r, 0, HALF_PI);
ctx.arc(left, bottom, r, HALF_PI, Math.PI);
} else if (left < right) {
ctx.moveTo(left, y);
ctx.arc(right, top, r, -HALF_PI, HALF_PI);
ctx.arc(left, top, r, HALF_PI, Math.PI + HALF_PI);
} else if (top < bottom) {
ctx.arc(left, top, r, -Math.PI, 0);
ctx.arc(left, bottom, r, 0, Math.PI);
} else {
ctx.arc(left, top, r, -Math.PI, Math.PI);
}
ctx.closePath();
ctx.moveTo(x, y);
} else {
ctx.rect(x, y, w, h);
}
}
function drawFrame(ctx, rect, model) {
var bgColor = model.backgroundColor;
var borderColor = model.borderColor;
var borderWidth = model.borderWidth;
if (!bgColor && (!borderColor || !borderWidth)) {
return;
}
ctx.beginPath();
drawRoundedRect(
ctx,
rasterize(rect.x) + borderWidth / 2,
rasterize(rect.y) + borderWidth / 2,
rasterize(rect.w) - borderWidth,
rasterize(rect.h) - borderWidth,
model.borderRadius);
ctx.closePath();
if (bgColor) {
ctx.fillStyle = bgColor;
ctx.fill();
}
if (borderColor && borderWidth) {
ctx.strokeStyle = borderColor;
ctx.lineWidth = borderWidth;
ctx.lineJoin = 'miter';
ctx.stroke();
}
}
function textGeometry(rect, align, font) {
var h = font.lineHeight;
var w = rect.w;
var x = rect.x;
var y = rect.y + h / 2;
if (align === 'center') {
x += w / 2;
} else if (align === 'end' || align === 'right') {
x += w;
}
return {
h: h,
w: w,
x: x,
y: y
};
}
function drawTextLine(ctx, text, cfg) {
var shadow = ctx.shadowBlur;
var stroked = cfg.stroked;
var x = rasterize(cfg.x);
var y = rasterize(cfg.y);
var w = rasterize(cfg.w);
if (stroked) {
ctx.strokeText(text, x, y, w);
}
if (cfg.filled) {
if (shadow && stroked) {
// Prevent drawing shadow on both the text stroke and fill, so
// if the text is stroked, remove the shadow for the text fill.
ctx.shadowBlur = 0;
}
ctx.fillText(text, x, y, w);
if (shadow && stroked) {
ctx.shadowBlur = shadow;
}
}
}
function drawText(ctx, lines, rect, model) {
var align = model.textAlign;
var color = model.color;
var filled = !!color;
var font = model.font;
var ilen = lines.length;
var strokeColor = model.textStrokeColor;
var strokeWidth = model.textStrokeWidth;
var stroked = strokeColor && strokeWidth;
var i;
if (!ilen || (!filled && !stroked)) {
return;
}
// Adjust coordinates based on text alignment and line height
rect = textGeometry(rect, align, font);
ctx.font = font.string;
ctx.textAlign = align;
ctx.textBaseline = 'middle';
ctx.shadowBlur = model.textShadowBlur;
ctx.shadowColor = model.textShadowColor;
if (filled) {
ctx.fillStyle = color;
}
if (stroked) {
ctx.lineJoin = 'round';
ctx.lineWidth = strokeWidth;
ctx.strokeStyle = strokeColor;
}
for (i = 0, ilen = lines.length; i < ilen; ++i) {
drawTextLine(ctx, lines[i], {
stroked: stroked,
filled: filled,
w: rect.w,
x: rect.x,
y: rect.y + rect.h * i
});
}
}
var Label = function(config, ctx, el, index) {
var me = this;
me._config = config;
me._index = index;
me._model = null;
me._rects = null;
me._ctx = ctx;
me._el = el;
};
merge(Label.prototype, {
/**
* @private
*/
_modelize: function(display, lines, config, context) {
var me = this;
var index = me._index;
var font = toFont(resolve([config.font, {}], context, index));
var color = resolve([config.color, defaults$1.color], context, index);
return {
align: resolve([config.align, 'center'], context, index),
anchor: resolve([config.anchor, 'center'], context, index),
area: context.chart.chartArea,
backgroundColor: resolve([config.backgroundColor, null], context, index),
borderColor: resolve([config.borderColor, null], context, index),
borderRadius: resolve([config.borderRadius, 0], context, index),
borderWidth: resolve([config.borderWidth, 0], context, index),
clamp: resolve([config.clamp, false], context, index),
clip: resolve([config.clip, false], context, index),
color: color,
display: display,
font: font,
lines: lines,
offset: resolve([config.offset, 0], context, index),
opacity: resolve([config.opacity, 1], context, index),
origin: getScaleOrigin(me._el, context),
padding: toPadding(resolve([config.padding, 0], context, index)),
positioner: getPositioner(me._el),
rotation: resolve([config.rotation, 0], context, index) * (Math.PI / 180),
size: utils.textSize(me._ctx, lines, font),
textAlign: resolve([config.textAlign, 'start'], context, index),
textShadowBlur: resolve([config.textShadowBlur, 0], context, index),
textShadowColor: resolve([config.textShadowColor, color], context, index),
textStrokeColor: resolve([config.textStrokeColor, color], context, index),
textStrokeWidth: resolve([config.textStrokeWidth, 0], context, index)
};
},
update: function(context) {
var me = this;
var model = null;
var rects = null;
var index = me._index;
var config = me._config;
var value, label, lines;
// We first resolve the display option (separately) to avoid computing
// other options in case the label is hidden (i.e. display: false).
var display = resolve([config.display, true], context, index);
if (display) {
value = context.dataset.data[index];
label = valueOrDefault(callback(config.formatter, [value, context]), value);
lines = isNullOrUndef(label) ? [] : utils.toTextLines(label);
if (lines.length) {
model = me._modelize(display, lines, config, context);
rects = boundingRects(model);
}
}
me._model = model;
me._rects = rects;
},
geometry: function() {
return this._rects ? this._rects.frame : {};
},
rotation: function() {
return this._model ? this._model.rotation : 0;
},
visible: function() {
return this._model && this._model.opacity;
},
model: function() {
return this._model;
},
draw: function(chart, center) {
var me = this;
var ctx = chart.ctx;
var model = me._model;
var rects = me._rects;
var area;
if (!this.visible()) {
return;
}
ctx.save();
if (model.clip) {
area = model.area;
ctx.beginPath();
ctx.rect(
area.left,
area.top,
area.right - area.left,
area.bottom - area.top);
ctx.clip();
}
ctx.globalAlpha = utils.bound(0, model.opacity, 1);
ctx.translate(rasterize(center.x), rasterize(center.y));
ctx.rotate(model.rotation);
drawFrame(ctx, rects.frame, model);
drawText(ctx, model.lines, rects.text, model);
ctx.restore();
}
});
var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991; // eslint-disable-line es/no-number-minsafeinteger
var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; // eslint-disable-line es/no-number-maxsafeinteger
function rotated(point, center, angle) {
var cos = Math.cos(angle);
var sin = Math.sin(angle);
var cx = center.x;
var cy = center.y;
return {
x: cx + cos * (point.x - cx) - sin * (point.y - cy),
y: cy + sin * (point.x - cx) + cos * (point.y - cy)
};
}
function projected(points, axis) {
var min = MAX_INTEGER;
var max = MIN_INTEGER;
var origin = axis.origin;
var i, pt, vx, vy, dp;
for (i = 0; i < points.length; ++i) {
pt = points[i];
vx = pt.x - origin.x;
vy = pt.y - origin.y;
dp = axis.vx * vx + axis.vy * vy;
min = Math.min(min, dp);
max = Math.max(max, dp);
}
return {
min: min,
max: max
};
}
function toAxis(p0, p1) {
var vx = p1.x - p0.x;
var vy = p1.y - p0.y;
var ln = Math.sqrt(vx * vx + vy * vy);
return {
vx: (p1.x - p0.x) / ln,
vy: (p1.y - p0.y) / ln,
origin: p0,
ln: ln
};
}
var HitBox = function() {
this._rotation = 0;
this._rect = {
x: 0,
y: 0,
w: 0,
h: 0
};
};
merge(HitBox.prototype, {
center: function() {
var r = this._rect;
return {
x: r.x + r.w / 2,
y: r.y + r.h / 2
};
},
update: function(center, rect, rotation) {
this._rotation = rotation;
this._rect = {
x: rect.x + center.x,
y: rect.y + center.y,
w: rect.w,
h: rect.h
};
},
contains: function(point) {
var me = this;
var margin = 1;
var rect = me._rect;
point = rotated(point, me.center(), -me._rotation);
return !(point.x < rect.x - margin
|| point.y < rect.y - margin
|| point.x > rect.x + rect.w + margin * 2
|| point.y > rect.y + rect.h + margin * 2);
},
// Separating Axis Theorem
// https://gamedevelopment.tutsplus.com/tutorials/collision-detection-using-the-separating-axis-theorem--gamedev-169
intersects: function(other) {
var r0 = this._points();
var r1 = other._points();
var axes = [
toAxis(r0[0], r0[1]),
toAxis(r0[0], r0[3])
];
var i, pr0, pr1;
if (this._rotation !== other._rotation) {
// Only separate with r1 axis if the rotation is different,
// else it's enough to separate r0 and r1 with r0 axis only!
axes.push(
toAxis(r1[0], r1[1]),
toAxis(r1[0], r1[3])
);
}
for (i = 0; i < axes.length; ++i) {
pr0 = projected(r0, axes[i]);
pr1 = projected(r1, axes[i]);
if (pr0.max < pr1.min || pr1.max < pr0.min) {
return false;
}
}
return true;
},
/**
* @private
*/
_points: function() {
var me = this;
var rect = me._rect;
var angle = me._rotation;
var center = me.center();
return [
rotated({x: rect.x, y: rect.y}, center, angle),
rotated({x: rect.x + rect.w, y: rect.y}, center, angle),
rotated({x: rect.x + rect.w, y: rect.y + rect.h}, center, angle),
rotated({x: rect.x, y: rect.y + rect.h}, center, angle)
];
}
});
function coordinates(el, model, geometry) {
var point = model.positioner(el, model);
var vx = point.vx;
var vy = point.vy;
if (!vx && !vy) {
// if aligned center, we don't want to offset the center point
return {x: point.x, y: point.y};
}
var w = geometry.w;
var h = geometry.h;
// take in account the label rotation
var rotation = model.rotation;
var dx = Math.abs(w / 2 * Math.cos(rotation)) + Math.abs(h / 2 * Math.sin(rotation));
var dy = Math.abs(w / 2 * Math.sin(rotation)) + Math.abs(h / 2 * Math.cos(rotation));
// scale the unit vector (vx, vy) to get at least dx or dy equal to
// w or h respectively (else we would calculate the distance to the
// ellipse inscribed in the bounding rect)
var vs = 1 / Math.max(Math.abs(vx), Math.abs(vy));
dx *= vx * vs;
dy *= vy * vs;
// finally, include the explicit offset
dx += model.offset * vx;
dy += model.offset * vy;
return {
x: point.x + dx,
y: point.y + dy
};
}
function collide(labels, collider) {
var i, j, s0, s1;
// IMPORTANT Iterate in the reverse order since items at the end of the
// list have an higher weight/priority and thus should be less impacted
// by the overlapping strategy.
for (i = labels.length - 1; i >= 0; --i) {
s0 = labels[i].$layout;
for (j = i - 1; j >= 0 && s0._visible; --j) {
s1 = labels[j].$layout;
if (s1._visible && s0._box.intersects(s1._box)) {
collider(s0, s1);
}
}
}
return labels;
}
function compute(labels) {
var i, ilen, label, state, geometry, center, proxy;
// Initialize labels for overlap detection
for (i = 0, ilen = labels.length; i < ilen; ++i) {
label = labels[i];
state = label.$layout;
if (state._visible) {
// Chart.js 3 removed el._model in favor of getProps(), making harder to
// abstract reading values in positioners. Also, using string arrays to
// read values (i.e. var {a,b,c} = el.getProps(["a","b","c"])) would make
// positioners inefficient in the normal case (i.e. not the final values)
// and the code a bit ugly, so let's use a Proxy instead.
proxy = new Proxy(label._el, {get: (el, p) => el.getProps([p], true)[p]});
geometry = label.geometry();
center = coordinates(proxy, label.model(), geometry);
state._box.update(center, geometry, label.rotation());
}
}
// Auto hide overlapping labels
return collide(labels, function(s0, s1) {
var h0 = s0._hidable;
var h1 = s1._hidable;
if ((h0 && h1) || h1) {
s1._visible = false;
} else if (h0) {
s0._visible = false;
}
});
}
var layout = {
prepare: function(datasets) {
var labels = [];
var i, j, ilen, jlen, label;
for (i = 0, ilen = datasets.length; i < ilen; ++i) {
for (j = 0, jlen = datasets[i].length; j < jlen; ++j) {
label = datasets[i][j];
labels.push(label);
label.$layout = {
_box: new HitBox(),
_hidable: false,
_visible: true,
_set: i,
_idx: j
};
}
}
// TODO New `z` option: labels with a higher z-index are drawn
// of top of the ones with a lower index. Lowest z-index labels
// are also discarded first when hiding overlapping labels.
labels.sort(function(a, b) {
var sa = a.$layout;
var sb = b.$layout;
return sa._idx === sb._idx
? sb._set - sa._set
: sb._idx - sa._idx;
});
this.update(labels);
return labels;
},
update: function(labels) {
var dirty = false;
var i, ilen, label, model, state;
for (i = 0, ilen = labels.length; i < ilen; ++i) {
label = labels[i];
model = label.model();
state = label.$layout;
state._hidable = model && model.display === 'auto';
state._visible = label.visible();
dirty |= state._hidable;
}
if (dirty) {
compute(labels);
}
},
lookup: function(labels, point) {
var i, state;
// IMPORTANT Iterate in the reverse order since items at the end of
// the list have an higher z-index, thus should be picked first.
for (i = labels.length - 1; i >= 0; --i) {
state = labels[i].$layout;
if (state && state._visible && state._box.contains(point)) {
return labels[i];
}
}
return null;
},
draw: function(chart, labels) {
var i, ilen, label, state, geometry, center;
for (i = 0, ilen = labels.length; i < ilen; ++i) {
label = labels[i];
state = label.$layout;
if (state._visible) {
geometry = label.geometry();
center = coordinates(label._el, label.model(), geometry);
state._box.update(center, geometry, label.rotation());
label.draw(chart, center);
}
}
}
};
var formatter = function(value) {
if (isNullOrUndef(value)) {
return null;
}
var label = value;
var keys, klen, k;
if (isObject(value)) {
if (!isNullOrUndef(value.label)) {
label = value.label;
} else if (!isNullOrUndef(value.r)) {
label = value.r;
} else {
label = '';
keys = Object.keys(value);
for (k = 0, klen = keys.length; k < klen; ++k) {
label += (k !== 0 ? ', ' : '') + keys[k] + ': ' + value[keys[k]];
}
}
}
return '' + label;
};
/**
* IMPORTANT: make sure to also update tests and TypeScript definition
* files (`/test/specs/defaults.spec.js` and `/types/options.d.ts`)
*/
var defaults = {
align: 'center',
anchor: 'center',
backgroundColor: null,
borderColor: null,
borderRadius: 0,
borderWidth: 0,
clamp: false,
clip: false,
color: undefined,
display: true,
font: {
family: undefined,
lineHeight: 1.2,
size: undefined,
style: undefined,
weight: null
},
formatter: formatter,
labels: undefined,
listeners: {},
offset: 4,
opacity: 1,
padding: {
top: 4,
right: 4,
bottom: 4,
left: 4
},
rotation: 0,
textAlign: 'start',
textStrokeColor: undefined,
textStrokeWidth: 0,
textShadowBlur: 0,
textShadowColor: undefined
};
/**
* @see https://github.com/chartjs/Chart.js/issues/4176
*/
var EXPANDO_KEY = '$datalabels';
var DEFAULT_KEY = '$default';
function configure(dataset, options) {
var override = dataset.datalabels;
var listeners = {};
var configs = [];
var labels, keys;
if (override === false) {
return null;
}
if (override === true) {
override = {};
}
options = merge({}, [options, override]);
labels = options.labels || {};
keys = Object.keys(labels);
delete options.labels;
if (keys.length) {
keys.forEach(function(key) {
if (labels[key]) {
configs.push(merge({}, [
options,
labels[key],
{_key: key}
]));
}
});
} else {
// Default label if no "named" label defined.
configs.push(options);
}
// listeners: {<event-type>: {<label-key>: <fn>}}
listeners = configs.reduce(function(target, config) {
each(config.listeners || {}, function(fn, event) {
target[event] = target[event] || {};
target[event][config._key || DEFAULT_KEY] = fn;
});
delete config.listeners;
return target;
}, {});
return {
labels: configs,
listeners: listeners
};
}
function dispatchEvent(chart, listeners, label) {
if (!listeners) {
return;
}
var context = label.$context;
var groups = label.$groups;
var callback$1;
if (!listeners[groups._set]) {
return;
}
callback$1 = listeners[groups._set][groups._key];
if (!callback$1) {
return;
}
if (callback(callback$1, [context]) === true) {
// Users are allowed to tweak the given context by injecting values that can be
// used in scriptable options to display labels differently based on the current
// event (e.g. highlight an hovered label). That's why we update the label with
// the output context and schedule a new chart render by setting it dirty.
chart[EXPANDO_KEY]._dirty = true;
label.update(context);
}
}
function dispatchMoveEvents(chart, listeners, previous, label) {
var enter, leave;
if (!previous && !label) {
return;
}
if (!previous) {
enter = true;
} else if (!label) {
leave = true;
} else if (previous !== label) {
leave = enter = true;
}
if (leave) {
dispatchEvent(chart, listeners.leave, previous);
}
if (enter) {
dispatchEvent(chart, listeners.enter, label);
}
}
function handleMoveEvents(chart, event) {
var expando = chart[EXPANDO_KEY];
var listeners = expando._listeners;
var previous, label;
if (!listeners.enter && !listeners.leave) {
return;
}
if (event.type === 'mousemove') {
label = layout.lookup(expando._labels, event);
} else if (event.type !== 'mouseout') {
return;
}
previous = expando._hovered;
expando._hovered = label;
dispatchMoveEvents(chart, listeners, previous, label);
}
function handleClickEvents(chart, event) {
var expando = chart[EXPANDO_KEY];
var handlers = expando._listeners.click;
var label = handlers && layout.lookup(expando._labels, event);
if (label) {
dispatchEvent(chart, handlers, label);
}
}
var plugin = {
id: 'datalabels',
defaults: defaults,
beforeInit: function(chart) {
chart[EXPANDO_KEY] = {
_actives: []
};
},
beforeUpdate: function(chart) {
var expando = chart[EXPANDO_KEY];
expando._listened = false;
expando._listeners = {}; // {<event-type>: {<dataset-index>: {<label-key>: <fn>}}}
expando._datasets = []; // per dataset labels: [Label[]]
expando._labels = []; // layouted labels: Label[]
},
afterDatasetUpdate: function(chart, args, options) {
var datasetIndex = args.index;
var expando = chart[EXPANDO_KEY];
var labels = expando._datasets[datasetIndex] = [];
var visible = chart.isDatasetVisible(datasetIndex);
var dataset = chart.data.datasets[datasetIndex];
var config = configure(dataset, options);
var elements = args.meta.data || [];
var ctx = chart.ctx;
var i, j, ilen, jlen, cfg, key, el, label;
ctx.save();
for (i = 0, ilen = elements.length; i < ilen; ++i) {
el = elements[i];
el[EXPANDO_KEY] = [];
if (visible && el && chart.getDataVisibility(i) && !el.skip) {
for (j = 0, jlen = config.labels.length; j < jlen; ++j) {
cfg = config.labels[j];
key = cfg._key;
label = new Label(cfg, ctx, el, i);
label.$groups = {
_set: datasetIndex,
_key: key || DEFAULT_KEY
};
label.$context = {
active: false,
chart: chart,
dataIndex: i,
dataset: dataset,
datasetIndex: datasetIndex
};
label.update(label.$context);
el[EXPANDO_KEY].push(label);
labels.push(label);
}
}
}
ctx.restore();
// Store listeners at the chart level and per event type to optimize
// cases where no listeners are registered for a specific event.
merge(expando._listeners, config.listeners, {
merger: function(event, target, source) {
target[event] = target[event] || {};
target[event][args.index] = source[event];
expando._listened = true;
}
});
},
afterUpdate: function(chart, options) {
chart[EXPANDO_KEY]._labels = layout.prepare(
chart[EXPANDO_KEY]._datasets,
options);
},
// Draw labels on top of all dataset elements
// https://github.com/chartjs/chartjs-plugin-datalabels/issues/29
// https://github.com/chartjs/chartjs-plugin-datalabels/issues/32
afterDatasetsDraw: function(chart) {
layout.draw(chart, chart[EXPANDO_KEY]._labels);
},
beforeEvent: function(chart, args) {
// If there is no listener registered for this chart, `listened` will be false,
// meaning we can immediately ignore the incoming event and avoid useless extra
// computation for users who don't implement label interactions.
if (chart[EXPANDO_KEY]._listened) {
var event = args.event;
switch (event.type) {
case 'mousemove':
case 'mouseout':
handleMoveEvents(chart, event);
break;
case 'click':
handleClickEvents(chart, event);
break;
}
}
},
afterEvent: function(chart) {
var expando = chart[EXPANDO_KEY];
var previous = expando._actives;
var actives = expando._actives = chart.getActiveElements();
var updates = utils.arrayDiff(previous, actives);
var i, ilen, j, jlen, update, label, labels;
for (i = 0, ilen = updates.length; i < ilen; ++i) {
update = updates[i];
if (update[1]) {
labels = update[0].element[EXPANDO_KEY] || [];
for (j = 0, jlen = labels.length; j < jlen; ++j) {
label = labels[j];
label.$context.active = (update[1] === 1);
label.update(label.$context);
}
}
}
if (expando._dirty || updates.length) {
layout.update(expando._labels);
chart.render();
}
delete expando._dirty;
}
};
export default plugin;
|
/*!
* DevExpress Gantt (dx-gantt)
* Version: 3.1.27
* Build date: Fri Oct 29 2021
*
* Copyright (c) 2012 - 2021 Developer Express Inc. ALL RIGHTS RESERVED
* Read about DevExpress licensing here: https://www.devexpress.com/Support/EULAs
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Gantt"] = factory();
else
root["DevExpress"] = root["DevExpress"] || {}, root["DevExpress"]["Gantt"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 87);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__extends", function() { return __extends; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__assign", function() { return __assign; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__rest", function() { return __rest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__decorate", function() { return __decorate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__param", function() { return __param; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__metadata", function() { return __metadata; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__awaiter", function() { return __awaiter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__generator", function() { return __generator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__createBinding", function() { return __createBinding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__exportStar", function() { return __exportStar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__values", function() { return __values; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spreadArrays", function() { return __spreadArrays; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spreadArray", function() { return __spreadArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncGenerator", function() { return __asyncGenerator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncDelegator", function() { return __asyncDelegator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncValues", function() { return __asyncValues; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__makeTemplateObject", function() { return __makeTemplateObject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importStar", function() { return __importStar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importDefault", function() { return __importDefault; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__classPrivateFieldGet", function() { return __classPrivateFieldGet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__classPrivateFieldSet", function() { return __classPrivateFieldSet; });
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
}
return __assign.apply(this, arguments);
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
var __createBinding = Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
function __exportStar(m, o) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
/** @deprecated */
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
/** @deprecated */
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
var __setModuleDefault = Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var string_1 = __webpack_require__(42);
function isDefined(value) {
return value !== undefined && value !== null;
}
exports.isDefined = isDefined;
function boolToInt(value) {
return value ? 1 : 0;
}
exports.boolToInt = boolToInt;
function boolToString(value) {
return value ? '1' : '0';
}
exports.boolToString = boolToString;
function isNumber(obj) {
return typeof obj === 'number';
}
exports.isNumber = isNumber;
function isString(obj) {
return typeof obj === 'string';
}
exports.isString = isString;
function isNonNullString(str) {
return !!str;
}
exports.isNonNullString = isNonNullString;
function isEven(num) {
return (num % 2) !== 0;
}
exports.isEven = isEven;
function isOdd(num) {
return (num % 2) === 0;
}
exports.isOdd = isOdd;
function numberToStringBin(num, minLength) {
if (minLength === void 0) { minLength = 0; }
return string_1.StringUtils.padLeft(num.toString(2), minLength, '0');
}
exports.numberToStringBin = numberToStringBin;
function numberToStringHex(num, minLength) {
if (minLength === void 0) { minLength = 0; }
return string_1.StringUtils.padLeft(num.toString(16), minLength, '0');
}
exports.numberToStringHex = numberToStringHex;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MouseEventSource = exports.TaskTitlePosition = exports.Position = exports.ViewType = void 0;
var ViewType;
(function (ViewType) {
ViewType[ViewType["TenMinutes"] = 0] = "TenMinutes";
ViewType[ViewType["Hours"] = 1] = "Hours";
ViewType[ViewType["SixHours"] = 2] = "SixHours";
ViewType[ViewType["Days"] = 3] = "Days";
ViewType[ViewType["Weeks"] = 4] = "Weeks";
ViewType[ViewType["Months"] = 5] = "Months";
ViewType[ViewType["Quarter"] = 6] = "Quarter";
ViewType[ViewType["Years"] = 7] = "Years";
ViewType[ViewType["FiveYears"] = 8] = "FiveYears";
})(ViewType = exports.ViewType || (exports.ViewType = {}));
var Position;
(function (Position) {
Position[Position["Left"] = 0] = "Left";
Position[Position["Top"] = 1] = "Top";
Position[Position["Right"] = 2] = "Right";
Position[Position["Bottom"] = 3] = "Bottom";
})(Position = exports.Position || (exports.Position = {}));
var TaskTitlePosition;
(function (TaskTitlePosition) {
TaskTitlePosition[TaskTitlePosition["Inside"] = 0] = "Inside";
TaskTitlePosition[TaskTitlePosition["Outside"] = 1] = "Outside";
TaskTitlePosition[TaskTitlePosition["None"] = 2] = "None";
})(TaskTitlePosition = exports.TaskTitlePosition || (exports.TaskTitlePosition = {}));
var MouseEventSource;
(function (MouseEventSource) {
MouseEventSource[MouseEventSource["TaskArea"] = 0] = "TaskArea";
MouseEventSource[MouseEventSource["TaskEdit_Frame"] = 1] = "TaskEdit_Frame";
MouseEventSource[MouseEventSource["TaskEdit_Progress"] = 2] = "TaskEdit_Progress";
MouseEventSource[MouseEventSource["TaskEdit_Start"] = 3] = "TaskEdit_Start";
MouseEventSource[MouseEventSource["TaskEdit_End"] = 4] = "TaskEdit_End";
MouseEventSource[MouseEventSource["TaskEdit_DependencyStart"] = 5] = "TaskEdit_DependencyStart";
MouseEventSource[MouseEventSource["TaskEdit_DependencyFinish"] = 6] = "TaskEdit_DependencyFinish";
MouseEventSource[MouseEventSource["Successor_Wrapper"] = 7] = "Successor_Wrapper";
MouseEventSource[MouseEventSource["Successor_DependencyStart"] = 8] = "Successor_DependencyStart";
MouseEventSource[MouseEventSource["Successor_DependencyFinish"] = 9] = "Successor_DependencyFinish";
})(MouseEventSource = exports.MouseEventSource || (exports.MouseEventSource = {}));
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var browser_1 = __webpack_require__(8);
var common_1 = __webpack_require__(1);
var math_1 = __webpack_require__(57);
var string_1 = __webpack_require__(42);
var DomUtils = (function () {
function DomUtils() {
}
DomUtils.clearInnerHtml = function (element) {
while (element.firstChild)
element.removeChild(element.firstChild);
};
DomUtils.setStylePosition = function (style, point) {
style.left = math_1.MathUtils.round(point.x, 3) + 'px';
style.top = math_1.MathUtils.round(point.y, 3) + 'px';
};
DomUtils.setStyleSize = function (style, size) {
style.width = math_1.MathUtils.round(size.width, 3) + 'px';
style.height = math_1.MathUtils.round(size.height, 3) + 'px';
};
DomUtils.setStyleSizeAndPosition = function (style, rectangle) {
DomUtils.setStylePosition(style, rectangle);
DomUtils.setStyleSize(style, rectangle);
};
DomUtils.hideNode = function (node) {
if (node) {
var parentNode = node.parentNode;
if (parentNode)
parentNode.removeChild(node);
}
};
DomUtils.isHTMLElementNode = function (node) {
return node.nodeType === Node.ELEMENT_NODE;
};
DomUtils.isTextNode = function (node) {
return node.nodeType === Node.TEXT_NODE;
};
DomUtils.isElementNode = function (node) {
return node.nodeType === Node.ELEMENT_NODE;
};
DomUtils.isHTMLTableRowElement = function (element) {
return element.tagName === 'TR';
};
DomUtils.isItParent = function (parentElement, element) {
if (!parentElement || !element)
return false;
while (element) {
if (element === parentElement)
return true;
if (element.tagName === 'BODY')
return false;
element = element.parentNode;
}
return false;
};
DomUtils.getParentByTagName = function (element, tagName) {
tagName = tagName.toUpperCase();
while (element) {
if (element.tagName === 'BODY')
return null;
if (element.tagName === tagName)
return element;
element = element.parentNode;
}
return null;
};
DomUtils.getDocumentScrollTop = function () {
var isScrollBodyIE = browser_1.Browser.IE && DomUtils.getCurrentStyle(document.body).overflow === 'hidden' && document.body.scrollTop > 0;
if (browser_1.Browser.WebKitFamily || browser_1.Browser.Edge || isScrollBodyIE) {
if (browser_1.Browser.MacOSMobilePlatform)
return window.pageYOffset;
if (browser_1.Browser.WebKitFamily)
return document.documentElement.scrollTop || document.body.scrollTop;
return document.body.scrollTop;
}
else
return document.documentElement.scrollTop;
};
DomUtils.getDocumentScrollLeft = function () {
var isScrollBodyIE = browser_1.Browser.IE && DomUtils.getCurrentStyle(document.body).overflow === 'hidden' && document.body.scrollLeft > 0;
if (browser_1.Browser.Edge || isScrollBodyIE)
return document.body ? document.body.scrollLeft : document.documentElement.scrollLeft;
if (browser_1.Browser.WebKitFamily)
return document.documentElement.scrollLeft || document.body.scrollLeft;
return document.documentElement.scrollLeft;
};
DomUtils.getCurrentStyle = function (element) {
if (element.currentStyle)
return element.currentStyle;
else if (document.defaultView && document.defaultView.getComputedStyle) {
var result = document.defaultView.getComputedStyle(element, null);
if (!result && browser_1.Browser.Firefox && window.frameElement) {
var changes = [];
var curElement = window.frameElement;
while (!(result = document.defaultView.getComputedStyle(element, null))) {
changes.push([curElement, curElement.style.display]);
curElement.style.setProperty('display', 'block', 'important');
curElement = curElement.tagName === 'BODY' ? curElement.ownerDocument.defaultView.frameElement : curElement.parentNode;
}
result = cloneObject(result);
for (var ch = void 0, i = 0; ch = changes[i]; i++)
ch[0].style.display = ch[1];
document.body.offsetWidth;
}
return result;
}
return window.getComputedStyle(element, null);
};
DomUtils.setFocus = function (element) {
function focusCore() {
try {
element.focus();
if (browser_1.Browser.IE && document.activeElement !== element)
element.focus();
}
catch (e) {
}
}
if (browser_1.Browser.MacOSMobilePlatform)
focusCore();
else {
setTimeout(function () {
focusCore();
}, 100);
}
};
DomUtils.hasClassName = function (element, className) {
try {
var classNames = className.split(' ');
var classList = element.classList;
if (classList) {
for (var i = classNames.length - 1; i >= 0; i--) {
if (!classList.contains(classNames[i]))
return false;
}
}
else {
var elementClassName = element.getAttribute && element.getAttribute('class');
if (!elementClassName)
return false;
var elementClasses = elementClassName.split(' ');
for (var i = classNames.length - 1; i >= 0; i--) {
if (elementClasses.indexOf(classNames[i]) < 0)
return false;
}
}
return true;
}
catch (e) {
return false;
}
};
DomUtils.addClassName = function (element, className) {
if (!DomUtils.hasClassName(element, className)) {
var elementClassName = element.getAttribute && element.getAttribute('class');
element.setAttribute('class', elementClassName === '' ? className : elementClassName + " " + className);
}
};
DomUtils.removeClassName = function (element, className) {
var elementClassName = element.getAttribute && element.getAttribute('class');
var updClassName = " " + elementClassName + " ";
var newClassName = updClassName.replace(" " + className + " ", ' ');
if (updClassName.length !== newClassName.length)
element.setAttribute('class', string_1.StringUtils.trim(newClassName));
};
DomUtils.toggleClassName = function (element, className, toggle) {
if (toggle === undefined) {
if (DomUtils.hasClassName(element, className))
DomUtils.removeClassName(element, className);
else
DomUtils.addClassName(element, className);
}
else {
if (toggle)
DomUtils.addClassName(element, className);
else
DomUtils.removeClassName(element, className);
}
};
DomUtils.pxToInt = function (px) {
return pxToNumber(px, parseInt);
};
DomUtils.pxToFloat = function (px) {
return pxToNumber(px, parseFloat);
};
DomUtils.getAbsolutePositionY = function (element) {
function getAbsolutePositionY_IE(element) {
return browser_1.Browser.IE && element.parentNode === null ?
0 :
element.getBoundingClientRect().top + DomUtils.getDocumentScrollTop();
}
function getAbsolutePositionY_FF3(element) {
return Math.round(element.getBoundingClientRect().top + DomUtils.getDocumentScrollTop());
}
function getAbsolutePositionY_Opera(curEl) {
var isFirstCycle = true;
if (curEl && DomUtils.isHTMLTableRowElement(curEl) && curEl.cells.length > 0)
curEl = curEl.cells[0];
var pos = getAbsoluteScrollOffset_OperaFF(curEl, false);
while (curEl != null) {
pos += curEl.offsetTop;
if (!isFirstCycle)
pos -= curEl.scrollTop;
curEl = curEl.offsetParent;
isFirstCycle = false;
}
pos += document.body.scrollTop;
return pos;
}
function getAbsolutePositionY_NS(curEl) {
var pos = getAbsoluteScrollOffset_OperaFF(curEl, false);
var isFirstCycle = true;
while (curEl != null) {
pos += curEl.offsetTop;
if (!isFirstCycle && curEl.offsetParent != null)
pos -= curEl.scrollTop;
if (!isFirstCycle && browser_1.Browser.Firefox) {
var style = DomUtils.getCurrentStyle(curEl);
if (curEl.tagName === 'DIV' && style.overflow !== 'visible')
pos += DomUtils.pxToInt(style.borderTopWidth);
}
isFirstCycle = false;
curEl = curEl.offsetParent;
}
return pos;
}
function getAbsolutePositionY_Other(curEl) {
var pos = 0;
var isFirstCycle = true;
while (curEl != null) {
pos += curEl.offsetTop;
if (!isFirstCycle && curEl.offsetParent != null)
pos -= curEl.scrollTop;
isFirstCycle = false;
curEl = curEl.offsetParent;
}
return pos;
}
if (!element)
return 0;
if (browser_1.Browser.IE)
return getAbsolutePositionY_IE(element);
else if (browser_1.Browser.Firefox && browser_1.Browser.Version >= 3)
return getAbsolutePositionY_FF3(element);
else if (browser_1.Browser.Opera)
return getAbsolutePositionY_Opera(element);
else if (browser_1.Browser.NetscapeFamily && (!browser_1.Browser.Firefox || browser_1.Browser.Version < 3))
return getAbsolutePositionY_NS(element);
else if (browser_1.Browser.WebKitFamily || browser_1.Browser.Edge)
return getAbsolutePositionY_FF3(element);
return getAbsolutePositionY_Other(element);
};
DomUtils.getAbsolutePositionX = function (element) {
function getAbsolutePositionX_IE(element) {
return browser_1.Browser.IE && element.parentNode === null ?
0 :
element.getBoundingClientRect().left + DomUtils.getDocumentScrollLeft();
}
function getAbsolutePositionX_FF3(element) {
return Math.round(element.getBoundingClientRect().left + DomUtils.getDocumentScrollLeft());
}
function getAbsolutePositionX_Opera(curEl) {
var isFirstCycle = true;
var pos = getAbsoluteScrollOffset_OperaFF(curEl, true);
while (curEl != null) {
pos += curEl.offsetLeft;
if (!isFirstCycle)
pos -= curEl.scrollLeft;
curEl = curEl.offsetParent;
isFirstCycle = false;
}
pos += document.body.scrollLeft;
return pos;
}
function getAbsolutePositionX_NS(curEl) {
var pos = getAbsoluteScrollOffset_OperaFF(curEl, true);
var isFirstCycle = true;
while (curEl != null) {
pos += curEl.offsetLeft;
if (!isFirstCycle && curEl.offsetParent != null)
pos -= curEl.scrollLeft;
if (!isFirstCycle && browser_1.Browser.Firefox) {
var style = DomUtils.getCurrentStyle(curEl);
if (curEl.tagName === 'DIV' && style.overflow !== 'visible')
pos += DomUtils.pxToInt(style.borderLeftWidth);
}
isFirstCycle = false;
curEl = curEl.offsetParent;
}
return pos;
}
function getAbsolutePositionX_Other(curEl) {
var pos = 0;
var isFirstCycle = true;
while (curEl != null) {
pos += curEl.offsetLeft;
if (!isFirstCycle && curEl.offsetParent != null)
pos -= curEl.scrollLeft;
isFirstCycle = false;
curEl = curEl.offsetParent;
}
return pos;
}
if (!element)
return 0;
if (browser_1.Browser.IE)
return getAbsolutePositionX_IE(element);
else if (browser_1.Browser.Firefox && browser_1.Browser.Version >= 3)
return getAbsolutePositionX_FF3(element);
else if (browser_1.Browser.Opera)
return getAbsolutePositionX_Opera(element);
else if (browser_1.Browser.NetscapeFamily && (!browser_1.Browser.Firefox || browser_1.Browser.Version < 3))
return getAbsolutePositionX_NS(element);
else if (browser_1.Browser.WebKitFamily || browser_1.Browser.Edge)
return getAbsolutePositionX_FF3(element);
else
return getAbsolutePositionX_Other(element);
};
DomUtils.isInteractiveControl = function (element) {
return ['A', 'INPUT', 'SELECT', 'OPTION', 'TEXTAREA', 'BUTTON', 'IFRAME'].indexOf(element.tagName) > -1;
};
DomUtils.getClearClientHeight = function (element) {
return element.offsetHeight - (DomUtils.getTopBottomPaddings(element) + DomUtils.getVerticalBordersWidth(element));
};
DomUtils.getTopBottomPaddings = function (element, style) {
var currentStyle = style ? style : DomUtils.getCurrentStyle(element);
return DomUtils.pxToInt(currentStyle.paddingTop) + DomUtils.pxToInt(currentStyle.paddingBottom);
};
DomUtils.getVerticalBordersWidth = function (element, style) {
if (!common_1.isDefined(style))
style = (browser_1.Browser.IE && browser_1.Browser.MajorVersion !== 9 && window.getComputedStyle) ? window.getComputedStyle(element) : DomUtils.getCurrentStyle(element);
var res = 0;
if (style.borderTopStyle !== 'none')
res += DomUtils.pxToFloat(style.borderTopWidth);
if (style.borderBottomStyle !== 'none')
res += DomUtils.pxToFloat(style.borderBottomWidth);
return res;
};
DomUtils.getNodes = function (parent, predicate) {
var collection = parent.all || parent.getElementsByTagName('*');
var result = [];
for (var i = 0; i < collection.length; i++) {
var element = collection[i];
if (predicate(element))
result.push(element);
}
return result;
};
DomUtils.getChildNodes = function (parent, predicate) {
var collection = parent.childNodes;
var result = [];
for (var i = 0; i < collection.length; i++) {
var element = collection[i];
if (predicate(element))
result.push(element);
}
return result;
};
DomUtils.getNodesByClassName = function (parent, className) {
if (parent.querySelectorAll) {
var children = parent.querySelectorAll("." + className);
var result_1 = [];
children.forEach(function (element) { return result_1.push(element); });
return result_1;
}
else
return DomUtils.getNodes(parent, function (elem) { return DomUtils.hasClassName(elem, className); });
};
DomUtils.getChildNodesByClassName = function (parent, className) {
function nodeListToArray(nodeList, filter) {
var result = [];
nodeList.forEach(function (element) {
if (filter(element))
result.push(element);
});
return result;
}
if (parent.querySelectorAll) {
var children = parent.querySelectorAll("." + className);
return nodeListToArray(children, function (element) { return element.parentNode === parent; });
}
else {
return DomUtils.getChildNodes(parent, function (elem) {
if (DomUtils.isElementNode(elem))
return common_1.isNonNullString(elem.className) && DomUtils.hasClassName(elem, elem.className);
else
return false;
});
}
};
DomUtils.getVerticalScrollBarWidth = function () {
if (DomUtils.verticalScrollBarWidth === undefined) {
var container = document.createElement('DIV');
container.style.cssText = 'position: absolute; top: 0px; left: 0px; visibility: hidden; width: 200px; height: 150px; overflow: hidden; box-sizing: content-box';
document.body.appendChild(container);
var child = document.createElement('P');
container.appendChild(child);
child.style.cssText = 'width: 100%; height: 200px;';
var widthWithoutScrollBar = child.offsetWidth;
container.style.overflow = 'scroll';
var widthWithScrollBar = child.offsetWidth;
if (widthWithoutScrollBar === widthWithScrollBar)
widthWithScrollBar = container.clientWidth;
DomUtils.verticalScrollBarWidth = widthWithoutScrollBar - widthWithScrollBar;
document.body.removeChild(container);
}
return DomUtils.verticalScrollBarWidth;
};
DomUtils.getHorizontalBordersWidth = function (element, style) {
if (!common_1.isDefined(style))
style = (browser_1.Browser.IE && window.getComputedStyle) ? window.getComputedStyle(element) : DomUtils.getCurrentStyle(element);
var res = 0;
if (style.borderLeftStyle !== 'none')
res += DomUtils.pxToFloat(style.borderLeftWidth);
if (style.borderRightStyle !== 'none')
res += DomUtils.pxToFloat(style.borderRightWidth);
return res;
};
DomUtils.getFontFamiliesFromCssString = function (cssString) {
return cssString.split(',').map(function (fam) { return string_1.StringUtils.trim(fam.replace(/'|"/gi, '')); });
};
DomUtils.getInnerText = function (container) {
if (browser_1.Browser.Safari && browser_1.Browser.MajorVersion <= 5) {
if (DomUtils.html2PlainTextFilter === null) {
DomUtils.html2PlainTextFilter = document.createElement('DIV');
DomUtils.html2PlainTextFilter.style.width = '0';
DomUtils.html2PlainTextFilter.style.height = '0';
DomUtils.html2PlainTextFilter.style.overflow = 'visible';
DomUtils.html2PlainTextFilter.style.display = 'none';
document.body.appendChild(DomUtils.html2PlainTextFilter);
}
var filter = DomUtils.html2PlainTextFilter;
filter.innerHTML = container.innerHTML;
filter.style.display = '';
var innerText = filter.innerText;
filter.style.display = 'none';
return innerText;
}
else if (browser_1.Browser.NetscapeFamily || browser_1.Browser.WebKitFamily || (browser_1.Browser.IE && browser_1.Browser.Version >= 9) || browser_1.Browser.Edge)
return container.textContent;
else
return container.innerText;
};
DomUtils.html2PlainTextFilter = null;
DomUtils.verticalScrollBarWidth = undefined;
return DomUtils;
}());
exports.DomUtils = DomUtils;
function cloneObject(srcObject) {
if (typeof (srcObject) !== 'object' || !common_1.isDefined(srcObject))
return srcObject;
var newObject = {};
for (var i in srcObject)
newObject[i] = srcObject[i];
return newObject;
}
function pxToNumber(px, parseFunction) {
var result = 0;
if (common_1.isDefined(px) && px !== '') {
try {
var indexOfPx = px.indexOf('px');
if (indexOfPx > -1)
result = parseFunction(px.substr(0, indexOfPx));
}
catch (e) { }
}
return result;
}
function getAbsoluteScrollOffset_OperaFF(curEl, isX) {
var pos = 0;
var isFirstCycle = true;
while (curEl != null) {
if (curEl.tagName === 'BODY')
break;
var style = DomUtils.getCurrentStyle(curEl);
if (style.position === 'absolute')
break;
if (!isFirstCycle && curEl.tagName === 'DIV' && (style.position === '' || style.position === 'static'))
pos -= isX ? curEl.scrollLeft : curEl.scrollTop;
curEl = curEl.parentNode;
isFirstCycle = false;
}
return pos;
}
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Point = (function () {
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.zero = function () {
return new Point(0, 0);
};
Point.fromNumber = function (num) {
return new Point(num, num);
};
Point.prototype.isZero = function () {
return this.x === 0 && this.y === 0;
};
Point.prototype.toString = function () {
return JSON.stringify(this);
};
Point.prototype.copyFrom = function (obj) {
this.x = obj.x;
this.y = obj.y;
};
Point.prototype.clone = function () {
return new Point(this.x, this.y);
};
Point.prototype.equals = function (obj) {
return this.x === obj.x && this.y === obj.y;
};
Point.prototype.offset = function (offsetX, offsetY) {
this.x += offsetX;
this.y += offsetY;
return this;
};
Point.prototype.offsetByPoint = function (offset) {
this.x += offset.x;
this.y += offset.y;
return this;
};
Point.prototype.multiply = function (multiplierX, multiplierY) {
this.x *= multiplierX;
this.y *= multiplierY;
return this;
};
Point.prototype.negative = function () {
this.x *= -1;
this.y *= -1;
return this;
};
Point.prototype.applyConverter = function (converter) {
this.x = converter(this.x);
this.y = converter(this.y);
return this;
};
Point.plus = function (a, b) {
return new Point(a.x + b.x, a.y + b.y);
};
Point.minus = function (a, b) {
return new Point(a.x - b.x, a.y - b.y);
};
Point.xComparer = function (a, b) {
return a.x - b.x;
};
Point.yComparer = function (a, b) {
return a.y - b.y;
};
Point.equals = function (a, b) {
return a.x === b.x && a.y === b.y;
};
return Point;
}());
exports.Point = Point;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommandBase = void 0;
var CommandBase = (function () {
function CommandBase(control) {
this.control = control;
}
Object.defineProperty(CommandBase.prototype, "modelManipulator", {
get: function () { return this.control.modelManipulator; },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandBase.prototype, "history", {
get: function () { return this.control.history; },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandBase.prototype, "validationController", {
get: function () { return this.control.validationController; },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandBase.prototype, "state", {
get: function () {
if (!this._state)
this._state = this.getState();
return this._state;
},
enumerable: false,
configurable: true
});
CommandBase.prototype.execute = function () {
var parameters = [];
for (var _i = 0; _i < arguments.length; _i++) {
parameters[_i] = arguments[_i];
}
if (!this.state.enabled)
return false;
var executed = this.executeInternal.apply(this, parameters);
if (executed)
this.control.barManager.updateItemsState([]);
return executed;
};
CommandBase.prototype.isEnabled = function () {
return this.control.settings.editing.enabled;
};
CommandBase.prototype.executeInternal = function () {
var parameters = [];
for (var _i = 0; _i < arguments.length; _i++) {
parameters[_i] = arguments[_i];
}
throw new Error("Not implemented");
};
return CommandBase;
}());
exports.CommandBase = CommandBase;
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SimpleCommandState = void 0;
var SimpleCommandState = (function () {
function SimpleCommandState(enabled, value) {
this.visible = true;
this.enabled = enabled;
this.value = value;
}
return SimpleCommandState;
}());
exports.SimpleCommandState = SimpleCommandState;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DateTimeUtils = void 0;
var Time_1 = __webpack_require__(66);
var TimeRange_1 = __webpack_require__(67);
var common_1 = __webpack_require__(1);
var DateRange_1 = __webpack_require__(14);
var DayOfWeekMonthlyOccurrence_1 = __webpack_require__(68);
var DateTimeUtils = (function () {
function DateTimeUtils() {
}
DateTimeUtils.compareDates = function (date1, date2) {
if (!date1 || !date2)
return -1;
return date2.getTime() - date1.getTime();
};
DateTimeUtils.areDatesEqual = function (date1, date2) {
return this.compareDates(date1, date2) == 0;
};
DateTimeUtils.getMaxDate = function (date1, date2) {
if (!date1 && !date2)
return null;
if (!date1)
return date2;
if (!date2)
return date1;
var diff = this.compareDates(date1, date2);
return diff > 0 ? date2 : date1;
};
DateTimeUtils.getMinDate = function (date1, date2) {
if (!date1 && !date2)
return null;
if (!date1)
return date2;
if (!date2)
return date1;
var diff = this.compareDates(date1, date2);
return diff > 0 ? date1 : date2;
};
DateTimeUtils.getDaysBetween = function (start, end) {
var diff = Math.abs(end.getTime() - start.getTime());
return Math.ceil(diff / this.msInDay);
};
DateTimeUtils.getWeeksBetween = function (start, end) {
var daysBetween = this.getDaysBetween(start, end);
var numWeeks = Math.floor(daysBetween / 7);
if (start.getDay() > end.getDay())
numWeeks++;
return numWeeks;
};
DateTimeUtils.getMonthsDifference = function (start, end) {
var dateDiff = this.compareDates(start, end);
var from = dateDiff >= 0 ? start : end;
var to = dateDiff >= 0 ? end : start;
var yearsDiff = to.getFullYear() - from.getFullYear();
var monthDiff = yearsDiff * 12 + (to.getMonth() - from.getMonth());
return monthDiff;
};
DateTimeUtils.getYearsDifference = function (start, end) {
return Math.abs(end.getFullYear() - start.getFullYear());
};
DateTimeUtils.getDayNumber = function (date) {
return Math.ceil(date.getTime() / this.msInDay);
};
DateTimeUtils.getDateByDayNumber = function (num) {
var date = new Date(num * this.msInDay);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
return date;
};
DateTimeUtils.addDays = function (date, days) {
return new Date(date.getTime() + days * this.msInDay);
};
DateTimeUtils.checkDayOfMonth = function (day, date) {
return day == date.getDate();
};
DateTimeUtils.checkDayOfWeek = function (day, date) {
return day == date.getDay();
};
DateTimeUtils.checkMonth = function (month, date) {
return month == date.getMonth();
};
DateTimeUtils.checkYear = function (year, date) {
return year == date.getFullYear();
};
DateTimeUtils.checkDayOfWeekOccurrenceInMonth = function (date, dayOfWeek, occurrence) {
var dayOfWeekInMonthDates = this.getSpecificDayOfWeekInMonthDates(dayOfWeek, date.getFullYear(), date.getMonth());
if (occurrence == DayOfWeekMonthlyOccurrence_1.DayOfWeekMonthlyOccurrence.Last)
return this.areDatesEqual(date, dayOfWeekInMonthDates[dayOfWeekInMonthDates.length - 1]);
return this.areDatesEqual(date, dayOfWeekInMonthDates[occurrence]);
};
DateTimeUtils.getFirstDayOfWeekInMonth = function (year, month) {
var date = new Date(year, month, 1);
return date.getDay();
};
DateTimeUtils.getSpecificDayOfWeekInMonthDates = function (dayOfWeek, year, month) {
var firstDayOfWeekInMonth = this.getFirstDayOfWeekInMonth(year, month);
var diffDays = dayOfWeek >= firstDayOfWeekInMonth ? dayOfWeek - firstDayOfWeekInMonth : dayOfWeek + 7 - firstDayOfWeekInMonth;
var res = new Array();
var specificDayOfWeekDate = new Date(year, month, diffDays + 1);
while (specificDayOfWeekDate.getMonth() == month) {
res.push(specificDayOfWeekDate);
specificDayOfWeekDate = this.addDays(specificDayOfWeekDate, 7);
}
return res;
};
DateTimeUtils.getSpecificDayOfWeekInMonthDate = function (dayOfWeek, year, month, occurrence) {
var dates = this.getSpecificDayOfWeekInMonthDates(dayOfWeek, year, month);
if (occurrence == DayOfWeekMonthlyOccurrence_1.DayOfWeekMonthlyOccurrence.Last)
return dates[dates.length - 1];
return dates[occurrence];
};
DateTimeUtils.checkValidDayInMonth = function (year, month, day) {
if (day < 1 || day > 31 || (new Date(year, month, day)).getMonth() != month)
return false;
return true;
};
DateTimeUtils.getNextMonth = function (month, inc) {
if (inc === void 0) { inc = 1; }
return (month + inc) % 12;
};
DateTimeUtils.convertToDate = function (src) {
if (src instanceof Date)
return new Date(src);
var ms = Date.parse(src);
if (!isNaN(ms))
return new Date(ms);
return null;
};
DateTimeUtils.convertTimeRangeToDateRange = function (timeRange, dayNumber) {
var date = this.getDateByDayNumber(dayNumber);
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var startT = timeRange.start;
var start = new Date(year, month, day, startT.hour, startT.min, startT.sec, startT.msec);
var endT = timeRange.end;
var end = new Date(year, month, day, endT.hour, endT.min, endT.sec, endT.msec);
return new DateRange_1.DateRange(start, end);
};
DateTimeUtils.convertToTimeRanges = function (src) {
var _this = this;
if (src instanceof Array)
return src.map(function (x) { return _this.convertToTimeRange(x); });
return this.parseTimeRanges(src);
};
DateTimeUtils.convertToTimeRange = function (src) {
if (!src)
return null;
if (src instanceof TimeRange_1.TimeRange)
return src;
if ((0, common_1.isDefined)(src.start) && (0, common_1.isDefined)(src.end))
return new TimeRange_1.TimeRange(this.convertToTime(src.start), this.convertToTime(src.end));
return this.parseTimeRange(src);
};
DateTimeUtils.convertToTime = function (src) {
if (!src)
return null;
if (src instanceof Time_1.Time)
return src;
if (src instanceof Date)
return this.getTimeGromJsDate(src);
return this.parseTime(src);
};
DateTimeUtils.parseTimeRanges = function (src) {
var _this = this;
if (!src)
return null;
var parts = src.split(/;|,/);
return parts.map(function (p) { return _this.parseTimeRange(p); }).filter(function (r) { return !!r; });
};
DateTimeUtils.parseTimeRange = function (src) {
if (!src)
return null;
var parts = src.split("-");
var start = parts[0];
var end = parts[1];
if ((0, common_1.isDefined)(start) && (0, common_1.isDefined)(end))
return new TimeRange_1.TimeRange(this.parseTime(start), this.parseTime(end));
return null;
};
DateTimeUtils.parseTime = function (src) {
if (!src)
return null;
var parts = src.split(":");
var h = parseInt(parts[0]) || 0;
var m = parseInt(parts[1]) || 0;
var s = parseInt(parts[2]) || 0;
var ms = parseInt(parts[3]) || 0;
return new Time_1.Time(h, m, s, ms);
};
DateTimeUtils.getTimeGromJsDate = function (date) {
if (!date)
return null;
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
var ms = date.getMilliseconds();
return new Time_1.Time(h, m, s, ms);
};
DateTimeUtils.caclTimeDifference = function (time1, time2) {
return time2.getTimeInMilleconds() - time1.getTimeInMilleconds();
};
DateTimeUtils.areTimesEqual = function (time1, time2) {
return this.caclTimeDifference(time1, time2) == 0;
};
DateTimeUtils.getMaxTime = function (time1, time2) {
if (!time1 && !time2)
return null;
if (!time1)
return time2;
if (!time2)
return time1;
var diff = this.caclTimeDifference(time1, time2);
return diff > 0 ? time2 : time1;
};
DateTimeUtils.getMinTime = function (time1, time2) {
if (!time1 && !time2)
return null;
if (!time1)
return time2;
if (!time2)
return time1;
var diff = this.caclTimeDifference(time1, time2);
return diff > 0 ? time1 : time2;
};
DateTimeUtils.getLastTimeOfDay = function () {
return new Time_1.Time(23, 59, 59, 999);
};
DateTimeUtils.msInDay = 24 * 3600 * 1000;
return DateTimeUtils;
}());
exports.DateTimeUtils = DateTimeUtils;
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Browser = (function () {
function Browser() {
}
Browser.IdentUserAgent = function (userAgent, ignoreDocumentMode) {
if (ignoreDocumentMode === void 0) { ignoreDocumentMode = false; }
var browserTypesOrderedList = ['Mozilla', 'IE', 'Firefox', 'Netscape', 'Safari', 'Chrome', 'Opera', 'Opera10', 'Edge'];
var defaultBrowserType = 'IE';
var defaultPlatform = 'Win';
var defaultVersions = { Safari: 2, Chrome: 0.1, Mozilla: 1.9, Netscape: 8, Firefox: 2, Opera: 9, IE: 6, Edge: 12 };
if (!userAgent || userAgent.length === 0) {
Browser.fillUserAgentInfo(browserTypesOrderedList, defaultBrowserType, defaultVersions[defaultBrowserType], defaultPlatform);
return;
}
userAgent = userAgent.toLowerCase();
Browser.indentPlatformMajorVersion(userAgent);
try {
var platformIdentStrings = {
'Windows': 'Win',
'Macintosh': 'Mac',
'Mac OS': 'Mac',
'Mac_PowerPC': 'Mac',
'cpu os': 'MacMobile',
'cpu iphone os': 'MacMobile',
'Android': 'Android',
'!Windows Phone': 'WinPhone',
'!WPDesktop': 'WinPhone',
'!ZuneWP': 'WinPhone'
};
var optSlashOrSpace = '(?:/|\\s*)?';
var versionString = '(\\d+)(?:\\.((?:\\d+?[1-9])|\\d)0*?)?';
var optVersion = '(?:' + versionString + ')?';
var patterns = {
Safari: 'applewebkit(?:.*?(?:version/' + versionString + '[\\.\\w\\d]*?(?:\\s+mobile/\\S*)?\\s+safari))?',
Chrome: '(?:chrome|crios)(?!frame)' + optSlashOrSpace + optVersion,
Mozilla: 'mozilla(?:.*rv:' + optVersion + '.*Gecko)?',
Netscape: '(?:netscape|navigator)\\d*/?\\s*' + optVersion,
Firefox: 'firefox' + optSlashOrSpace + optVersion,
Opera: '(?:opera|\\sopr)' + optSlashOrSpace + optVersion,
Opera10: 'opera.*\\s*version' + optSlashOrSpace + optVersion,
IE: 'msie\\s*' + optVersion,
Edge: 'edge' + optSlashOrSpace + optVersion
};
var browserType = null;
var version = -1;
for (var i = 0; i < browserTypesOrderedList.length; i++) {
var browserTypeCandidate = browserTypesOrderedList[i];
var regExp = new RegExp(patterns[browserTypeCandidate], 'i');
var matches = regExp.exec(userAgent);
if (matches && matches.index >= 0) {
if (browserType === 'IE' && version >= 11 && browserTypeCandidate === 'Safari')
continue;
browserType = browserTypeCandidate;
if (browserType === 'Opera10')
browserType = 'Opera';
var tridentPattern = 'trident' + optSlashOrSpace + optVersion;
version = Browser.GetBrowserVersion(userAgent, matches, tridentPattern, Browser.getIECompatibleVersionString());
if (browserType === 'Mozilla' && version >= 11)
browserType = 'IE';
}
}
if (!browserType)
browserType = defaultBrowserType;
var browserVersionDetected = version !== -1;
if (!browserVersionDetected)
version = defaultVersions[browserType];
var platform = null;
var minOccurenceIndex = Number.MAX_VALUE;
for (var identStr in platformIdentStrings) {
if (!Object.prototype.hasOwnProperty.call(platformIdentStrings, identStr))
continue;
var importantIdent = identStr.substr(0, 1) === '!';
var occurenceIndex = userAgent.indexOf((importantIdent ? identStr.substr(1) : identStr).toLowerCase());
if (occurenceIndex >= 0 && (occurenceIndex < minOccurenceIndex || importantIdent)) {
minOccurenceIndex = importantIdent ? 0 : occurenceIndex;
platform = platformIdentStrings[identStr];
}
}
var samsungPattern = 'SM-[A-Z]';
var m = userAgent.toUpperCase().match(samsungPattern);
var isSamsungAndroidDevice = m && m.length > 0;
if (platform === 'WinPhone' && version < 9)
version = Math.floor(Browser.getVersionFromTrident(userAgent, 'trident' + optSlashOrSpace + optVersion));
if (!ignoreDocumentMode && browserType === 'IE' && version > 7 && document.documentMode < version)
version = document.documentMode;
if (platform === 'WinPhone')
version = Math.max(9, version);
if (!platform)
platform = defaultPlatform;
if (platform === platformIdentStrings['cpu os'] && !browserVersionDetected)
version = 4;
Browser.fillUserAgentInfo(browserTypesOrderedList, browserType, version, platform, isSamsungAndroidDevice);
}
catch (e) {
Browser.fillUserAgentInfo(browserTypesOrderedList, defaultBrowserType, defaultVersions[defaultBrowserType], defaultPlatform);
}
};
Browser.GetBrowserVersion = function (userAgent, matches, tridentPattern, ieCompatibleVersionString) {
var version = Browser.getVersionFromMatches(matches);
if (ieCompatibleVersionString) {
var versionFromTrident = Browser.getVersionFromTrident(userAgent, tridentPattern);
if (ieCompatibleVersionString === 'edge' || parseInt(ieCompatibleVersionString) === versionFromTrident)
return versionFromTrident;
}
return version;
};
Browser.getIECompatibleVersionString = function () {
if (document.compatible) {
for (var i = 0; i < document.compatible.length; i++) {
if (document.compatible[i].userAgent === 'IE' && document.compatible[i].version)
return document.compatible[i].version.toLowerCase();
}
}
return '';
};
Browser.isTouchEnabled = function () {
return ('ontouchstart' in window) ||
(navigator['maxTouchPoints'] > 0) ||
(navigator['msMaxTouchPoints'] > 0);
};
Browser.fillUserAgentInfo = function (browserTypesOrderedList, browserType, version, platform, isSamsungAndroidDevice) {
if (isSamsungAndroidDevice === void 0) { isSamsungAndroidDevice = false; }
for (var i = 0; i < browserTypesOrderedList.length; i++) {
var type = browserTypesOrderedList[i];
Browser[type] = type === browserType;
}
Browser.Version = Math.floor(10.0 * version) / 10.0;
Browser.MajorVersion = Math.floor(Browser.Version);
Browser.WindowsPlatform = platform === 'Win' || platform === 'WinPhone';
Browser.MacOSMobilePlatform = platform === 'MacMobile' || (platform === 'Mac' && Browser.isTouchEnabled());
Browser.MacOSPlatform = platform === 'Mac' && !Browser.MacOSMobilePlatform;
Browser.AndroidMobilePlatform = platform === 'Android';
Browser.WindowsPhonePlatform = platform === 'WinPhone';
Browser.WebKitFamily = Browser.Safari || Browser.Chrome || Browser.Opera && Browser.MajorVersion >= 15;
Browser.NetscapeFamily = Browser.Netscape || Browser.Mozilla || Browser.Firefox;
Browser.HardwareAcceleration = (Browser.IE && Browser.MajorVersion >= 9) || (Browser.Firefox && Browser.MajorVersion >= 4) ||
(Browser.AndroidMobilePlatform && Browser.Chrome) || (Browser.Chrome && Browser.MajorVersion >= 37) ||
(Browser.Safari && !Browser.WindowsPlatform) || Browser.Edge || (Browser.Opera && Browser.MajorVersion >= 46);
Browser.WebKitTouchUI = Browser.MacOSMobilePlatform || Browser.AndroidMobilePlatform;
var isIETouchUI = Browser.IE && Browser.MajorVersion > 9 && Browser.WindowsPlatform && Browser.UserAgent.toLowerCase().indexOf('touch') >= 0;
Browser.MSTouchUI = isIETouchUI || (Browser.Edge && !!window.navigator.maxTouchPoints);
Browser.TouchUI = Browser.WebKitTouchUI || Browser.MSTouchUI;
Browser.MobileUI = Browser.WebKitTouchUI || Browser.WindowsPhonePlatform;
Browser.AndroidDefaultBrowser = Browser.AndroidMobilePlatform && !Browser.Chrome;
Browser.AndroidChromeBrowser = Browser.AndroidMobilePlatform && Browser.Chrome;
if (isSamsungAndroidDevice)
Browser.SamsungAndroidDevice = isSamsungAndroidDevice;
if (Browser.MSTouchUI) {
var isARMArchitecture = Browser.UserAgent.toLowerCase().indexOf('arm;') > -1;
Browser.VirtualKeyboardSupported = isARMArchitecture || Browser.WindowsPhonePlatform;
}
else
Browser.VirtualKeyboardSupported = Browser.WebKitTouchUI;
Browser.fillDocumentElementBrowserTypeClassNames(browserTypesOrderedList);
};
Browser.indentPlatformMajorVersion = function (userAgent) {
var regex = /(?:(?:windows nt|macintosh|mac os|cpu os|cpu iphone os|android|windows phone|linux) )(\d+)(?:[-0-9_.])*/;
var matches = regex.exec(userAgent);
if (matches)
Browser.PlaformMajorVersion = matches[1];
};
Browser.getVersionFromMatches = function (matches) {
var result = -1;
var versionStr = '';
if (matches) {
if (matches[1]) {
versionStr += matches[1];
if (matches[2])
versionStr += '.' + matches[2];
}
if (versionStr !== '') {
result = parseFloat(versionStr);
if (isNaN(result))
result = -1;
}
}
return result;
};
Browser.getVersionFromTrident = function (userAgent, tridentPattern) {
var tridentDiffFromVersion = 4;
var matches = new RegExp(tridentPattern, 'i').exec(userAgent);
return Browser.getVersionFromMatches(matches) + tridentDiffFromVersion;
};
Browser.fillDocumentElementBrowserTypeClassNames = function (browserTypesOrderedList) {
var documentElementClassName = '';
var browserTypeslist = browserTypesOrderedList.concat(['WindowsPlatform', 'MacOSPlatform', 'MacOSMobilePlatform', 'AndroidMobilePlatform',
'WindowsPhonePlatform', 'WebKitFamily', 'WebKitTouchUI', 'MSTouchUI', 'TouchUI', 'AndroidDefaultBrowser']);
for (var i = 0; i < browserTypeslist.length; i++) {
var type = browserTypeslist[i];
if (Browser[type])
documentElementClassName += 'dx' + type + ' ';
}
documentElementClassName += 'dxBrowserVersion-' + Browser.MajorVersion;
if (typeof document !== 'undefined' && document && document.documentElement) {
if (document.documentElement.className !== '')
documentElementClassName = ' ' + documentElementClassName;
document.documentElement.className += documentElementClassName;
Browser.Info = documentElementClassName;
}
};
Browser.getUserAgent = function () {
return typeof navigator !== 'undefined' && navigator.userAgent ? navigator.userAgent.toLowerCase() : '';
};
Browser.UserAgent = Browser.getUserAgent();
Browser._foo = Browser.IdentUserAgent(Browser.UserAgent);
return Browser;
}());
exports.Browser = Browser;
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseArguments = void 0;
var BaseArguments = (function () {
function BaseArguments(key) {
this.cancel = false;
this.values = {};
this.key = key;
}
return BaseArguments;
}());
exports.BaseArguments = BaseArguments;
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var browser_1 = __webpack_require__(8);
var common_1 = __webpack_require__(1);
var dom_1 = __webpack_require__(3);
var touch_1 = __webpack_require__(27);
var EvtUtils = (function () {
function EvtUtils() {
}
EvtUtils.preventEvent = function (evt) {
if (evt.preventDefault)
evt.preventDefault();
else
evt.returnValue = false;
};
EvtUtils.getEventSource = function (evt) {
if (!common_1.isDefined(evt))
return null;
return evt.srcElement ? evt.srcElement : evt.target;
};
EvtUtils.getEventSourceByPosition = function (evt) {
if (!common_1.isDefined(evt))
return null;
if (document.elementFromPoint && EvtUtils.getEventX(evt) !== undefined && EvtUtils.getEventY(evt) !== undefined)
return document.elementFromPoint(EvtUtils.getEventX(evt), EvtUtils.getEventY(evt));
return evt.srcElement ? evt.srcElement : evt.target;
};
EvtUtils.getMouseWheelEventName = function () {
if (browser_1.Browser.Safari)
return 'mousewheel';
if (browser_1.Browser.NetscapeFamily && browser_1.Browser.MajorVersion < 17)
return 'DOMMouseScroll';
return 'wheel';
};
EvtUtils.isLeftButtonPressed = function (evt) {
if (touch_1.TouchUtils.isTouchEvent(evt))
return true;
evt = (browser_1.Browser.IE && common_1.isDefined(event)) ? event : evt;
if (!evt)
return false;
if (browser_1.Browser.IE && browser_1.Browser.Version < 11) {
if (browser_1.Browser.MSTouchUI)
return true;
return evt.button % 2 === 1;
}
else if (browser_1.Browser.WebKitFamily) {
if (evt.type === 'pointermove')
return evt.buttons === 1;
return evt.which === 1;
}
else if (browser_1.Browser.NetscapeFamily || browser_1.Browser.Edge || (browser_1.Browser.IE && browser_1.Browser.Version >= 11)) {
if (evt.type === touch_1.TouchUtils.touchMouseMoveEventName)
return evt.buttons === 1;
return evt.which === 1;
}
else if (browser_1.Browser.Opera)
return evt.button === 0;
return true;
};
EvtUtils.preventEventAndBubble = function (evt) {
EvtUtils.preventEvent(evt);
if (evt.stopPropagation)
evt.stopPropagation();
evt.cancelBubble = true;
};
EvtUtils.clientEventRequiresDocScrollCorrection = function () {
var isSafariVerLess3 = browser_1.Browser.Safari && browser_1.Browser.Version < 3;
var isMacOSMobileVerLess51 = browser_1.Browser.MacOSMobilePlatform && browser_1.Browser.Version < 5.1;
return browser_1.Browser.AndroidDefaultBrowser || browser_1.Browser.AndroidChromeBrowser || !(isSafariVerLess3 || isMacOSMobileVerLess51);
};
EvtUtils.getEventX = function (evt) {
if (touch_1.TouchUtils.isTouchEvent(evt))
return touch_1.TouchUtils.getEventX(evt);
return evt.clientX + (EvtUtils.clientEventRequiresDocScrollCorrection() ? dom_1.DomUtils.getDocumentScrollLeft() : 0);
};
EvtUtils.getEventY = function (evt) {
if (touch_1.TouchUtils.isTouchEvent(evt))
return touch_1.TouchUtils.getEventY(evt);
return evt.clientY + (EvtUtils.clientEventRequiresDocScrollCorrection() ? dom_1.DomUtils.getDocumentScrollTop() : 0);
};
EvtUtils.cancelBubble = function (evt) {
evt.cancelBubble = true;
};
EvtUtils.getWheelDelta = function (evt) {
var ret;
if (browser_1.Browser.NetscapeFamily && browser_1.Browser.MajorVersion < 17)
ret = -evt.detail;
else if (browser_1.Browser.Safari)
ret = evt.wheelDelta;
else
ret = -evt.deltaY;
if (browser_1.Browser.Opera && browser_1.Browser.Version < 9)
ret = -ret;
return ret;
};
return EvtUtils;
}());
exports.EvtUtils = EvtUtils;
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Size = (function () {
function Size(width, height) {
this.width = width;
this.height = height;
}
Size.empty = function () {
return new Size(0, 0);
};
Size.fromNumber = function (num) {
return new Size(num, num);
};
Size.initByCommonAction = function (action) {
var widthAdp = function (s) { return s.width; };
var heightAdp = function (s) { return s.height; };
return new Size(action(widthAdp, heightAdp), action(heightAdp, widthAdp));
};
Size.prototype.isEmpty = function () {
return this.width === 0 && this.height === 0;
};
Size.prototype.toString = function () {
return JSON.stringify(this);
};
Size.prototype.nonNegativeSize = function () {
if (this.width < 0)
this.width = 0;
if (this.height < 0)
this.height = 0;
return this;
};
Size.prototype.offset = function (offsetWidth, offsetHeight) {
this.width = this.width + offsetWidth;
this.height = this.height + offsetHeight;
return this;
};
Size.prototype.multiply = function (multiplierW, multiplierH) {
this.width *= multiplierW;
this.height *= multiplierH;
return this;
};
Size.prototype.equals = function (obj) {
return this.width === obj.width && this.height === obj.height;
};
Size.prototype.clone = function () {
return new Size(this.width, this.height);
};
Size.prototype.copyFrom = function (obj) {
this.width = obj.width;
this.height = obj.height;
};
Size.prototype.applyConverter = function (conv) {
this.width = conv(this.width);
this.height = conv(this.height);
return this;
};
Size.equals = function (a, b) {
return a.width === b.width && a.height === b.height;
};
return Size;
}());
exports.Size = Size;
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HistoryItem = void 0;
var HistoryItem = (function () {
function HistoryItem(modelManipulator) {
this.setModelManipulator(modelManipulator);
}
HistoryItem.prototype.setModelManipulator = function (modelManipulator) {
this.modelManipulator = modelManipulator;
};
return HistoryItem;
}());
exports.HistoryItem = HistoryItem;
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RenderElementUtils = void 0;
var RenderElementUtils = (function () {
function RenderElementUtils() {
}
RenderElementUtils.create = function (info, index, parent, dictionary) {
var element = document.createElement("DIV");
info.assignToElement(element);
parent.appendChild(element);
if (dictionary)
if (dictionary instanceof Array && index !== null)
dictionary[index] = element;
else
dictionary[info.id] = element;
for (var key in info.attr)
if (Object.prototype.hasOwnProperty.call(info.attr, key))
element.setAttribute(key, info.attr[key]);
for (var key in info.style)
if (Object.prototype.hasOwnProperty.call(info.style, key))
element.style[key] = info.style[key];
return element;
};
RenderElementUtils.remove = function (info, index, parent, dictionary) {
var element;
if (dictionary instanceof Array && index !== null) {
element = dictionary[index];
delete dictionary[index];
}
else {
element = dictionary[info.id];
delete dictionary[info.id];
}
if (element && element.parentNode == parent)
parent.removeChild(element);
};
RenderElementUtils.recreate = function (oldRenderedElementsInfo, newRenderedelementsInfo, removeAction, createAction) {
oldRenderedElementsInfo
.filter(function (info) { return newRenderedelementsInfo.indexOf(info) === -1; })
.forEach(function (info) { removeAction(info); });
newRenderedelementsInfo
.filter(function (info) { return oldRenderedElementsInfo.indexOf(info) === -1; })
.forEach(function (info) { createAction(info); });
};
return RenderElementUtils;
}());
exports.RenderElementUtils = RenderElementUtils;
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DateRange = void 0;
var DateRange = (function () {
function DateRange(start, end) {
this.start = start;
this.end = end;
}
DateRange.prototype.equal = function (date) {
var result = true;
result = result && this.start.getTime() === date.start.getTime();
result = result && this.end.getTime() === date.end.getTime();
return result;
};
return DateRange;
}());
exports.DateRange = DateRange;
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskPropertiesHistoryItemBase = void 0;
var tslib_1 = __webpack_require__(0);
var HistoryItem_1 = __webpack_require__(12);
var TaskPropertiesHistoryItemBase = (function (_super) {
(0, tslib_1.__extends)(TaskPropertiesHistoryItemBase, _super);
function TaskPropertiesHistoryItemBase(modelManipulator, taskId, newValue) {
var _this = _super.call(this, modelManipulator) || this;
_this.taskId = taskId;
_this.newValue = newValue;
return _this;
}
TaskPropertiesHistoryItemBase.prototype.redo = function () {
this.oldState = this.getPropertiesManipulator().setValue(this.taskId, this.newValue);
};
TaskPropertiesHistoryItemBase.prototype.undo = function () {
this.getPropertiesManipulator().restoreValue(this.oldState);
};
TaskPropertiesHistoryItemBase.prototype.getPropertiesManipulator = function () {
throw new Error("Not Implemented");
};
return TaskPropertiesHistoryItemBase;
}(HistoryItem_1.HistoryItem));
exports.TaskPropertiesHistoryItemBase = TaskPropertiesHistoryItemBase;
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GridLayoutCalculator = void 0;
var size_1 = __webpack_require__(11);
var DateRange_1 = __webpack_require__(14);
var Enums_1 = __webpack_require__(2);
var GridElementInfo_1 = __webpack_require__(72);
var point_1 = __webpack_require__(4);
var DateUtils_1 = __webpack_require__(21);
var StripLine_1 = __webpack_require__(73);
var Enums_2 = __webpack_require__(24);
var ScaleCalculator_1 = __webpack_require__(150);
var common_1 = __webpack_require__(1);
var GridLayoutCalculator = (function () {
function GridLayoutCalculator() {
this.tileToDependencyMap = [];
this.tileToNoWorkingIntervalsMap = [];
this.minLineLength = 10;
this.resourceMaxWidth = 500;
this.minTaskWidth = 2;
this._taskWrapperPoints = Array();
this._taskElementInfoList = Array();
this._scaleCalculator = new ScaleCalculator_1.ScaleCalculator();
}
GridLayoutCalculator.prototype.setSettings = function (visibleTaskAreaSize, tickSize, elementSizeValues, range, viewModel, viewType, scrollBarHeight, firstDayOfWeek) {
if (scrollBarHeight === void 0) { scrollBarHeight = 0; }
if (firstDayOfWeek === void 0) { firstDayOfWeek = 0; }
this.visibleTaskAreaSize = visibleTaskAreaSize;
this.tickSize = tickSize;
this._viewType = viewType;
this.range = range;
this.verticalTickCount = viewModel.itemCount;
this.viewModel = viewModel;
this.elementSizeValues = elementSizeValues;
this.taskHeight = elementSizeValues.taskHeight;
this.parentTaskHeight = elementSizeValues.parentTaskHeight;
this.milestoneWidth = elementSizeValues.milestoneWidth;
this.scaleHeight = elementSizeValues.scaleItemHeight;
this.arrowSize = new size_1.Size(elementSizeValues.connectorArrowWidth, elementSizeValues.connectorArrowWidth);
this.lineThickness = elementSizeValues.connectorLineThickness;
this.minConnectorSpaceFromTask = (this.tickSize.height - this.taskHeight) / 2;
this.tickTimeSpan = DateUtils_1.DateUtils.getTickTimeSpan(viewType);
this.scrollBarHeight = scrollBarHeight;
this.createTileToNonWorkingIntervalsMap();
this._scaleCalculator.setSettings(range, viewType, tickSize, firstDayOfWeek);
this.reset();
};
Object.defineProperty(GridLayoutCalculator.prototype, "viewType", {
get: function () { return this._viewType; },
set: function (value) {
if (this._viewType !== value) {
this._viewType = value;
this._scaleCalculator.setViewType(value);
}
},
enumerable: false,
configurable: true
});
GridLayoutCalculator.prototype.reset = function () {
this._taskWrapperPoints = new Array();
this._taskElementInfoList = Array();
};
GridLayoutCalculator.prototype.resetTaskInfo = function (index) {
delete this._taskWrapperPoints[index];
delete this._taskElementInfoList[index];
};
GridLayoutCalculator.prototype.getTaskAreaBorderInfo = function (index, isVertical) {
var sizeValue = isVertical ? this.getVerticalGridLineHeight() : this.getTotalWidth();
return this.getGridBorderInfo(index, isVertical, sizeValue);
};
GridLayoutCalculator.prototype.getTotalWidth = function () {
return this._scaleCalculator.scaleWidth;
};
GridLayoutCalculator.prototype.getScaleBorderInfo = function (index, scaleType) {
var result = new GridElementInfo_1.GridElementInfo();
var calc = this._scaleCalculator;
result.setPosition(new point_1.Point(calc.getScaleBorderPosition(index, scaleType), undefined));
result.setSize(new size_1.Size(0, this.scaleHeight));
result.className = "dx-gantt-vb";
return result;
};
GridLayoutCalculator.prototype.getGridBorderInfo = function (index, isVertical, size) {
var result = new GridElementInfo_1.GridElementInfo();
result.setPosition(this.getGridBorderPosition(index, isVertical));
if (size)
result.setSize(this.getGridBorderSize(isVertical, size));
result.className = isVertical ? "dx-gantt-vb" : "dx-gantt-hb";
return result;
};
GridLayoutCalculator.prototype.getGridBorderPosition = function (index, isVertical) {
var result = new point_1.Point(undefined, undefined);
var calc = this._scaleCalculator;
var posValue = isVertical ? calc.getScaleBorderPosition(index, this.viewType) : (index + 1) * this.tickSize.height;
if (isVertical)
result.x = posValue;
else
result.y = posValue;
return result;
};
GridLayoutCalculator.prototype.getGridBorderSize = function (isVertical, sizeValue) {
var result = new size_1.Size(0, 0);
if (isVertical)
result.height = sizeValue;
else
result.width = sizeValue;
return result;
};
GridLayoutCalculator.prototype.getScaleElementInfo = function (index, scaleType) {
var result = new GridElementInfo_1.GridElementInfo();
var item = this.getScaleItemInfo(index, scaleType);
if (item) {
result.setPosition(item.position);
result.setSize(item.size);
result.className = this.getScaleItemClassName(scaleType, result, this.getRenderedNoWorkingIntervals(result.position.x));
var calc = this._scaleCalculator;
var items = calc.getScaleItems(scaleType);
var needEllipsis = index === 0 || index === items.length - 1;
if (needEllipsis) {
result.style["overflowX"] = "hidden";
result.style["textOverflow"] = "ellipsis";
}
}
return result;
};
GridLayoutCalculator.prototype.getScaleItemStart = function (index, scaleType) {
return this._scaleCalculator.getScaleItemAdjustedStart(index, scaleType);
};
GridLayoutCalculator.prototype.getScaleItemClassName = function (scaleType, scaleItemInfo, noWorkingIntervals) {
var result = "dx-gantt-si";
if (scaleType.valueOf() == this.viewType.valueOf() && this.isScaleItemInsideNoWorkingInterval(scaleItemInfo, noWorkingIntervals))
result += " dx-gantt-holiday-scaleItem";
return result;
};
GridLayoutCalculator.prototype.getScaleItemInfo = function (index, scaleType) {
return this._scaleCalculator.getScaleItem(index, scaleType);
};
GridLayoutCalculator.prototype.getScaleRangesInArea = function (left, right) {
var topScale = DateUtils_1.DateUtils.ViewTypeToScaleMap[this.viewType];
var calc = this._scaleCalculator;
var topStartIndex = Math.max(calc.getScaleIndexByPos(left, topScale), 0);
var topEndIndex = calc.getScaleIndexByPos(right, topScale);
if (topEndIndex === -1)
topEndIndex = calc.topScaleItems.length - 1;
var bottomStartIndex = Math.max(calc.getScaleIndexByPos(left), 0);
var bottomEndIndex = calc.getScaleIndexByPos(right);
if (bottomEndIndex === -1)
bottomEndIndex = calc.bottomScaleItems.length - 1;
return [
[topStartIndex, topEndIndex],
[bottomStartIndex, bottomEndIndex]
];
};
GridLayoutCalculator.prototype.isScaleItemInsideNoWorkingInterval = function (scaleItemInfo, noWorkingIntervals) {
var scaleItemLeft = scaleItemInfo.position.x;
var scaleItemRight = scaleItemInfo.position.x + scaleItemInfo.size.width;
for (var i = 0; i < noWorkingIntervals.length; i++) {
var noWorkingIntervalLeft = noWorkingIntervals[i].position.x;
var noWorkingIntervalRight = noWorkingIntervals[i].position.x + noWorkingIntervals[i].size.width;
if (scaleItemLeft >= noWorkingIntervalLeft && scaleItemRight <= noWorkingIntervalRight)
return true;
}
return false;
};
GridLayoutCalculator.prototype.getScaleItemColSpan = function (scaleType) {
return this._scaleCalculator.getScaleItemColSpan(scaleType);
};
GridLayoutCalculator.prototype.getTaskWrapperElementInfo = function (index) {
var result = new GridElementInfo_1.GridElementInfo();
result.className = this.getTaskWrapperClassName(index);
result.setPosition(this.getTaskWrapperPoint(index));
result.setAttribute("task-index", index);
return result;
};
GridLayoutCalculator.prototype.getTaskWrapperClassName = function (index) {
var result = "dx-gantt-taskWrapper";
var viewItem = this.getViewItem(index);
if (viewItem.task.isMilestone() && !viewItem.isCustom)
result = "dx-gantt-milestoneWrapper";
if (viewItem.selected)
result += " dx-gantt-selectedTask";
return result;
};
GridLayoutCalculator.prototype.getTaskWrapperPoint = function (index) {
if (!(0, common_1.isDefined)(this._taskWrapperPoints[index])) {
var viewItem = this.getViewItem(index);
var height = this.getTaskHeight(index);
var y = index * this.tickSize.height + (this.tickSize.height - height) / 2;
var result = new point_1.Point(this.getPosByDate(viewItem.task.start), y);
if (viewItem.task.isMilestone() && !viewItem.isCustom)
result.x -= height / 2;
this._taskWrapperPoints[index] = result;
}
return this._taskWrapperPoints[index].clone();
};
GridLayoutCalculator.prototype.getTaskElementInfo = function (index, textOutsideTask) {
if (textOutsideTask === void 0) { textOutsideTask = false; }
if (!(0, common_1.isDefined)(this._taskElementInfoList[index])) {
var result = new GridElementInfo_1.GridElementInfo();
var task = this.getTask(index);
var autoCalculatedParent = this.viewModel.parentAutoCalc && this.viewModel.taskHasChildrenByIndex(index);
if (!task.isMilestone()) {
var defWidth = this.getTaskWidth(index);
result.size.width = this.getCorrectedTaskWidthByRange(index, defWidth);
if (result.size.width < defWidth)
result.additionalInfo["taskCut"] = true;
if (textOutsideTask)
result.size.height = this.getTaskHeight(index);
}
result.className = this.getTaskClassName(index, result.size.width);
if (task.color) {
result.style.backgroundColor = task.color;
if (autoCalculatedParent) {
result.style.borderLeftColor = task.color;
result.style.borderRightColor = task.color;
result.style.borderTopColor = task.color;
}
}
this._taskElementInfoList[index] = result;
}
return this._taskElementInfoList[index];
};
GridLayoutCalculator.prototype.getTaskClassName = function (index, taskWidth) {
var result = GridLayoutCalculator.taskClassName;
var viewItem = this.getViewItem(index);
var autoCalculatedParent = this.viewModel.parentAutoCalc && this.viewModel.taskHasChildrenByIndex(index);
if (viewItem.task.isMilestone() && !viewItem.isCustom)
result += " " + GridLayoutCalculator.milestoneClassName;
else {
if (taskWidth <= this.elementSizeValues.smallTaskWidth)
result += " " + GridLayoutCalculator.smallTaskClassName;
if (autoCalculatedParent)
result += this.getAutoCalcParentTaskClassName(viewItem.task);
}
return result;
};
GridLayoutCalculator.prototype.getAutoCalcParentTaskClassName = function (task) {
var result = " " + GridLayoutCalculator.parentTaskClassName;
if (task.progress == 0)
result += " dx-gantt-noPrg";
if (task.progress >= 100)
result += " dx-gantt-cmpl";
return result;
};
GridLayoutCalculator.prototype.getTaskPoint = function (index) {
var result = this.getTaskWrapperPoint(index);
if (!this.getTask(index).isMilestone())
result.y += this.elementSizeValues.taskWrapperTopPadding;
return result;
};
GridLayoutCalculator.prototype.getTaskSize = function (index) {
return new size_1.Size(this.getTaskWidth(index), this.getTaskHeight(index));
};
GridLayoutCalculator.prototype.getTaskWidth = function (index) {
var viewItem = this.getViewItem(index);
if (viewItem.isCustom && viewItem.size.width)
return viewItem.size.width;
return viewItem.task.isMilestone() && !viewItem.isCustom ? this.getTaskHeight(index) : Math.max(this.getWidthByDateRange(viewItem.task.start, viewItem.task.end), this.minTaskWidth);
};
GridLayoutCalculator.prototype.getTaskHeight = function (index) {
var viewItem = this.getViewItem(index);
if (viewItem.task.isMilestone() && !viewItem.isCustom)
return this.milestoneWidth;
if (this.viewModel.isTaskToCalculateByChildren(viewItem.task.id))
return this.parentTaskHeight;
return (viewItem.isCustom && viewItem.size.height) ? viewItem.size.height : this.taskHeight;
};
GridLayoutCalculator.prototype.getTask = function (index) {
var item = this.getViewItem(index);
return item === null || item === void 0 ? void 0 : item.task;
};
GridLayoutCalculator.prototype.getViewItem = function (index) {
return this.viewModel.items[index];
};
GridLayoutCalculator.prototype.getTaskProgressElementInfo = function (index) {
var result = new GridElementInfo_1.GridElementInfo();
result.className = GridLayoutCalculator.taskProgressClassName;
result.setSize(this.getTaskProgressSize(index));
return result;
};
GridLayoutCalculator.prototype.getTaskProgressSize = function (index) {
var width = this.getTaskProgressWidth(index);
if (this.isTaskCutByRange(index))
width = this.getCorrectedTaskWidthByRange(index, width);
return new size_1.Size(width, 0);
};
GridLayoutCalculator.prototype.getTaskProgressWidth = function (index) {
return this.getTaskWidth(index) * this.getTask(index).progress / 100;
};
GridLayoutCalculator.prototype.getTaskTextElementInfo = function (index, isInsideText) {
var result = new GridElementInfo_1.GridElementInfo();
result.className = this.getTaskTextElementClassName(isInsideText);
if (!isInsideText) {
var taskX = this.getTaskPoint(index).x;
if (taskX < this.elementSizeValues.outsideTaskTextDefaultWidth) {
result.size.width = taskX;
result.margins.left = -taskX;
}
}
return result;
};
GridLayoutCalculator.prototype.getTaskTextElementClassName = function (isInsideText) {
return GridLayoutCalculator.taskTitleClassName.concat(" ", isInsideText ? GridLayoutCalculator.titleInClassName : GridLayoutCalculator.titleOutClassName);
};
GridLayoutCalculator.prototype.getTaskResourcesWrapperElementInfo = function (index) {
var result = new GridElementInfo_1.GridElementInfo();
var width = this.getTaskSize(index).width;
result.className = "dx-gantt-taskResWrapper";
result.setPosition(this.getTaskWrapperPoint(index));
result.position.x = result.position.x + width;
return result;
};
GridLayoutCalculator.prototype.getTaskResourceElementInfo = function () {
var result = new GridElementInfo_1.GridElementInfo();
result.className = GridLayoutCalculator.taskResourceClassName;
return result;
};
GridLayoutCalculator.prototype.getSelectionElementInfo = function (index) {
return this.getRowElementInfo(index, "dx-gantt-sel");
};
GridLayoutCalculator.prototype.getSelectionPosition = function (index) {
var result = new point_1.Point(undefined, undefined);
result.y = index * this.tickSize.height;
return result;
};
GridLayoutCalculator.prototype.getSelectionSize = function () {
return new size_1.Size(this.getTotalWidth(), this.tickSize.height);
};
GridLayoutCalculator.prototype.getHighlightRowInfo = function (index) {
return this.getRowElementInfo(index, "dx-gantt-altRow");
};
GridLayoutCalculator.prototype.getRowElementInfo = function (index, className) {
var result = new GridElementInfo_1.GridElementInfo();
result.className = className;
result.setPosition(this.getSelectionPosition(index));
result.setSize(this.getSelectionSize());
return result;
};
GridLayoutCalculator.prototype.getNoWorkingIntervalInfo = function (noWorkingDateRange) {
var result = new GridElementInfo_1.GridElementInfo();
result.className = "dx-gantt-nwi";
result.setPosition(this.getNoWorkingIntervalPosition(noWorkingDateRange.start));
result.setSize(this.getNoWorkingIntervalSize(noWorkingDateRange));
return result;
};
GridLayoutCalculator.prototype.getNoWorkingIntervalPosition = function (intervalStart) {
var result = new point_1.Point(undefined, undefined);
result.x = this.getPosByDate(intervalStart);
return result;
};
GridLayoutCalculator.prototype.getNoWorkingIntervalSize = function (noWorkingInterval) {
return new size_1.Size(this.getWidthByDateRange(noWorkingInterval.start, noWorkingInterval.end), this.getVerticalGridLineHeight());
};
GridLayoutCalculator.prototype.getVerticalGridLineHeight = function () {
return Math.max(this.visibleTaskAreaSize.height - this.scrollBarHeight, this.tickSize.height * this.verticalTickCount);
};
GridLayoutCalculator.prototype.getConnectorInfo = function (id, predessorIndex, successorIndex, connectorType) {
var result = new Array();
var connectorPoints = this.getConnectorPoints(predessorIndex, successorIndex, connectorType);
for (var i = 0; i < connectorPoints.length - 1; i++)
result.push(this.getConnectorLineInfo(id, connectorPoints[i], connectorPoints[i + 1], i == 0 || i == connectorPoints.length - 2));
result.push(this.getArrowInfo(id, connectorPoints, result, predessorIndex, successorIndex));
this.checkAndCorrectConnectorLinesByRange(result);
return result.filter(function (c) { return !!c; });
};
GridLayoutCalculator.prototype.getConnectorLineInfo = function (id, startPoint, endPoint, isEdgeLine) {
var result = new GridElementInfo_1.GridElementInfo();
var isVertical = startPoint.x == endPoint.x;
result.className = this.getConnectorClassName(isVertical);
result.setPosition(this.getConnectorPosition(startPoint, endPoint));
result.setSize(this.getConnectorSize(startPoint, endPoint, isVertical, isEdgeLine));
result.setAttribute("dependency-id", id);
return result;
};
GridLayoutCalculator.prototype.getConnectorClassName = function (isVertical) {
return isVertical ? GridLayoutCalculator.CLASSNAMES.CONNECTOR_VERTICAL : GridLayoutCalculator.CLASSNAMES.CONNECTOR_HORIZONTAL;
};
GridLayoutCalculator.prototype.getConnectorPosition = function (startPoint, endPoint) {
return new point_1.Point(Math.min(startPoint.x, endPoint.x), Math.min(startPoint.y, endPoint.y));
};
GridLayoutCalculator.prototype.getConnectorSize = function (startPoint, endPoint, isVertical, isEdgeLine) {
var result = new size_1.Size(0, 0);
var sizeCorrection = isEdgeLine ? 0 : 1;
if (isVertical)
result.height = Math.abs(endPoint.y - startPoint.y) + sizeCorrection;
else
result.width = Math.abs(endPoint.x - startPoint.x) + sizeCorrection;
return result;
};
GridLayoutCalculator.prototype.getArrowInfo = function (id, connectorPoints, connectorLines, predessorIndex, successorIndex) {
var result = new GridElementInfo_1.GridElementInfo();
var lineInfo = this.findArrowLineInfo(connectorLines, predessorIndex, successorIndex);
var arrowPosition = this.getArrowPosition(connectorPoints, predessorIndex, successorIndex);
result.className = this.getArrowClassName(arrowPosition);
result.setPosition(this.getArrowPoint(lineInfo, arrowPosition));
result.setAttribute("dependency-id", id);
return result;
};
GridLayoutCalculator.prototype.findArrowLineInfo = function (connectorLines, predessorIndex, successorIndex) {
var arrowLineIndex = predessorIndex < successorIndex ? connectorLines.length - 1 : 0;
return connectorLines[arrowLineIndex];
};
GridLayoutCalculator.prototype.getArrowPosition = function (connectorPoints, predessorIndex, successorIndex) {
var prevLastPoint = connectorPoints[predessorIndex < successorIndex ? connectorPoints.length - 2 : 1];
var lastPoint = connectorPoints[predessorIndex < successorIndex ? connectorPoints.length - 1 : 0];
if (prevLastPoint.x == lastPoint.x)
return prevLastPoint.y > lastPoint.y ? Enums_1.Position.Top : Enums_1.Position.Bottom;
return prevLastPoint.x > lastPoint.x ? Enums_1.Position.Left : Enums_1.Position.Right;
};
GridLayoutCalculator.prototype.getArrowClassName = function (arrowPosition) {
var result = GridLayoutCalculator.arrowClassName;
switch (arrowPosition) {
case Enums_1.Position.Left:
result = result.concat(" ", GridLayoutCalculator.leftArrowClassName);
break;
case Enums_1.Position.Top:
result = result.concat(" ", GridLayoutCalculator.topArrowClassName);
break;
case Enums_1.Position.Right:
result = result.concat(" ", GridLayoutCalculator.rightArrowClassName);
break;
case Enums_1.Position.Bottom:
result = result.concat(" ", GridLayoutCalculator.bottomArrowClassName);
break;
}
return result;
};
GridLayoutCalculator.prototype.getArrowPositionByClassName = function (className) {
if (className.indexOf(GridLayoutCalculator.leftArrowClassName) > -1)
return Enums_1.Position.Left;
if (className.indexOf(GridLayoutCalculator.topArrowClassName) > -1)
return Enums_1.Position.Top;
if (className.indexOf(GridLayoutCalculator.rightArrowClassName) > -1)
return Enums_1.Position.Right;
if (className.indexOf(GridLayoutCalculator.bottomArrowClassName) > -1)
return Enums_1.Position.Bottom;
};
GridLayoutCalculator.prototype.getArrowPoint = function (lineInfo, arrowPosition) {
return new point_1.Point(this.getArrowX(lineInfo, arrowPosition), this.getArrowY(lineInfo, arrowPosition));
};
GridLayoutCalculator.prototype.getArrowX = function (lineInfo, arrowPosition) {
switch (arrowPosition) {
case Enums_1.Position.Left:
return lineInfo.position.x - this.arrowSize.width / 2;
case Enums_1.Position.Right:
return lineInfo.position.x + lineInfo.size.width - this.arrowSize.width / 2;
case Enums_1.Position.Top:
case Enums_1.Position.Bottom:
return lineInfo.position.x - (this.arrowSize.width - this.lineThickness) / 2;
}
};
GridLayoutCalculator.prototype.getArrowY = function (lineInfo, arrowPosition) {
switch (arrowPosition) {
case Enums_1.Position.Top:
return lineInfo.position.y - this.arrowSize.height / 2;
case Enums_1.Position.Bottom:
return lineInfo.position.y + lineInfo.size.height - this.arrowSize.height / 2;
case Enums_1.Position.Left:
case Enums_1.Position.Right:
return lineInfo.position.y - (this.arrowSize.height - this.lineThickness) / 2;
}
};
GridLayoutCalculator.prototype.getPosByDate = function (date) {
return this.getWidthByDateRange(this.range.start, date);
};
GridLayoutCalculator.prototype.getWidthByDateRange = function (start, end) {
return DateUtils_1.DateUtils.getRangeTickCount(start, end, this.viewType) * this.tickSize.width;
};
GridLayoutCalculator.prototype.getDateByPos = function (position) {
if (this.viewType === Enums_1.ViewType.Months || this.viewType === Enums_1.ViewType.Quarter)
return this.getDateByPosInMonthBasedViewTypes(position);
var preResult = position / this.tickSize.width;
var start = new Date(this.range.start);
var time = preResult * this.tickTimeSpan + start.getTime();
var delta = DateUtils_1.DateUtils.getDSTDelta(this.range.start, new Date(time));
return new Date(time - delta);
};
GridLayoutCalculator.prototype.getDateByPosInMonthBasedViewTypes = function (position) {
return this._scaleCalculator.getDateInScale(position);
};
GridLayoutCalculator.prototype.getConnectorPoints = function (predessorIndex, successorIndex, connectorType) {
switch (connectorType) {
case Enums_2.DependencyType.FS:
return this.getFinishToStartConnectorPoints(predessorIndex, successorIndex);
case Enums_2.DependencyType.SF:
return this.getStartToFinishConnectorPoints(predessorIndex, successorIndex);
case Enums_2.DependencyType.SS:
return this.getStartToStartConnectorPoints(predessorIndex, successorIndex);
case Enums_2.DependencyType.FF:
return this.getFinishToFinishConnectorPoints(predessorIndex, successorIndex);
default:
return new Array();
}
};
GridLayoutCalculator.prototype.getFinishToStartConnectorPoints = function (predessorIndex, successorIndex) {
if (predessorIndex < successorIndex) {
if (this.getTask(predessorIndex).end <= this.getTask(successorIndex).start)
return this.getConnectorPoints_FromTopTaskRightSide_ToBottomTaskTopSide(predessorIndex, successorIndex, false);
return this.getConnectorPoints_FromTopTaskRightSide_ToBottomTaskLeftSide(predessorIndex, successorIndex, false);
}
if (this.getTask(predessorIndex).end <= this.getTask(successorIndex).start)
return this.getConnectorPoints_FromTopTaskBottomSide_ToBottomTaskRightSide(successorIndex, predessorIndex, false);
return this.getConnectorPoints_FromTopTaskLeftSide_ToBottomTaskRightSide(successorIndex, predessorIndex, true);
};
GridLayoutCalculator.prototype.getFinishToFinishConnectorPoints = function (predessorIndex, successorIndex) {
if (predessorIndex < successorIndex)
return this.getConnectorPoints_FromTopTaskRightSide_ToBottomTaskRightSide(predessorIndex, successorIndex);
return this.getConnectorPoints_FromTopTaskRightSide_ToBottomTaskRightSide(successorIndex, predessorIndex);
};
GridLayoutCalculator.prototype.getStartToStartConnectorPoints = function (predessorIndex, successorIndex) {
if (predessorIndex < successorIndex)
return this.getConnectorPoints_FromTopTaskLeftSide_ToBottomTaskLeftSide(predessorIndex, successorIndex);
return this.getConnectorPoints_FromTopTaskLeftSide_ToBottomTaskLeftSide(successorIndex, predessorIndex);
};
GridLayoutCalculator.prototype.getStartToFinishConnectorPoints = function (predessorIndex, successorIndex) {
if (predessorIndex < successorIndex) {
if (this.getTask(predessorIndex).start >= this.getTask(successorIndex).end)
return this.getConnectorPoints_FromTopTaskLeftSide_ToBottomTaskTopSide(predessorIndex, successorIndex, true);
return this.getConnectorPoints_FromTopTaskLeftSide_ToBottomTaskRightSide(predessorIndex, successorIndex, false);
}
if (this.getTask(predessorIndex).start >= this.getTask(successorIndex).end)
return this.getConnectorPoints_FromTopTaskBottomSide_ToBottomTaskLeftSide(successorIndex, predessorIndex, true);
return this.getConnectorPoints_FromTopTaskRightSide_ToBottomTaskLeftSide(successorIndex, predessorIndex, true);
};
GridLayoutCalculator.prototype.getConnectorPoints_FromTopTaskRightSide_ToBottomTaskTopSide = function (topTaskIndex, bottomTaskIndex, shiftEndPointToRight) {
var result = new Array();
var topTaskPoint = this.getTaskPoint(topTaskIndex);
var bottomTaskPoint = this.getTaskPoint(bottomTaskIndex);
var topTaskRightCenter = this.getTaskRightCenter(topTaskPoint, topTaskIndex);
var isBottomMilestone = this.getTask(bottomTaskIndex).isMilestone();
var bottomTaskTopCenter = this.getTaskTopCenter(bottomTaskPoint, bottomTaskIndex);
var endPointIndent = shiftEndPointToRight ? this.getTaskWidth(bottomTaskIndex) - this.minLineLength : this.minLineLength;
result.push(new point_1.Point(Math.floor(topTaskRightCenter.x), Math.floor(topTaskRightCenter.y)));
result.push(new point_1.Point(Math.floor(isBottomMilestone ? bottomTaskTopCenter.x : bottomTaskPoint.x + endPointIndent), Math.floor(result[0].y)));
result.push(new point_1.Point(Math.floor(result[1].x), Math.floor(bottomTaskTopCenter.y)));
return result;
};
GridLayoutCalculator.prototype.getConnectorPoints_FromTopTaskRightSide_ToBottomTaskRightSide = function (topTaskIndex, bottomTaskIndex) {
var result = new Array();
var topTaskPoint = this.getTaskPoint(topTaskIndex);
var bottomTaskPoint = this.getTaskPoint(bottomTaskIndex);
var topTaskRightCenter = this.getTaskRightCenter(topTaskPoint, topTaskIndex);
var bottomTaskRightCenter = this.getTaskRightCenter(bottomTaskPoint, bottomTaskIndex);
result.push(new point_1.Point(Math.floor(topTaskRightCenter.x), Math.floor(topTaskRightCenter.y)));
result.push(new point_1.Point(Math.floor(Math.max(topTaskRightCenter.x, bottomTaskRightCenter.x) + this.minLineLength), Math.floor(result[0].y)));
result.push(new point_1.Point(Math.floor(result[1].x), Math.floor(bottomTaskRightCenter.y)));
result.push(new point_1.Point(Math.floor(bottomTaskRightCenter.x), Math.floor(bottomTaskRightCenter.y)));
return result;
};
GridLayoutCalculator.prototype.getConnectorPoints_FromTopTaskRightSide_ToBottomTaskLeftSide = function (topTaskIndex, bottomTaskIndex, shiftToTop) {
var result = new Array();
var topTaskPoint = this.getTaskPoint(topTaskIndex);
var bottomTaskPoint = this.getTaskPoint(bottomTaskIndex);
var topTaskRightCenter = this.getTaskRightCenter(topTaskPoint, topTaskIndex);
var topTaskBottomCenter = this.getTaskBottomCenter(topTaskPoint, topTaskIndex);
var bottomTaskLeftCenter = this.getTaskLeftCenter(bottomTaskPoint, bottomTaskIndex);
var bottomTaskTopCenter = this.getTaskTopCenter(bottomTaskPoint, bottomTaskIndex);
var viewItem = shiftToTop ? this.getViewItem(topTaskIndex) : this.getViewItem(bottomTaskIndex);
var connectorSpace = viewItem.isCustom ? (this.tickSize.height - viewItem.size.height) / 2 : this.minConnectorSpaceFromTask;
result.push(new point_1.Point(Math.floor(topTaskRightCenter.x), Math.floor(topTaskRightCenter.y)));
result.push(new point_1.Point(Math.floor(result[0].x + this.minLineLength), Math.floor(result[0].y)));
result.push(new point_1.Point(Math.floor(result[1].x), Math.floor(shiftToTop ?
topTaskBottomCenter.y + connectorSpace
: bottomTaskTopCenter.y - connectorSpace)));
result.push(new point_1.Point(Math.floor(bottomTaskLeftCenter.x - this.minLineLength), Math.floor(result[2].y)));
result.push(new point_1.Point(Math.floor(result[3].x), Math.floor(bottomTaskLeftCenter.y)));
result.push(new point_1.Point(Math.floor(bottomTaskLeftCenter.x), Math.floor(bottomTaskLeftCenter.y)));
return result;
};
GridLayoutCalculator.prototype.getConnectorPoints_FromTopTaskBottomSide_ToBottomTaskRightSide = function (topTaskIndex, bottomTaskIndex, shiftStartPointToRight) {
var result = new Array();
var topTaskPoint = this.getTaskPoint(topTaskIndex);
var bottomTaskPoint = this.getTaskPoint(bottomTaskIndex);
var topTaskBottomCenter = this.getTaskBottomCenter(topTaskPoint, topTaskIndex);
var isTopMilestone = this.getTask(topTaskIndex).isMilestone();
var bottomTaskRightCenter = this.getTaskRightCenter(bottomTaskPoint, bottomTaskIndex);
var startPointIndent = shiftStartPointToRight ? this.getTaskWidth(topTaskIndex) - this.minLineLength : this.minLineLength;
result.push(new point_1.Point(Math.floor(isTopMilestone ? topTaskBottomCenter.x : topTaskPoint.x + startPointIndent), Math.floor(topTaskBottomCenter.y)));
result.push(new point_1.Point(Math.floor(result[0].x), Math.floor(bottomTaskRightCenter.y)));
result.push(new point_1.Point(Math.floor(bottomTaskRightCenter.x), Math.floor(bottomTaskRightCenter.y)));
return result;
};
GridLayoutCalculator.prototype.getConnectorPoints_FromTopTaskBottomSide_ToBottomTaskLeftSide = function (topTaskIndex, bottomTaskIndex, shiftStartPointToRight) {
var result = new Array();
var topTaskPoint = this.getTaskPoint(topTaskIndex);
var bottomTaskPoint = this.getTaskPoint(bottomTaskIndex);
var topTaskBottomCenter = this.getTaskBottomCenter(topTaskPoint, topTaskIndex);
var isTopMilestone = this.getTask(topTaskIndex).isMilestone();
var bottomTaskLeftCenter = this.getTaskLeftCenter(bottomTaskPoint, bottomTaskIndex);
var startPointIndent = shiftStartPointToRight ? this.getTaskWidth(topTaskIndex) - this.minLineLength : this.minLineLength;
result.push(new point_1.Point(Math.floor(isTopMilestone ? topTaskBottomCenter.x : topTaskPoint.x + startPointIndent), Math.floor(topTaskBottomCenter.y)));
result.push(new point_1.Point(Math.floor(result[0].x), Math.floor(bottomTaskLeftCenter.y)));
result.push(new point_1.Point(Math.floor(bottomTaskLeftCenter.x), Math.floor(bottomTaskLeftCenter.y)));
return result;
};
GridLayoutCalculator.prototype.getConnectorPoints_FromTopTaskLeftSide_ToBottomTaskTopSide = function (topTaskIndex, bottomTaskIndex, shiftEndPointToRight) {
var result = new Array();
var topTaskPoint = this.getTaskPoint(topTaskIndex);
var bottomTaskPoint = this.getTaskPoint(bottomTaskIndex);
var topTaskLeftCenter = this.getTaskLeftCenter(topTaskPoint, topTaskIndex);
var bottomTaskTopCenter = this.getTaskTopCenter(bottomTaskPoint, bottomTaskIndex);
var isBottomMilestone = this.getTask(bottomTaskIndex).isMilestone();
var endPointIndent = shiftEndPointToRight ? this.getTaskWidth(bottomTaskIndex) - this.minLineLength : this.minLineLength;
result.push(new point_1.Point(Math.floor(topTaskLeftCenter.x), Math.floor(topTaskLeftCenter.y)));
result.push(new point_1.Point(Math.floor(isBottomMilestone ? bottomTaskTopCenter.x : bottomTaskPoint.x + endPointIndent), Math.floor(result[0].y)));
result.push(new point_1.Point(Math.floor(result[1].x), Math.floor(bottomTaskTopCenter.y)));
return result;
};
GridLayoutCalculator.prototype.getConnectorPoints_FromTopTaskLeftSide_ToBottomTaskRightSide = function (topTaskIndex, bottomTaskIndex, shiftToTop) {
var result = new Array();
var topTaskPoint = this.getTaskPoint(topTaskIndex);
var bottomTaskPoint = this.getTaskPoint(bottomTaskIndex);
var topTaskLeftCenter = this.getTaskLeftCenter(topTaskPoint, topTaskIndex);
var topTaskBottomCenter = this.getTaskBottomCenter(topTaskPoint, topTaskIndex);
var bottomTaskRightCenter = this.getTaskRightCenter(bottomTaskPoint, bottomTaskIndex);
var bottomTaskTopCenter = this.getTaskTopCenter(bottomTaskPoint, bottomTaskIndex);
var viewItem = shiftToTop ? this.getViewItem(topTaskIndex) : this.getViewItem(bottomTaskIndex);
var connectorSpace = viewItem.isCustom ? (this.tickSize.height - viewItem.size.height) / 2 : this.minConnectorSpaceFromTask;
result.push(new point_1.Point(Math.floor(topTaskLeftCenter.x), topTaskLeftCenter.y));
result.push(new point_1.Point(Math.floor(result[0].x - this.minLineLength), result[0].y));
result.push(new point_1.Point(Math.floor(result[1].x), Math.floor(shiftToTop ?
topTaskBottomCenter.y + connectorSpace
: bottomTaskTopCenter.y - connectorSpace)));
result.push(new point_1.Point(Math.floor(bottomTaskRightCenter.x + this.minLineLength), Math.floor(result[2].y)));
result.push(new point_1.Point(Math.floor(result[3].x), Math.floor(bottomTaskRightCenter.y)));
result.push(new point_1.Point(Math.floor(bottomTaskRightCenter.x), Math.floor(bottomTaskRightCenter.y)));
return result;
};
GridLayoutCalculator.prototype.getConnectorPoints_FromTopTaskLeftSide_ToBottomTaskLeftSide = function (topTaskIndex, bottomTaskIndex) {
var result = new Array();
var topTaskPoint = this.getTaskPoint(topTaskIndex);
var bottomTaskPoint = this.getTaskPoint(bottomTaskIndex);
var topTaskLeftCenter = this.getTaskLeftCenter(topTaskPoint, topTaskIndex);
var bottomTaskLeftCenter = this.getTaskLeftCenter(bottomTaskPoint, bottomTaskIndex);
result.push(new point_1.Point(Math.floor(topTaskLeftCenter.x), Math.floor(topTaskLeftCenter.y)));
result.push(new point_1.Point(Math.floor(Math.min(topTaskLeftCenter.x, bottomTaskLeftCenter.x) - this.minLineLength), Math.floor(result[0].y)));
result.push(new point_1.Point(Math.floor(result[1].x), Math.floor(bottomTaskLeftCenter.y)));
result.push(new point_1.Point(Math.floor(bottomTaskLeftCenter.x), Math.floor(bottomTaskLeftCenter.y)));
return result;
};
GridLayoutCalculator.prototype.getTaskSidePoints = function (index) {
var point = this.getTaskPoint(index);
return [
this.getTaskLeftCenter(point, index),
this.getTaskTopCenter(point, index),
this.getTaskRightCenter(point, index),
this.getTaskBottomCenter(point, index)
];
};
GridLayoutCalculator.prototype.getTaskLeftCenter = function (taskPoint, index) {
return new point_1.Point(taskPoint.x - this.getTaskEdgeCorrection(index), taskPoint.y + this.getTaskHeight(index) / 2);
};
GridLayoutCalculator.prototype.getTaskRightCenter = function (taskPoint, index) {
return new point_1.Point(taskPoint.x + this.getTaskWidth(index) + this.getTaskEdgeCorrection(index), taskPoint.y + this.getTaskHeight(index) / 2);
};
GridLayoutCalculator.prototype.getTaskTopCenter = function (taskPoint, index) {
return new point_1.Point(taskPoint.x + this.getTaskWidth(index) / 2, taskPoint.y - this.getTaskEdgeCorrection(index));
};
GridLayoutCalculator.prototype.getTaskBottomCenter = function (taskPoint, index) {
return new point_1.Point(taskPoint.x + this.getTaskWidth(index) / 2, taskPoint.y + this.getTaskHeight(index) + this.getTaskEdgeCorrection(index));
};
GridLayoutCalculator.prototype.getTaskEdgeCorrection = function (index) {
var viewItem = this.getViewItem(index);
var isMilestone = viewItem.task.isMilestone() && !viewItem.isCustom;
return isMilestone ? this.getTaskHeight(index) * (Math.sqrt(2) - 1) / 2 : 0;
};
GridLayoutCalculator.prototype.getRenderedRowColumnIndices = function (scrollPos, isVertical) {
var visibleAreaSizeValue = isVertical ? this.visibleTaskAreaSize.height : this.visibleTaskAreaSize.width;
var firstVisibleIndex = isVertical ? this.getFirstVisibleGridCellIndex(scrollPos, this.tickSize.height) : this.getFirstScaleVisibleIndex(scrollPos);
var lastVisibleIndex = isVertical ? this.getLastVisibleGridCellIndex(scrollPos, this.tickSize.height, visibleAreaSizeValue, this.verticalTickCount) : this.getLastScaleVisibleIndex(scrollPos);
var result = new Array();
for (var i = firstVisibleIndex; i <= lastVisibleIndex; i++)
result.push(i);
return result;
};
GridLayoutCalculator.prototype.getRenderedScaleItemIndices = function (scaleType, renderedColIndices) {
var scaleItemColSpan = this.getScaleItemColSpan(scaleType);
var firstVisibleIndex = Math.floor(renderedColIndices[0] / scaleItemColSpan);
var lastVisibleIndex = Math.floor(renderedColIndices[renderedColIndices.length - 1] / scaleItemColSpan);
var result = new Array();
for (var i = firstVisibleIndex; i <= lastVisibleIndex; i++)
result.push(i);
return result;
};
GridLayoutCalculator.prototype.getFirstScaleVisibleIndex = function (scrollPos) {
return this._scaleCalculator.getFirstScaleIndexForRender(scrollPos);
};
GridLayoutCalculator.prototype.getLastScaleVisibleIndex = function (scrollPos) {
return this._scaleCalculator.getLastScaleIndexForRender(scrollPos + this.visibleTaskAreaSize.width);
};
GridLayoutCalculator.prototype.getFirstVisibleGridCellIndex = function (scrollPos, tickSizeValue) {
var result = Math.floor(scrollPos / tickSizeValue);
result = Math.max(result - 10, 0);
return result;
};
GridLayoutCalculator.prototype.getLastVisibleGridCellIndex = function (scrollPos, tickSizeValue, visibleAreaSizeValue, tickCount) {
var result = Math.floor((scrollPos + visibleAreaSizeValue) / tickSizeValue);
result = Math.min(result + 10, tickCount - 1);
return result;
};
GridLayoutCalculator.prototype.createTileToConnectorLinesMap = function () {
this.tileToDependencyMap = [];
for (var i = 0; i < this.viewModel.items.length; i++)
for (var j = 0; j < this.viewModel.items[i].dependencies.length; j++)
this.createConnecotInfo(this.viewModel.items[i].dependencies[j], this.viewModel.items[i].visibleIndex);
};
GridLayoutCalculator.prototype.updateTileToConnectorLinesMap = function (dependencyId) {
this.tileToDependencyMap.forEach(function (map, index, tileToDependencyMap) {
tileToDependencyMap[index] = map.filter(function (info) { return info.attr["dependency-id"] != dependencyId; });
});
var result = [];
var item = this.viewModel.items.filter(function (item) { return item.dependencies.filter(function (d) { return d.id == dependencyId; }).length > 0; })[0];
if (item) {
var dependency = item.dependencies.filter(function (d) { return d.id === dependencyId; })[0];
result = this.createConnecotInfo(dependency, item.visibleIndex);
}
return result;
};
GridLayoutCalculator.prototype.createConnecotInfo = function (dependencyInfo, successorIndex) {
var _this = this;
var predessorIndex = dependencyInfo.predecessor.visibleIndex;
var type = dependencyInfo.type;
var id = dependencyInfo.id;
var connectorInfo = this.getConnectorInfo(id, predessorIndex, successorIndex, type);
connectorInfo.forEach(function (connectorLine) {
_this.addElementInfoToTileMap(connectorLine, _this.tileToDependencyMap, true);
});
return connectorInfo;
};
GridLayoutCalculator.prototype.createTileToNonWorkingIntervalsMap = function () {
this.tileToNoWorkingIntervalsMap = [];
for (var i = 0; i < this.viewModel.noWorkingIntervals.length; i++) {
var noWorkingDateRange = this.getAdjustedNoWorkingInterval(this.viewModel.noWorkingIntervals[i]);
if (!noWorkingDateRange)
continue;
var noWorkingIntervalInfo = this.getNoWorkingIntervalInfo(noWorkingDateRange);
this.addElementInfoToTileMap(noWorkingIntervalInfo, this.tileToNoWorkingIntervalsMap, false);
}
};
GridLayoutCalculator.prototype.getAdjustedNoWorkingInterval = function (modelInterval) {
if (modelInterval.end.getTime() - modelInterval.start.getTime() < this.tickTimeSpan - 1)
return null;
return new DateRange_1.DateRange(DateUtils_1.DateUtils.getNearestScaleTickDate(modelInterval.start, this.range, this.tickTimeSpan, this.viewType), DateUtils_1.DateUtils.getNearestScaleTickDate(modelInterval.end, this.range, this.tickTimeSpan, this.viewType));
};
GridLayoutCalculator.prototype.addElementInfoToTileMap = function (info, map, isVerticalTile) {
var infoPointValue = isVerticalTile ? info.position.y : info.position.x;
var infoSizeValue = isVerticalTile ? info.size.height : info.size.width;
var tileSizeValue = (isVerticalTile ? this.visibleTaskAreaSize.height : this.visibleTaskAreaSize.width) * 2;
if (tileSizeValue > 0) {
var firstTileIndex = Math.floor(infoPointValue / tileSizeValue);
var lastTileIndex = Math.floor((infoPointValue + infoSizeValue) / tileSizeValue);
for (var i = firstTileIndex; i <= lastTileIndex; i++) {
if (!map[i])
map[i] = new Array();
map[i].push(info);
}
}
};
GridLayoutCalculator.prototype.getRenderedConnectorLines = function (scrollPos) {
return this.getElementsInRenderedTiles(this.tileToDependencyMap, true, scrollPos);
};
GridLayoutCalculator.prototype.getRenderedNoWorkingIntervals = function (scrollPos) {
return this.getElementsInRenderedTiles(this.tileToNoWorkingIntervalsMap, false, scrollPos);
};
GridLayoutCalculator.prototype.getRenderedStripLines = function (settings) {
var result = new Array();
var stripLines = settings.stripLines.map(function (t) { return t.clone(); });
if (settings.showCurrentTime)
stripLines.push(new StripLine_1.StripLine(new Date(), null, settings.currentTimeTitle, settings.currentTimeCssClass, true));
for (var i = 0, stripLine = void 0; stripLine = stripLines[i]; i++) {
var start = DateUtils_1.DateUtils.parse(stripLine.start);
var end = stripLine.end ? DateUtils_1.DateUtils.parse(stripLine.end) : null;
if (start >= this.range.start && start <= this.range.end || (end && end >= this.range.start && end <= this.range.end)) {
var renderedStart = start > this.range.start ? start : this.range.start;
var info = new GridElementInfo_1.GridElementInfo();
info.size.height = this.getVerticalGridLineHeight();
info.position.x = this.getPosByDate(renderedStart);
info.size.width = end ? this.getWidthByDateRange(renderedStart, end < this.range.end ? end : this.range.end) : 0;
info.className = stripLine.isCurrent ? "dx-gantt-tc" : end ? "dx-gantt-ti" : "dx-gantt-tm";
info.className += stripLine.cssClass ? " " + stripLine.cssClass : "";
info.attr.title = stripLine.title;
result.push(info);
}
}
return result;
};
GridLayoutCalculator.prototype.getElementsInRenderedTiles = function (map, isVerticalTile, scrollPos) {
var result = new Array();
var visibleAreaSizeValue = isVerticalTile ? this.visibleTaskAreaSize.height : this.visibleTaskAreaSize.width;
if (visibleAreaSizeValue > 0) {
var firstVisibleTileIndex = Math.floor(scrollPos / (visibleAreaSizeValue * 2));
var lastVisibleTileIndex = Math.floor((scrollPos + visibleAreaSizeValue) / (visibleAreaSizeValue * 2));
for (var i = firstVisibleTileIndex; i <= lastVisibleTileIndex; i++) {
if (!map[i])
continue;
map[i].forEach(function (info) {
if (result.indexOf(info) === -1)
result.push(info);
});
}
}
return result;
};
GridLayoutCalculator.prototype.isTaskInRenderedRange = function (index) {
var item = this.getViewItem(index);
var point = this.getTaskPoint(index);
if (!item.task.isMilestone())
return point.x < this.getTotalWidth();
else
return point.x + this.getTaskWidth(index) < this.getTotalWidth();
};
GridLayoutCalculator.prototype.isTaskCutByRange = function (index) {
var info = this.getTaskElementInfo(index);
return !!info.additionalInfo["taskCut"];
};
GridLayoutCalculator.prototype.checkAndCorrectElementDisplayByRange = function (element) {
var side = element.parentElement.offsetLeft + element.offsetLeft + element.offsetWidth;
if (side > this.getTotalWidth())
element.style.display = "none";
};
GridLayoutCalculator.prototype.checkAndCorrectArrowElementDisplayByRange = function (element) {
var side = element.offsetLeft + element.offsetWidth;
if (side > this.getTotalWidth())
element.style.display = "none";
};
GridLayoutCalculator.prototype.checkAndCorrectConnectorLinesByRange = function (lines) {
if (!(lines === null || lines === void 0 ? void 0 : lines.length))
return;
var totalWidth = this.getTotalWidth();
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
var isVertical = !line.size.width;
if (line.position.x > totalWidth)
delete lines[i];
else if (!isVertical && line.position.x + line.size.width > totalWidth)
line.size.width = totalWidth - line.position.x;
}
};
GridLayoutCalculator.prototype.getCorrectedTaskWidthByRange = function (index, width) {
var limitWidth = this.getTotalWidth() - this.getTaskPoint(index).x;
return Math.min(limitWidth, width);
};
GridLayoutCalculator.dxGanttPrefix = "dx-gantt-";
GridLayoutCalculator.taskClassName = GridLayoutCalculator.dxGanttPrefix + "task";
GridLayoutCalculator.milestoneClassName = GridLayoutCalculator.dxGanttPrefix + "milestone";
GridLayoutCalculator.smallTaskClassName = GridLayoutCalculator.dxGanttPrefix + "smallTask";
GridLayoutCalculator.parentTaskClassName = GridLayoutCalculator.dxGanttPrefix + "parent";
GridLayoutCalculator.taskProgressClassName = GridLayoutCalculator.dxGanttPrefix + "tPrg";
GridLayoutCalculator.taskTitleClassName = GridLayoutCalculator.dxGanttPrefix + "taskTitle";
GridLayoutCalculator.titleInClassName = GridLayoutCalculator.dxGanttPrefix + "titleIn";
GridLayoutCalculator.titleOutClassName = GridLayoutCalculator.dxGanttPrefix + "titleOut";
GridLayoutCalculator.taskResourceClassName = GridLayoutCalculator.dxGanttPrefix + "taskRes";
GridLayoutCalculator.arrowClassName = GridLayoutCalculator.dxGanttPrefix + "arrow";
GridLayoutCalculator.leftArrowClassName = GridLayoutCalculator.dxGanttPrefix + "LA";
GridLayoutCalculator.topArrowClassName = GridLayoutCalculator.dxGanttPrefix + "TA";
GridLayoutCalculator.rightArrowClassName = GridLayoutCalculator.dxGanttPrefix + "RA";
GridLayoutCalculator.bottomArrowClassName = GridLayoutCalculator.dxGanttPrefix + "BA";
GridLayoutCalculator.CLASSNAMES = {
CONNECTOR_VERTICAL: "dx-gantt-conn-v",
CONNECTOR_HORIZONTAL: "dx-gantt-conn-h"
};
return GridLayoutCalculator;
}());
exports.GridLayoutCalculator = GridLayoutCalculator;
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Color = void 0;
var common_1 = __webpack_require__(1);
var Color = (function () {
function Color(color) {
this._num = null;
this._opacity = 1;
this._rgb = null;
this.assign(color);
}
Object.defineProperty(Color.prototype, "opacity", {
get: function () {
return this._opacity;
},
enumerable: false,
configurable: true
});
Color.prototype.hasValue = function () {
return (0, common_1.isDefined)(this._num) || !!this._rgb || this._opacity === 0;
};
Color.prototype.getValue = function () {
if (this._opacity === 0 && !this._rgb)
return false;
if ((0, common_1.isDefined)(this._num))
return this._num;
if (this._rgb)
return this.getRBGColor();
return null;
};
Color.prototype.assign = function (source) {
this.reset();
if (typeof source === "string")
this.assignFromString(source);
if (typeof source === "number")
this._num = source;
if (source instanceof Array)
this.assignFromRgbArray(source);
if (source instanceof Color)
this.assignFromColor(source);
};
Color.prototype.reset = function () {
this._opacity = 1;
this._num = null;
this._rgb = null;
};
Color.prototype.assignFromString = function (color) {
if (!color)
return;
if (color === "transparent")
this._opacity = 0;
if (color.indexOf("#") === 0)
this.assignFromHexString(color);
if (color.substr(0, 3).toLowerCase() === "rgb")
this.assignFromRgbString(color);
};
Color.prototype.assignFromHexString = function (hex) {
if (hex.length === 4)
hex = "#" + hex[1].repeat(2) + hex[2].repeat(2) + hex[3].repeat(2);
if (hex.length > 6) {
var r = parseInt(hex.substr(1, 2), 16);
var g = parseInt(hex.substr(3, 2), 16);
var b = parseInt(hex.substr(5, 2), 16);
this._rgb = [r, g, b];
}
};
Color.prototype.assignFromRgbString = function (rgb) {
var isRGBA = rgb.substr(0, 4).toLowerCase() === "rgba";
var regResult = rgb.toLowerCase().match(isRGBA ? Color.rgbaRegexp : Color.rgbRegexp);
if (regResult) {
var r = parseInt(regResult[1]);
var g = parseInt(regResult[2]);
var b = parseInt(regResult[3]);
this._rgb = [r, g, b];
if (isRGBA)
this._opacity = parseFloat(regResult[4]);
}
};
Color.prototype.assignFromRgbArray = function (rgb) {
if (rgb && rgb.length > 2) {
this._rgb = [rgb[0], rgb[1], rgb[2]];
if ((0, common_1.isDefined)(rgb[3]))
this._opacity = rgb[3];
}
};
Color.prototype.assignFromColor = function (source) {
this._opacity = source._opacity;
this._num = source._num;
this._rgb = source._rgb;
};
Color.prototype.getRBGColor = function () {
return this._rgb ? this._rgb : [0, 0, 0];
};
Color.prototype.applyOpacityToBackground = function (source) {
if (this._opacity === 1)
return;
var background = source instanceof Color ? source : new Color(source);
var backRGB = background.getValue();
if (backRGB instanceof Array) {
var alpha = this.opacity;
var r = Math.round((1 - alpha) * backRGB[0] + alpha * this._rgb[0]);
var g = Math.round((1 - alpha) * backRGB[1] + alpha * this._rgb[1]);
var b = Math.round((1 - alpha) * backRGB[2] + alpha * this._rgb[2]);
this._rgb = [r, g, b];
}
};
Color.rgbRegexp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/;
Color.rgbaRegexp = /rgba?\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*,?\s*([0-9]*\.?[0-9]*)\s*\)/;
return Color;
}());
exports.Color = Color;
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseManipulator = void 0;
var BaseManipulator = (function () {
function BaseManipulator(viewModel, dispatcher) {
this.viewModel = viewModel;
this.dispatcher = dispatcher;
}
BaseManipulator.prototype.getErrorCallback = function () {
return this.viewModel.getDataUpdateErrorCallback();
};
Object.defineProperty(BaseManipulator.prototype, "renderHelper", {
get: function () {
return this.viewModel.owner.renderHelper;
},
enumerable: false,
configurable: true
});
return BaseManipulator;
}());
exports.BaseManipulator = BaseManipulator;
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskPropertyManipulator = void 0;
var tslib_1 = __webpack_require__(0);
var HistoryItemState_1 = __webpack_require__(80);
var BaseManipulator_1 = __webpack_require__(18);
var TaskPropertyManipulator = (function (_super) {
(0, tslib_1.__extends)(TaskPropertyManipulator, _super);
function TaskPropertyManipulator() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskPropertyManipulator.prototype.setValue = function (id, newValue) {
var task = this.viewModel.tasks.getItemById(id);
var oldState = new HistoryItemState_1.HistoryItemState(id, this.getPropertyValue(task));
this.setPropertyValue(task, newValue);
var viewItem = this.viewModel.findItem(id);
if (viewItem)
this.renderHelper.recreateTaskElement(viewItem.visibleIndex);
return oldState;
};
TaskPropertyManipulator.prototype.restoreValue = function (state) {
if (!state)
return;
var task = this.viewModel.tasks.getItemById(state.id);
this.setPropertyValue(task, state.value);
var viewItem = this.viewModel.findItem(state.id);
if (viewItem)
this.renderHelper.recreateTaskElement(viewItem.visibleIndex);
};
return TaskPropertyManipulator;
}(BaseManipulator_1.BaseManipulator));
exports.TaskPropertyManipulator = TaskPropertyManipulator;
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DataObject = void 0;
var common_1 = __webpack_require__(1);
var math_1 = __webpack_require__(57);
var DataObject = (function () {
function DataObject() {
this.internalId = math_1.MathUtils.generateGuid();
}
DataObject.prototype.assignFromObject = function (sourceObj) {
if (!(0, common_1.isDefined)(sourceObj))
return;
if ((0, common_1.isDefined)(sourceObj.id)) {
this.id = sourceObj.id;
this.internalId = String(sourceObj.id);
}
};
return DataObject;
}());
exports.DataObject = DataObject;
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DateUtils = void 0;
var Enums_1 = __webpack_require__(2);
var DateUtils = (function () {
function DateUtils() {
}
DateUtils.getDaysInQuarter = function (start) {
var month = Math.floor(start.getMonth() / 3) * 3;
var quarterMonths = [month, month + 1, month + 2];
return quarterMonths.reduce(function (acc, m) { return acc += DateUtils.getDaysInMonth(m, start.getFullYear()); }, 0);
};
DateUtils.getDaysInMonth = function (month, year) {
var d = new Date(year, month + 1, 0);
return d.getDate();
};
DateUtils.getOffsetInMonths = function (start, end) {
return (end.getFullYear() - start.getFullYear()) * 12 + end.getMonth() - start.getMonth();
};
DateUtils.getOffsetInQuarters = function (start, end) {
return (end.getFullYear() - start.getFullYear()) * 4 + Math.floor(end.getMonth() / 3) - Math.floor(start.getMonth() / 3);
};
DateUtils.getNearestScaleTickDate = function (date, range, tickTimeSpan, viewType) {
var result = new Date();
var rangeStartTime = range.start.getTime();
var rangeEndTime = range.end.getTime();
result.setTime(date.getTime());
if (date.getTime() < rangeStartTime)
result.setTime(rangeStartTime);
else if (date.getTime() > rangeEndTime)
result.setTime(rangeEndTime);
else if (this.needCorrectDate(date, rangeStartTime, tickTimeSpan, viewType)) {
var nearestLeftTickTime = this.getNearestLeftTickTime(date, rangeStartTime, tickTimeSpan, viewType);
var nearestRightTickTime = this.getNextTickTime(nearestLeftTickTime, tickTimeSpan, viewType);
if (Math.abs(date.getTime() - nearestLeftTickTime) > Math.abs(date.getTime() - nearestRightTickTime))
result.setTime(nearestRightTickTime);
else
result.setTime(nearestLeftTickTime);
}
return result;
};
DateUtils.needCorrectDate = function (date, rangeStartTime, tickTimeSpan, viewType) {
if (viewType == Enums_1.ViewType.Months)
return date.getTime() !== new Date(date.getFullYear(), date.getMonth(), 1).getTime();
return (date.getTime() - rangeStartTime) % tickTimeSpan !== 0;
};
DateUtils.getNearestLeftTickTime = function (date, rangeStartTime, tickTimeSpan, viewType) {
if (viewType == Enums_1.ViewType.Months)
return new Date(date.getFullYear(), date.getMonth(), 1).getTime();
var tickCountAtLeft = Math.floor((date.getTime() - rangeStartTime) / tickTimeSpan);
return rangeStartTime + tickCountAtLeft * tickTimeSpan;
};
DateUtils.getNextTickTime = function (currentTickTime, tickTimeSpan, viewType) {
if (viewType == Enums_1.ViewType.Months) {
var nextTickDate = new Date();
nextTickDate.setTime(currentTickTime);
nextTickDate.setMonth(nextTickDate.getMonth() + 1);
return nextTickDate.getTime();
}
return currentTickTime + tickTimeSpan;
};
DateUtils.adjustStartDateByViewType = function (date, viewType, firstDayOfWeek) {
if (firstDayOfWeek === void 0) { firstDayOfWeek = 0; }
switch (viewType) {
case Enums_1.ViewType.TenMinutes:
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours());
case Enums_1.ViewType.SixHours:
case Enums_1.ViewType.Hours:
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
case Enums_1.ViewType.Days:
case Enums_1.ViewType.Weeks:
return new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + firstDayOfWeek);
case Enums_1.ViewType.Months:
case Enums_1.ViewType.Quarter:
case Enums_1.ViewType.Years:
return new Date(date.getFullYear(), 0, 1);
default:
return new Date();
}
};
DateUtils.adjustEndDateByViewType = function (date, viewType, firstDayOfWeek) {
if (firstDayOfWeek === void 0) { firstDayOfWeek = 0; }
switch (viewType) {
case Enums_1.ViewType.TenMinutes:
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours() + 1);
case Enums_1.ViewType.SixHours:
case Enums_1.ViewType.Hours:
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
case Enums_1.ViewType.Days:
case Enums_1.ViewType.Weeks:
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 7 - date.getDay() + firstDayOfWeek);
case Enums_1.ViewType.Months:
case Enums_1.ViewType.Quarter:
case Enums_1.ViewType.Years:
return new Date(date.getFullYear() + 1, 0, 1);
default:
return new Date();
}
};
DateUtils.roundStartDate = function (date, viewType) {
switch (viewType) {
case Enums_1.ViewType.TenMinutes:
case Enums_1.ViewType.Hours:
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours() - 1);
case Enums_1.ViewType.SixHours:
case Enums_1.ViewType.Days:
return new Date(date.getFullYear(), date.getMonth(), date.getDate() - 1);
case Enums_1.ViewType.Weeks:
return new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
case Enums_1.ViewType.Months:
return new Date(date.getFullYear(), date.getMonth() - 1);
case Enums_1.ViewType.Quarter:
case Enums_1.ViewType.Years:
return new Date(date.getFullYear() - 1, 0, 1);
default:
return new Date();
}
};
DateUtils.getTickTimeSpan = function (viewType) {
switch (viewType) {
case Enums_1.ViewType.TenMinutes:
return DateUtils.msPerHour / 6;
case Enums_1.ViewType.Hours:
return DateUtils.msPerHour;
case Enums_1.ViewType.SixHours:
return DateUtils.msPerHour * 6;
case Enums_1.ViewType.Days:
return DateUtils.msPerDay;
case Enums_1.ViewType.Weeks:
return DateUtils.msPerWeek;
case Enums_1.ViewType.Months:
return DateUtils.msPerMonth;
case Enums_1.ViewType.Quarter:
return DateUtils.msPerMonth * 3;
case Enums_1.ViewType.Years:
return DateUtils.msPerYear;
}
};
DateUtils.getRangeTickCount = function (start, end, scaleType) {
if (scaleType === Enums_1.ViewType.Months)
return this.getRangeTickCountInMonthsViewType(start, end);
if (scaleType === Enums_1.ViewType.Quarter)
return this.getRangeTickCountInQuarterViewType(start, end);
return (end.getTime() + DateUtils.getDSTDelta(start, end) - start.getTime()) / DateUtils.getTickTimeSpan(scaleType);
};
DateUtils.getRangeTickCountInMonthsViewType = function (start, end) {
var startMonthStartDate = new Date(start.getFullYear(), start.getMonth(), 1);
var endMonthStartDate = new Date(end.getFullYear(), end.getMonth(), 1);
var monthOffset = DateUtils.getOffsetInMonths(startMonthStartDate, endMonthStartDate);
var endFromMonthStartDateOffset = end.getTime() - endMonthStartDate.getTime();
var msInEndMonth = DateUtils.getDaysInMonth(end.getMonth(), end.getFullYear()) * DateUtils.msPerDay;
var startFromMonthStartDateOffset = start.getTime() - startMonthStartDate.getTime();
var msInStartMonth = DateUtils.getDaysInMonth(start.getMonth(), start.getFullYear()) * DateUtils.msPerDay;
return monthOffset + endFromMonthStartDateOffset / msInEndMonth - startFromMonthStartDateOffset / msInStartMonth;
};
DateUtils.getRangeTickCountInQuarterViewType = function (start, end) {
var startQuarterStartDate = new Date(start.getFullYear(), Math.floor(start.getMonth() / 3) * 3, 1);
var endQuarterStartDate = new Date(end.getFullYear(), Math.floor(end.getMonth() / 3) * 3, 1);
var quarterOffset = DateUtils.getOffsetInQuarters(startQuarterStartDate, endQuarterStartDate);
var endFromQuarterStartDateOffset = end.getTime() - endQuarterStartDate.getTime();
var msInEndQuarter = DateUtils.getDaysInQuarter(endQuarterStartDate) * DateUtils.msPerDay;
var startFromQuarterStartDateOffset = start.getTime() - startQuarterStartDate.getTime();
var msInStartQuarter = DateUtils.getDaysInQuarter(startQuarterStartDate) * DateUtils.msPerDay;
return quarterOffset + endFromQuarterStartDateOffset / msInEndQuarter - startFromQuarterStartDateOffset / msInStartQuarter;
};
DateUtils.parse = function (data) {
return typeof data === "function" ? new Date(data()) : new Date(data);
};
DateUtils.getTimezoneOffsetDiff = function (data1, data2) {
return data2.getTimezoneOffset() - data1.getTimezoneOffset();
};
DateUtils.getOrCreateUTCDate = function (date) {
var timezoneOffset = date.getTimezoneOffset();
return timezoneOffset ? new Date(date.valueOf() + timezoneOffset * 60000) : date;
};
DateUtils.getDSTDelta = function (start, end) {
var timeZoneDiff = -DateUtils.getTimezoneOffsetDiff(start, end) * DateUtils.msPerMinute;
return timeZoneDiff;
};
DateUtils.msPerMinute = 60 * 1000;
DateUtils.msPerHour = 3600000;
DateUtils.msPerDay = 24 * DateUtils.msPerHour;
DateUtils.msPerWeek = 7 * DateUtils.msPerDay;
DateUtils.msPerMonth = 30 * DateUtils.msPerDay;
DateUtils.msPerYear = 365 * DateUtils.msPerDay;
DateUtils.ViewTypeToScaleMap = createViewTypeToScaleMap();
return DateUtils;
}());
exports.DateUtils = DateUtils;
function createViewTypeToScaleMap() {
var result = {};
result[Enums_1.ViewType.TenMinutes] = Enums_1.ViewType.Hours;
result[Enums_1.ViewType.Hours] = Enums_1.ViewType.Days;
result[Enums_1.ViewType.SixHours] = Enums_1.ViewType.Days;
result[Enums_1.ViewType.Days] = Enums_1.ViewType.Weeks;
result[Enums_1.ViewType.Weeks] = Enums_1.ViewType.Months;
result[Enums_1.ViewType.Months] = Enums_1.ViewType.Years;
result[Enums_1.ViewType.Quarter] = Enums_1.ViewType.Years;
result[Enums_1.ViewType.Years] = Enums_1.ViewType.FiveYears;
return result;
}
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourceCollection = void 0;
var tslib_1 = __webpack_require__(0);
var CollectionBase_1 = __webpack_require__(23);
var Resource_1 = __webpack_require__(56);
var ResourceCollection = (function (_super) {
(0, tslib_1.__extends)(ResourceCollection, _super);
function ResourceCollection() {
return _super !== null && _super.apply(this, arguments) || this;
}
ResourceCollection.prototype.createItem = function () { return new Resource_1.Resource(); };
return ResourceCollection;
}(CollectionBase_1.CollectionBase));
exports.ResourceCollection = ResourceCollection;
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CollectionBase = void 0;
var common_1 = __webpack_require__(1);
var GanttJsonUtils_1 = __webpack_require__(94);
var CollectionBase = (function () {
function CollectionBase() {
this._items = new Array();
this._isGanttCollection = true;
}
CollectionBase.prototype.add = function (element) {
if (!(0, common_1.isDefined)(element))
return;
if (this.getItemById(element.internalId))
throw "The collection item with id ='" + element.internalId + "' already exists.";
this._addItem(element);
};
CollectionBase.prototype.addRange = function (range) {
for (var i = 0; i < range.length; i++)
this.add(range[i]);
};
CollectionBase.prototype.remove = function (element) {
var index = this._items.indexOf(element);
if (index > -1 && index < this._items.length)
this._removeItems(index, 1);
};
CollectionBase.prototype.clear = function () {
this._removeItems(0, this._items.length);
};
CollectionBase.prototype._addItem = function (element) {
this._items.push(element);
delete this._invertedItems;
};
CollectionBase.prototype._removeItems = function (start, count) {
this._items.splice(start, count);
delete this._invertedItems;
};
Object.defineProperty(CollectionBase.prototype, "items", {
get: function () {
return this._items.slice();
},
set: function (value) {
if (value)
this._items = value.slice();
},
enumerable: false,
configurable: true
});
Object.defineProperty(CollectionBase.prototype, "length", {
get: function () {
return this._items.length;
},
enumerable: false,
configurable: true
});
CollectionBase.prototype.getItem = function (index) {
if (index > -1 && index < this._items.length)
return this._items[index];
return null;
};
Object.defineProperty(CollectionBase.prototype, "invertedItems", {
get: function () {
var _a;
(_a = this._invertedItems) !== null && _a !== void 0 ? _a : (this._invertedItems = this._createInvertedItems());
return this._invertedItems;
},
enumerable: false,
configurable: true
});
CollectionBase.prototype._createInvertedItems = function () {
var result = {};
for (var i = 0; i < this._items.length; i++) {
var item = this._items[i];
result[item.internalId] = item;
}
return result;
};
CollectionBase.prototype.getItemById = function (id) {
return this.invertedItems[id];
};
CollectionBase.prototype.getItemByPublicId = function (id) {
return this._items.filter(function (val) { return val.id === id || val.id.toString() === id; })[0];
};
CollectionBase.prototype.assign = function (sourceCollection) {
if (!(0, common_1.isDefined)(sourceCollection))
return;
this.items = sourceCollection.items;
};
CollectionBase.prototype.importFromObject = function (source) {
if (!(0, common_1.isDefined)(source))
return;
this.clear();
if (source._isGanttCollection)
this.assign(source);
else if (source instanceof Array)
this.importFromArray(source);
else
this.createItemFromObjectAndAdd(source);
};
CollectionBase.prototype.createItemFromObjectAndAdd = function (source) {
if ((0, common_1.isDefined)(source)) {
var item = this.createItem();
item.assignFromObject(source);
this.add(item);
}
};
CollectionBase.prototype.importFromArray = function (values) {
for (var i = 0; i < values.length; i++)
this.createItemFromObjectAndAdd(values[i]);
};
CollectionBase.prototype.importFromJSON = function (json) {
this.importFromObject(GanttJsonUtils_1.GanttJsonUtils.parseJson(json));
};
return CollectionBase;
}());
exports.CollectionBase = CollectionBase;
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DependencyType = exports.TaskType = void 0;
var TaskType;
(function (TaskType) {
TaskType[TaskType["Regular"] = 0] = "Regular";
TaskType[TaskType["Summary"] = 1] = "Summary";
TaskType[TaskType["Milestone"] = 2] = "Milestone";
})(TaskType = exports.TaskType || (exports.TaskType = {}));
var DependencyType;
(function (DependencyType) {
DependencyType[DependencyType["FS"] = 0] = "FS";
DependencyType[DependencyType["SS"] = 1] = "SS";
DependencyType[DependencyType["FF"] = 2] = "FF";
DependencyType[DependencyType["SF"] = 3] = "SF";
})(DependencyType = exports.DependencyType || (exports.DependencyType = {}));
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskCommandBase = void 0;
var tslib_1 = __webpack_require__(0);
var CommandBase_1 = __webpack_require__(5);
var SimpleCommandState_1 = __webpack_require__(6);
var TaskCommandBase = (function (_super) {
(0, tslib_1.__extends)(TaskCommandBase, _super);
function TaskCommandBase() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.isApiCall = false;
return _this;
}
TaskCommandBase.prototype.getState = function () {
var state = new SimpleCommandState_1.SimpleCommandState(this.isEnabled());
state.visible = this.control.settings.editing.enabled && !this.control.taskEditController.dependencyId;
return state;
};
TaskCommandBase.prototype.updateParent = function (parent) {
var isAutoUpdateParentTask = this.validationController._parentAutoCalc;
if (isAutoUpdateParentTask && parent && parent.children.length > 0)
this.control.validationController.updateParentsIfRequired(parent.children[0].task.internalId);
};
return TaskCommandBase;
}(CommandBase_1.CommandBase));
exports.TaskCommandBase = TaskCommandBase;
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskPropertyCommandBase = void 0;
var tslib_1 = __webpack_require__(0);
var CommandBase_1 = __webpack_require__(5);
var SimpleCommandState_1 = __webpack_require__(6);
var TaskPropertyCommandBase = (function (_super) {
(0, tslib_1.__extends)(TaskPropertyCommandBase, _super);
function TaskPropertyCommandBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskPropertyCommandBase.prototype.getState = function () {
return new SimpleCommandState_1.SimpleCommandState(this.isEnabled());
};
TaskPropertyCommandBase.prototype.isEnabled = function () {
return _super.prototype.isEnabled.call(this) && this.control.settings.editing.allowTaskUpdate;
};
TaskPropertyCommandBase.prototype.getTask = function (id) {
return this.control.viewModel.tasks.getItemById(id);
};
return TaskPropertyCommandBase;
}(CommandBase_1.CommandBase));
exports.TaskPropertyCommandBase = TaskPropertyCommandBase;
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var browser_1 = __webpack_require__(8);
var common_1 = __webpack_require__(1);
var TouchUtils = (function () {
function TouchUtils() {
}
TouchUtils.onEventAttachingToDocument = function (eventName, func) {
if (browser_1.Browser.MacOSMobilePlatform && TouchUtils.isTouchEventName(eventName)) {
if (!TouchUtils.documentTouchHandlers[eventName])
TouchUtils.documentTouchHandlers[eventName] = [];
TouchUtils.documentTouchHandlers[eventName].push(func);
return TouchUtils.documentEventAttachingAllowed;
}
return true;
};
TouchUtils.isTouchEventName = function (eventName) {
return browser_1.Browser.WebKitTouchUI && (eventName.indexOf('touch') > -1 || eventName.indexOf('gesture') > -1);
};
TouchUtils.isTouchEvent = function (evt) {
return browser_1.Browser.WebKitTouchUI && common_1.isDefined(evt.changedTouches);
};
TouchUtils.getEventX = function (evt) {
return browser_1.Browser.IE ? evt.pageX : evt.changedTouches[0].pageX;
};
TouchUtils.getEventY = function (evt) {
return browser_1.Browser.IE ? evt.pageY : evt.changedTouches[0].pageY;
};
TouchUtils.touchMouseDownEventName = browser_1.Browser.WebKitTouchUI ? 'touchstart' : (browser_1.Browser.Edge && browser_1.Browser.MSTouchUI && window.PointerEvent ? 'pointerdown' : 'mousedown');
TouchUtils.touchMouseUpEventName = browser_1.Browser.WebKitTouchUI ? 'touchend' : (browser_1.Browser.Edge && browser_1.Browser.MSTouchUI && window.PointerEvent ? 'pointerup' : 'mouseup');
TouchUtils.touchMouseMoveEventName = browser_1.Browser.WebKitTouchUI ? 'touchmove' : (browser_1.Browser.Edge && browser_1.Browser.MSTouchUI && window.PointerEvent ? 'pointermove' : 'mousemove');
TouchUtils.msTouchDraggableClassName = 'dxMSTouchDraggable';
TouchUtils.documentTouchHandlers = {};
TouchUtils.documentEventAttachingAllowed = true;
return TouchUtils;
}());
exports.TouchUtils = TouchUtils;
/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StyleDef = void 0;
var common_1 = __webpack_require__(1);
var dom_1 = __webpack_require__(3);
var Color_1 = __webpack_require__(17);
var PredefinedStyles_1 = __webpack_require__(51);
var Margin_1 = __webpack_require__(40);
var Width_1 = __webpack_require__(78);
var StyleDef = (function () {
function StyleDef(source) {
this._fillColor = new Color_1.Color();
this._textColor = new Color_1.Color();
this._lineColor = new Color_1.Color();
this._cellWidth = new Width_1.Width();
this._cellPadding = new Margin_1.Margin();
if (source)
this.assign(source);
}
Object.defineProperty(StyleDef.prototype, "font", {
get: function () { return this._fontFamily; },
set: function (value) { this._fontFamily = PredefinedStyles_1.PredefinedStyles.getPredefinedStringOrUndefined(value, PredefinedStyles_1.PredefinedStyles.fontFamilies) || value; },
enumerable: false,
configurable: true
});
Object.defineProperty(StyleDef.prototype, "fontStyle", {
get: function () { return this._fontStyle; },
set: function (value) { this._fontStyle = PredefinedStyles_1.PredefinedStyles.getPredefinedStringOrUndefined(value, PredefinedStyles_1.PredefinedStyles.fontStyles); },
enumerable: false,
configurable: true
});
Object.defineProperty(StyleDef.prototype, "fontSize", {
get: function () { return this._fontSize; },
set: function (value) { this._fontSize = value; },
enumerable: false,
configurable: true
});
Object.defineProperty(StyleDef.prototype, "overflow", {
get: function () { return this._overflow; },
set: function (value) { this._overflow = PredefinedStyles_1.PredefinedStyles.getPredefinedStringOrUndefined(value, PredefinedStyles_1.PredefinedStyles.overflow); },
enumerable: false,
configurable: true
});
Object.defineProperty(StyleDef.prototype, "halign", {
get: function () { return this._horizontalAlign; },
set: function (value) { this._horizontalAlign = PredefinedStyles_1.PredefinedStyles.getPredefinedStringOrUndefined(value, PredefinedStyles_1.PredefinedStyles.horizontalAlign); },
enumerable: false,
configurable: true
});
Object.defineProperty(StyleDef.prototype, "valign", {
get: function () { return this._verticalAlign; },
set: function (value) { this._verticalAlign = PredefinedStyles_1.PredefinedStyles.getPredefinedStringOrUndefined(value, PredefinedStyles_1.PredefinedStyles.verticalAlign); },
enumerable: false,
configurable: true
});
Object.defineProperty(StyleDef.prototype, "fillColor", {
get: function () { return this._fillColor; },
enumerable: false,
configurable: true
});
Object.defineProperty(StyleDef.prototype, "textColor", {
get: function () { return this._textColor; },
enumerable: false,
configurable: true
});
Object.defineProperty(StyleDef.prototype, "lineColor", {
get: function () { return this._lineColor; },
enumerable: false,
configurable: true
});
Object.defineProperty(StyleDef.prototype, "cellWidth", {
get: function () { return this._cellWidth; },
enumerable: false,
configurable: true
});
Object.defineProperty(StyleDef.prototype, "cellPadding", {
get: function () { return this._cellPadding; },
enumerable: false,
configurable: true
});
Object.defineProperty(StyleDef.prototype, "lineWidth", {
get: function () { return this._lineWidth; },
set: function (value) { this._lineWidth = value; },
enumerable: false,
configurable: true
});
Object.defineProperty(StyleDef.prototype, "minCellWidth", {
get: function () { return this._minCellWidth; },
set: function (value) { this._minCellWidth = value; },
enumerable: false,
configurable: true
});
Object.defineProperty(StyleDef.prototype, "minCellHeight", {
get: function () { return this._minCellHeight; },
set: function (value) { this._minCellHeight = value; },
enumerable: false,
configurable: true
});
StyleDef.prototype.assign = function (source) {
if (!source)
return;
if (source instanceof StyleDef) {
if ((0, common_1.isDefined)(source["font"]))
this.font = source["font"];
if ((0, common_1.isDefined)(source["fontStyle"]))
this.fontStyle = source["fontStyle"];
if ((0, common_1.isDefined)(source["overflow"]))
this.overflow = source["overflow"];
if ((0, common_1.isDefined)(source["halign"]))
this.halign = source["halign"];
if ((0, common_1.isDefined)(source["valign"]))
this.valign = source["valign"];
if ((0, common_1.isDefined)(source["fontSize"]))
this.fontSize = source["fontSize"];
if ((0, common_1.isDefined)(source["lineWidth"]))
this.lineWidth = source["lineWidth"];
if ((0, common_1.isDefined)(source["minCellWidth"]))
this.minCellWidth = source["minCellWidth"];
if ((0, common_1.isDefined)(source["minCellHeight"]))
this.minCellHeight = source["minCellHeight"];
if ((0, common_1.isDefined)(source["fillColor"]))
this.fillColor.assign(source["fillColor"]);
if ((0, common_1.isDefined)(source["textColor"]))
this.textColor.assign(source["textColor"]);
if ((0, common_1.isDefined)(source["lineColor"]))
this.lineColor.assign(source["lineColor"]);
if ((0, common_1.isDefined)(source["cellWidth"]))
this.cellWidth.assign(source["cellWidth"]);
if ((0, common_1.isDefined)(source["cellPadding"]))
this.cellPadding.assign(source["cellPadding"]);
}
else
this.assignFromCssStyle(source);
};
StyleDef.prototype.assignFromCssStyle = function (source) {
if (source.fontFamily)
this.font = this.getPdfFontFamily(source);
this.fontStyle = this.getPdfFontStyle(source);
if ((0, common_1.isDefined)(source.fontSize))
this.fontSize = this.getPfrFontSize(source.fontSize);
if (source.textAlign)
this.halign = source.textAlign;
if (source.verticalAlign)
this.valign = source.verticalAlign;
if ((0, common_1.isDefined)(source.borderWidth))
this.lineWidth = source.borderWidth;
if ((0, common_1.isDefined)(source.cellWidth))
this.cellWidth.assign(source.cellWidth);
if ((0, common_1.isDefined)(source.width))
this.minCellWidth = typeof source.width === "number" ? source.width : dom_1.DomUtils.pxToInt(source.width);
if ((0, common_1.isDefined)(source.height))
this.minCellHeight = typeof source.height === "number" ? source.height : dom_1.DomUtils.pxToInt(source.height);
if (source.backgroundColor)
this.fillColor.assign(source.backgroundColor);
if (source.color)
this.textColor.assign(source.color);
if (source.borderColor)
this.lineColor.assign(source.borderColor);
if ((0, common_1.isDefined)(source.width))
this.cellWidth.assign(source.width);
this.assignPaddingFromCss(source);
if ((0, common_1.isDefined)(source.extraLeftPadding)) {
var currentLeftPadding = this._cellPadding.left;
this._cellPadding.left = currentLeftPadding ? currentLeftPadding + source.extraLeftPadding : source.extraLeftPadding;
}
};
StyleDef.prototype.getPdfFontStyle = function (style) {
var fontWeight = style.fontWeight;
var numeric = parseInt(fontWeight);
var isBold = fontWeight === "bold" || !isNaN(numeric) && numeric > 500;
var isItalic = style.fontStyle === "italic";
var result = isBold ? "bold" : "normal";
if (isItalic)
result = isBold ? "bolditalic" : "italic";
return result;
};
StyleDef.prototype.getPdfFontFamily = function (style) {
var fontFamily = style.fontFamily && style.fontFamily.toLowerCase();
var result = "helvetica";
if (fontFamily.indexOf("times") > -1)
result = "times";
if (fontFamily.indexOf("courier") > -1)
result = "courier";
return result;
};
StyleDef.prototype.getPfrFontSize = function (fontSize) {
var size = dom_1.DomUtils.pxToInt(fontSize);
if (!isNaN(size))
return Math.ceil(size / 96 * 72);
};
StyleDef.prototype.assignPaddingFromCss = function (source) {
if (source.padding)
this._cellPadding.assign(source.padding);
else {
var padding = {};
if (source.paddingLeft)
padding["left"] = dom_1.DomUtils.pxToInt(source.paddingLeft);
if (source.paddingTop)
padding["top"] = dom_1.DomUtils.pxToInt(source.paddingTop);
if (source.paddingRight)
padding["right"] = dom_1.DomUtils.pxToInt(source.paddingRight);
if (source.paddingBottom)
padding["bottom"] = dom_1.DomUtils.pxToInt(source.paddingBottom);
this._cellPadding.assign(padding);
}
};
StyleDef.prototype.hasValue = function () {
return true;
};
StyleDef.prototype.getValue = function () {
var _this = this;
var style = {};
if ((0, common_1.isDefined)(this.font))
style["font"] = this.font;
if ((0, common_1.isDefined)(this.fontStyle))
style["fontStyle"] = this.fontStyle;
if ((0, common_1.isDefined)(this.fontSize))
style["fontSize"] = this.fontSize;
if ((0, common_1.isDefined)(this.overflow))
style["overflow"] = this.overflow;
if ((0, common_1.isDefined)(this.halign))
style["halign"] = this.halign;
if ((0, common_1.isDefined)(this.valign))
style["valign"] = this.valign;
if ((0, common_1.isDefined)(this.lineWidth))
style["lineWidth"] = this.lineWidth;
if ((0, common_1.isDefined)(this.minCellWidth))
style["minCellWidth"] = this.minCellWidth;
if ((0, common_1.isDefined)(this.minCellHeight))
style["minCellHeight"] = this.minCellHeight;
this.getJsPdfProviderProps().forEach(function (key) {
var prop = _this[key];
if (prop && prop.hasValue())
style[key] = prop.getValue();
});
return style;
};
StyleDef.prototype.getJsPdfProviderProps = function () {
return [
"fillColor",
"textColor",
"lineColor",
"cellWidth",
"cellPadding"
];
};
return StyleDef;
}());
exports.StyleDef = StyleDef;
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PdfPageTableNames = void 0;
var PdfPageTableNames = (function () {
function PdfPageTableNames() {
}
PdfPageTableNames.treeListHeader = "treeListHeader";
PdfPageTableNames.treeListMain = "treeListMain";
PdfPageTableNames.chartMain = "chartMain";
PdfPageTableNames.chartScaleTop = "chartScaleTop";
PdfPageTableNames.chartScaleBottom = "chartScaleBottom";
return PdfPageTableNames;
}());
exports.PdfPageTableNames = PdfPageTableNames;
/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DialogBase = void 0;
var tslib_1 = __webpack_require__(0);
var CommandBase_1 = __webpack_require__(5);
var SimpleCommandState_1 = __webpack_require__(6);
var DialogBase = (function (_super) {
(0, tslib_1.__extends)(DialogBase, _super);
function DialogBase() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.isApiCall = false;
return _this;
}
DialogBase.prototype.execute = function (options, isApiCall) {
if (options === void 0) { options = undefined; }
if (isApiCall === void 0) { isApiCall = false; }
this.isApiCall = isApiCall;
return _super.prototype.execute.call(this, options);
};
DialogBase.prototype.executeInternal = function (options) {
var _this = this;
var params = this.createParameters(options);
var initParams = params.clone();
if (!this.onBeforeDialogShow(params))
return false;
this.control.showDialog(this.getDialogName(), params, function (result) {
if (result)
_this.applyParameters(result, initParams);
}, function () {
_this.afterClosing();
});
return true;
};
DialogBase.prototype.onBeforeDialogShow = function (params) {
return true;
};
DialogBase.prototype.applyParameters = function (_newParameters, _oldParameters) {
return false;
};
DialogBase.prototype.afterClosing = function () { };
DialogBase.prototype.getState = function () {
return new SimpleCommandState_1.SimpleCommandState(this.isEnabled());
};
return DialogBase;
}(CommandBase_1.CommandBase));
exports.DialogBase = DialogBase;
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RemoveDependencyHistoryItem = void 0;
var tslib_1 = __webpack_require__(0);
var HistoryItem_1 = __webpack_require__(12);
var RemoveDependencyHistoryItem = (function (_super) {
(0, tslib_1.__extends)(RemoveDependencyHistoryItem, _super);
function RemoveDependencyHistoryItem(modelManipulator, dependencyId) {
var _this = _super.call(this, modelManipulator) || this;
_this.dependencyId = dependencyId;
return _this;
}
RemoveDependencyHistoryItem.prototype.redo = function () {
this.dependency = this.modelManipulator.dependency.removeDependency(this.dependencyId);
};
RemoveDependencyHistoryItem.prototype.undo = function () {
this.modelManipulator.dependency.insertDependency(this.dependency.predecessorId, this.dependency.successorId, this.dependency.type, this.dependencyId);
};
return RemoveDependencyHistoryItem;
}(HistoryItem_1.HistoryItem));
exports.RemoveDependencyHistoryItem = RemoveDependencyHistoryItem;
/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConstraintViolationOption = exports.ConfirmationType = void 0;
var ConfirmationType;
(function (ConfirmationType) {
ConfirmationType[ConfirmationType["TaskDelete"] = 0] = "TaskDelete";
ConfirmationType[ConfirmationType["DependencyDelete"] = 1] = "DependencyDelete";
ConfirmationType[ConfirmationType["ResourcesDelete"] = 2] = "ResourcesDelete";
})(ConfirmationType = exports.ConfirmationType || (exports.ConfirmationType = {}));
var ConstraintViolationOption;
(function (ConstraintViolationOption) {
ConstraintViolationOption[ConstraintViolationOption["DoNothing"] = 0] = "DoNothing";
ConstraintViolationOption[ConstraintViolationOption["RemoveDependency"] = 1] = "RemoveDependency";
ConstraintViolationOption[ConstraintViolationOption["KeepDependency"] = 2] = "KeepDependency";
})(ConstraintViolationOption = exports.ConstraintViolationOption || (exports.ConstraintViolationOption = {}));
/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DialogParametersBase = void 0;
var DialogParametersBase = (function () {
function DialogParametersBase() {
}
return DialogParametersBase;
}());
exports.DialogParametersBase = DialogParametersBase;
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DeassignResourceHistoryItem = void 0;
var tslib_1 = __webpack_require__(0);
var HistoryItem_1 = __webpack_require__(12);
var DeassignResourceHistoryItem = (function (_super) {
(0, tslib_1.__extends)(DeassignResourceHistoryItem, _super);
function DeassignResourceHistoryItem(modelManipulator, assignmentId) {
var _this = _super.call(this, modelManipulator) || this;
_this.assignmentId = assignmentId;
return _this;
}
DeassignResourceHistoryItem.prototype.redo = function () {
this.assignment = this.modelManipulator.resource.deassig(this.assignmentId);
};
DeassignResourceHistoryItem.prototype.undo = function () {
this.modelManipulator.resource.assign(this.assignment.resourceId, this.assignment.taskId, this.assignmentId);
};
return DeassignResourceHistoryItem;
}(HistoryItem_1.HistoryItem));
exports.DeassignResourceHistoryItem = DeassignResourceHistoryItem;
/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskEndHistoryItem = void 0;
var tslib_1 = __webpack_require__(0);
var TaskPropertiesHistoryItemBase_1 = __webpack_require__(15);
var TaskEndHistoryItem = (function (_super) {
(0, tslib_1.__extends)(TaskEndHistoryItem, _super);
function TaskEndHistoryItem() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskEndHistoryItem.prototype.getPropertiesManipulator = function () {
return this.modelManipulator.task.properties.end;
};
return TaskEndHistoryItem;
}(TaskPropertiesHistoryItemBase_1.TaskPropertiesHistoryItemBase));
exports.TaskEndHistoryItem = TaskEndHistoryItem;
/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskProgressHistoryItem = void 0;
var tslib_1 = __webpack_require__(0);
var TaskPropertiesHistoryItemBase_1 = __webpack_require__(15);
var TaskProgressHistoryItem = (function (_super) {
(0, tslib_1.__extends)(TaskProgressHistoryItem, _super);
function TaskProgressHistoryItem() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskProgressHistoryItem.prototype.getPropertiesManipulator = function () {
return this.modelManipulator.task.properties.progress;
};
return TaskProgressHistoryItem;
}(TaskPropertiesHistoryItemBase_1.TaskPropertiesHistoryItemBase));
exports.TaskProgressHistoryItem = TaskProgressHistoryItem;
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskStartHistoryItem = void 0;
var tslib_1 = __webpack_require__(0);
var TaskPropertiesHistoryItemBase_1 = __webpack_require__(15);
var TaskStartHistoryItem = (function (_super) {
(0, tslib_1.__extends)(TaskStartHistoryItem, _super);
function TaskStartHistoryItem() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskStartHistoryItem.prototype.getPropertiesManipulator = function () {
return this.modelManipulator.task.properties.start;
};
return TaskStartHistoryItem;
}(TaskPropertiesHistoryItemBase_1.TaskPropertiesHistoryItemBase));
exports.TaskStartHistoryItem = TaskStartHistoryItem;
/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourceCommandBase = void 0;
var tslib_1 = __webpack_require__(0);
var CommandBase_1 = __webpack_require__(5);
var SimpleCommandState_1 = __webpack_require__(6);
var ResourceCommandBase = (function (_super) {
(0, tslib_1.__extends)(ResourceCommandBase, _super);
function ResourceCommandBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
ResourceCommandBase.prototype.getState = function () {
return new SimpleCommandState_1.SimpleCommandState(this.isEnabled());
};
return ResourceCommandBase;
}(CommandBase_1.CommandBase));
exports.ResourceCommandBase = ResourceCommandBase;
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HandlerStateBase = void 0;
var point_1 = __webpack_require__(4);
var dom_1 = __webpack_require__(3);
var HandlerStateBase = (function () {
function HandlerStateBase(handler) {
this.handler = handler;
}
HandlerStateBase.prototype.start = function () { };
HandlerStateBase.prototype.finish = function () { };
HandlerStateBase.prototype.getRelativePos = function (absolutePos) {
var taskAreaX = dom_1.DomUtils.getAbsolutePositionX(this.renderHelper.taskArea);
var taskAreaY = dom_1.DomUtils.getAbsolutePositionY(this.renderHelper.taskArea);
return new point_1.Point(absolutePos.x - taskAreaX, absolutePos.y - taskAreaY);
};
Object.defineProperty(HandlerStateBase.prototype, "renderHelper", {
get: function () {
return this.handler.settings.getRenderHelper();
},
enumerable: false,
configurable: true
});
Object.defineProperty(HandlerStateBase.prototype, "taskEditController", {
get: function () {
return this.handler.settings.getTaskEditController();
},
enumerable: false,
configurable: true
});
Object.defineProperty(HandlerStateBase.prototype, "tickSize", {
get: function () {
return this.handler.settings.getTickSize();
},
enumerable: false,
configurable: true
});
Object.defineProperty(HandlerStateBase.prototype, "viewModel", {
get: function () {
return this.handler.settings.getViewModel();
},
enumerable: false,
configurable: true
});
HandlerStateBase.prototype.zoomIn = function (leftPosition) {
this.handler.settings.zoomIn(leftPosition);
};
HandlerStateBase.prototype.zoomOut = function (leftPosition) {
this.handler.settings.zoomOut(leftPosition);
};
HandlerStateBase.prototype.selectDependency = function (id) {
this.handler.settings.selectDependency(id);
};
HandlerStateBase.prototype.showPopupMenu = function (info) {
this.handler.settings.showPopupMenu(info);
};
HandlerStateBase.prototype.changeGanttTaskSelection = function (id, selected) {
this.handler.settings.changeGanttTaskSelection(id, selected);
};
return HandlerStateBase;
}());
exports.HandlerStateBase = HandlerStateBase;
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Margin = void 0;
var common_1 = __webpack_require__(1);
var dom_1 = __webpack_require__(3);
var Margin = (function () {
function Margin(values) {
this.assign(values);
}
Margin.prototype.assign = function (values) {
if (!(0, common_1.isDefined)(values))
return;
if (typeof values === "string")
this.assignFromString(values);
else if (typeof values === "number" || values instanceof Array)
this.assignWithValues(values);
else {
var source = values || values;
this.assignWithMargin(source);
}
};
Margin.prototype.assignFromString = function (source) {
var values = source.split(" ").map(function (p) { return dom_1.DomUtils.pxToInt(p); });
this.assignWithValues(values);
};
Margin.prototype.assignWithMargin = function (source) {
if ((0, common_1.isDefined)(source.top))
this.top = source.top;
if ((0, common_1.isDefined)(source.right))
this.right = source.right;
if ((0, common_1.isDefined)(source.bottom))
this.bottom = source.bottom;
if ((0, common_1.isDefined)(source.left))
this.left = source.left;
};
Margin.prototype.assignWithValues = function (values) {
var numbers = this.getCorrectedValues(values);
this.top = numbers[0];
this.right = numbers[1];
this.bottom = numbers[2];
this.left = numbers[3];
};
Margin.prototype.getCorrectedValues = function (values) {
var result = [this.top, this.right, this.bottom, this.left];
if (typeof values === "number") {
var num = values;
result = [num, num, num, num];
}
else {
var numbers = values;
switch (numbers.length) {
case 1:
result = [numbers[0], numbers[0], numbers[0], numbers[0]];
break;
case 2:
result = [numbers[0], numbers[1], numbers[0], numbers[1]];
break;
case 3:
result = [numbers[0], numbers[1], numbers[2], numbers[1]];
break;
default:
numbers.forEach(function (v, i) { return result[i] = v; });
break;
}
}
return result;
};
Margin.prototype.hasValue = function () {
return (0, common_1.isDefined)(this.top) || (0, common_1.isDefined)(this.left) || (0, common_1.isDefined)(this.right) || (0, common_1.isDefined)(this.bottom);
};
Margin.prototype.getValue = function () {
if (!this.hasValue())
return null;
if (this.top === this.bottom && this.left === this.right && this.top === this.left)
return this.top;
var result = {};
if ((0, common_1.isDefined)(this.top))
result["top"] = this.top;
if ((0, common_1.isDefined)(this.left))
result["left"] = this.left;
if ((0, common_1.isDefined)(this.right))
result["right"] = this.right;
if ((0, common_1.isDefined)(this.bottom))
result["bottom"] = this.bottom;
return result;
};
return Margin;
}());
exports.Margin = Margin;
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecurrenceBase = void 0;
var tslib_1 = __webpack_require__(0);
var DayOfWeek_1 = __webpack_require__(234);
var DayOfWeekMonthlyOccurrence_1 = __webpack_require__(68);
var Month_1 = __webpack_require__(235);
var common_1 = __webpack_require__(1);
var DateTimeUtils_1 = __webpack_require__(7);
var RecurrenceFactory_1 = __webpack_require__(85);
var DataObject_1 = __webpack_require__(20);
var RecurrenceBase = (function (_super) {
(0, tslib_1.__extends)(RecurrenceBase, _super);
function RecurrenceBase(start, end, interval, occurrenceCount) {
if (start === void 0) { start = null; }
if (end === void 0) { end = null; }
if (interval === void 0) { interval = 1; }
if (occurrenceCount === void 0) { occurrenceCount = 0; }
var _this = _super.call(this) || this;
_this._start = null;
_this._end = null;
_this._interval = 1;
_this._occurrenceCount = 0;
_this._dayOfWeek = 0;
_this._day = 1;
_this._dayOfWeekOccurrence = 0;
_this._month = 0;
_this._calculateByDayOfWeek = false;
_this.start = start;
_this.end = end;
_this.interval = interval;
_this.occurrenceCount = occurrenceCount;
return _this;
}
RecurrenceBase.prototype.assignFromObject = function (sourceObj) {
if ((0, common_1.isDefined)(sourceObj)) {
_super.prototype.assignFromObject.call(this, sourceObj);
this.start = DateTimeUtils_1.DateTimeUtils.convertToDate(sourceObj.start);
this.end = DateTimeUtils_1.DateTimeUtils.convertToDate(sourceObj.end);
if ((0, common_1.isDefined)(sourceObj.interval))
this.interval = sourceObj.interval;
if ((0, common_1.isDefined)(sourceObj.occurrenceCount))
this.occurrenceCount = sourceObj.occurrenceCount;
if ((0, common_1.isDefined)(sourceObj.dayOfWeek))
this.dayOfWeekInternal = RecurrenceFactory_1.RecurrenceFactory.getEnumValue(DayOfWeek_1.DayOfWeek, sourceObj.dayOfWeek);
if ((0, common_1.isDefined)(sourceObj.day))
this.dayInternal = sourceObj.day;
if ((0, common_1.isDefined)(sourceObj.dayOfWeekOccurrence))
this.dayOfWeekOccurrenceInternal = RecurrenceFactory_1.RecurrenceFactory.getEnumValue(DayOfWeekMonthlyOccurrence_1.DayOfWeekMonthlyOccurrence, sourceObj.dayOfWeekOccurrence);
if ((0, common_1.isDefined)(sourceObj.month))
this.monthInternal = RecurrenceFactory_1.RecurrenceFactory.getEnumValue(Month_1.Month, sourceObj.month);
if ((0, common_1.isDefined)(sourceObj.calculateByDayOfWeek))
this._calculateByDayOfWeek = !!sourceObj.calculateByDayOfWeek;
}
};
RecurrenceBase.prototype.calculatePoints = function (start, end) {
if (!start || !end)
return new Array();
var from = DateTimeUtils_1.DateTimeUtils.getMaxDate(start, this._start);
var to = DateTimeUtils_1.DateTimeUtils.getMinDate(end, this._end);
if (this._occurrenceCount > 0)
return this.calculatePointsByOccurrenceCount(from, to);
return this.calculatePointsByDateRange(from, to);
};
RecurrenceBase.prototype.calculatePointsByOccurrenceCount = function (start, end) {
var points = new Array();
var point = this.getFirstPoint(start);
while (!!point && points.length < this._occurrenceCount && DateTimeUtils_1.DateTimeUtils.compareDates(point, end) >= 0) {
if (this.isRecurrencePoint(point))
points.push(point);
point = this.getNextPoint(point);
}
return points;
};
RecurrenceBase.prototype.calculatePointsByDateRange = function (start, end) {
var points = new Array();
var point = this.getFirstPoint(start);
while (!!point && DateTimeUtils_1.DateTimeUtils.compareDates(point, end) >= 0) {
if (this.isRecurrencePoint(point))
points.push(point);
point = this.getNextPoint(point);
}
return points;
};
RecurrenceBase.prototype.getFirstPoint = function (start) {
if (this.isRecurrencePoint(start))
return start;
return this.getNextPoint(start);
};
RecurrenceBase.prototype.isRecurrencePoint = function (date) {
return this.isDateInRange(date) && this.checkDate(date) && (!this.useIntervalInCalc() || this.checkInterval(date));
};
RecurrenceBase.prototype.isDateInRange = function (date) {
if (!date)
return false;
if (this._start && DateTimeUtils_1.DateTimeUtils.compareDates(this.start, date) < 0)
return false;
if (this._occurrenceCount == 0 && this.end && DateTimeUtils_1.DateTimeUtils.compareDates(date, this.end) < 0)
return false;
return true;
};
RecurrenceBase.prototype.useIntervalInCalc = function () {
return this.interval > 1 && !!this._start;
};
RecurrenceBase.prototype.getNextPoint = function (date) {
if (!this.isDateInRange(date))
return null;
if (this.useIntervalInCalc())
return this.calculatePointByInterval(date);
return this.calculateNearestPoint(date);
};
RecurrenceBase.prototype.getSpecDayInMonth = function (year, month) {
var date;
if (this._calculateByDayOfWeek)
date = DateTimeUtils_1.DateTimeUtils.getSpecificDayOfWeekInMonthDate(this.dayOfWeekInternal, year, month, this.dayOfWeekOccurrenceInternal);
else
date = new Date(year, month, this.dayInternal);
return date;
};
Object.defineProperty(RecurrenceBase.prototype, "dayInternal", {
get: function () { return this._day; },
set: function (value) {
if (value > 0 && value <= 31)
this._day = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RecurrenceBase.prototype, "dayOfWeekInternal", {
get: function () { return this._dayOfWeek; },
set: function (dayOfWeek) {
if (dayOfWeek >= DayOfWeek_1.DayOfWeek.Sunday && dayOfWeek <= DayOfWeek_1.DayOfWeek.Saturday)
this._dayOfWeek = dayOfWeek;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RecurrenceBase.prototype, "dayOfWeekOccurrenceInternal", {
get: function () {
return this._dayOfWeekOccurrence;
},
set: function (value) {
if (value >= DayOfWeekMonthlyOccurrence_1.DayOfWeekMonthlyOccurrence.First && value <= DayOfWeekMonthlyOccurrence_1.DayOfWeekMonthlyOccurrence.Last)
this._dayOfWeekOccurrence = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RecurrenceBase.prototype, "monthInternal", {
get: function () { return this._month; },
set: function (value) {
if (value >= Month_1.Month.January && value <= Month_1.Month.December)
this._month = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RecurrenceBase.prototype, "start", {
get: function () { return this._start; },
set: function (date) {
if (!date)
return;
this._start = date;
if (!!this._end && date > this._end)
this._end = date;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RecurrenceBase.prototype, "end", {
get: function () { return this._end; },
set: function (date) {
if (!date)
return;
this._end = date;
if (!!this._start && date < this._start)
this._start = date;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RecurrenceBase.prototype, "occurrenceCount", {
get: function () { return this._occurrenceCount; },
set: function (value) {
if (value < 0)
value = 0;
this._occurrenceCount = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RecurrenceBase.prototype, "interval", {
get: function () { return this._interval; },
set: function (value) {
if (value > 0)
this._interval = value;
},
enumerable: false,
configurable: true
});
return RecurrenceBase;
}(DataObject_1.DataObject));
exports.RecurrenceBase = RecurrenceBase;
/***/ }),
/* 42 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var StringUtils = (function () {
function StringUtils() {
}
StringUtils.isAlpha = function (ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
};
StringUtils.isDigit = function (ch) {
return ch >= '0' && ch <= '9';
};
StringUtils.stringHashCode = function (str) {
var hash = 0;
if (str.length === 0)
return hash;
var strLen = str.length;
for (var i = 0; i < strLen; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash |= 0;
}
return hash;
};
StringUtils.endsAt = function (str, template) {
var strInd = str.length - 1;
var tmplInd = template.length - 1;
var strStartInd = strInd - tmplInd;
if (strStartInd < 0)
return false;
for (; strInd >= strStartInd; strInd--, tmplInd--) {
if (str[strInd] !== template[tmplInd])
return false;
}
return true;
};
StringUtils.startsAt = function (str, template) {
return str.substr(0, template.length) === template;
};
StringUtils.stringInLowerCase = function (str) {
return str.toLowerCase() === str;
};
StringUtils.stringInUpperCase = function (str) {
return str.toUpperCase() === str;
};
StringUtils.atLeastOneSymbolInUpperCase = function (str) {
for (var i = 0, char = void 0; char = str[i]; i++) {
if (StringUtils.stringInUpperCase(char) && !StringUtils.stringInLowerCase(char))
return true;
}
return false;
};
StringUtils.getSymbolFromEnd = function (text, posFromEnd) {
return text[text.length - posFromEnd];
};
StringUtils.trim = function (str, trimChars) {
if (trimChars === undefined)
return StringUtils.trimInternal(str, true, true);
else {
var joinedChars = trimChars.join('');
return str.replace(new RegExp("(^[" + joinedChars + "]*)|([" + joinedChars + "]*$)", 'g'), '');
}
};
StringUtils.trimStart = function (str, trimChars) {
if (trimChars === undefined)
return StringUtils.trimInternal(str, true, false);
else {
var joinedChars = trimChars.join('');
return str.replace(new RegExp("^[" + joinedChars + "]*", 'g'), '');
}
};
StringUtils.trimEnd = function (str, trimChars) {
if (trimChars === undefined)
return StringUtils.trimInternal(str, false, true);
else {
var joinedChars = trimChars.join('');
return str.replace(new RegExp("[" + joinedChars + "]*$", 'g'), '');
}
};
StringUtils.getDecimalSeparator = function () {
return (1.1).toLocaleString().substr(1, 1);
};
StringUtils.repeat = function (str, count) {
return new Array(count <= 0 ? 0 : count + 1).join(str);
};
StringUtils.isNullOrEmpty = function (str) {
return !str || !str.length;
};
StringUtils.padLeft = function (str, totalWidth, paddingChar) {
return StringUtils.repeat(paddingChar, Math.max(0, totalWidth - str.length)) + str;
};
StringUtils.trimInternal = function (source, trimStart, trimEnd) {
var len = source.length;
if (!len)
return source;
if (len < 0xBABA1) {
var result = source;
if (trimStart)
result = result.replace(/^\s+/, '');
if (trimEnd)
result = result.replace(/\s+$/, '');
return result;
}
else {
var start = 0;
if (trimEnd) {
while (len > 0 && /\s/.test(source[len - 1]))
len--;
}
if (trimStart && len > 0) {
while (start < len && /\s/.test(source[start]))
start++;
}
return source.substring(start, len);
}
};
return StringUtils;
}());
exports.StringUtils = StringUtils;
/***/ }),
/* 43 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConfirmationDialogParameters = void 0;
var tslib_1 = __webpack_require__(0);
var DialogParametersBase_1 = __webpack_require__(33);
var ConfirmationDialogParameters = (function (_super) {
(0, tslib_1.__extends)(ConfirmationDialogParameters, _super);
function ConfirmationDialogParameters(type, callback) {
var _this = _super.call(this) || this;
_this.type = type;
_this.callback = callback;
return _this;
}
ConfirmationDialogParameters.prototype.clone = function () {
var result = new ConfirmationDialogParameters(this.type, this.callback);
result.message = this.message;
return result;
};
return ConfirmationDialogParameters;
}(DialogParametersBase_1.DialogParametersBase));
exports.ConfirmationDialogParameters = ConfirmationDialogParameters;
/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskTitleHistoryItem = void 0;
var tslib_1 = __webpack_require__(0);
var TaskPropertiesHistoryItemBase_1 = __webpack_require__(15);
var TaskTitleHistoryItem = (function (_super) {
(0, tslib_1.__extends)(TaskTitleHistoryItem, _super);
function TaskTitleHistoryItem() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskTitleHistoryItem.prototype.getPropertiesManipulator = function () {
return this.modelManipulator.task.properties.title;
};
return TaskTitleHistoryItem;
}(TaskPropertiesHistoryItemBase_1.TaskPropertiesHistoryItemBase));
exports.TaskTitleHistoryItem = TaskTitleHistoryItem;
/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CompositionHistoryItem = void 0;
var tslib_1 = __webpack_require__(0);
var HistoryItem_1 = __webpack_require__(12);
var CompositionHistoryItem = (function (_super) {
(0, tslib_1.__extends)(CompositionHistoryItem, _super);
function CompositionHistoryItem() {
var _this = _super.call(this, null) || this;
_this.historyItems = [];
return _this;
}
CompositionHistoryItem.prototype.redo = function () {
var item;
for (var i = 0; item = this.historyItems[i]; i++)
item.redo();
};
CompositionHistoryItem.prototype.undo = function () {
var item;
for (var i = this.historyItems.length - 1; item = this.historyItems[i]; i--)
item.undo();
};
CompositionHistoryItem.prototype.add = function (historyItem) {
if (historyItem == null)
throw new Error("Can't add null HistoryItem");
this.historyItems.push(historyItem);
};
CompositionHistoryItem.prototype.undoItemsQuery = function () {
this.undo();
};
CompositionHistoryItem.prototype.setModelManipulator = function (modelManipulator) {
if (this.historyItems)
for (var i = 0; i < this.historyItems.length - 1; i++)
this.historyItems[i].setModelManipulator(modelManipulator);
};
return CompositionHistoryItem;
}(HistoryItem_1.HistoryItem));
exports.CompositionHistoryItem = CompositionHistoryItem;
/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CreateTaskHistoryItem = void 0;
var tslib_1 = __webpack_require__(0);
var HistoryItem_1 = __webpack_require__(12);
var CreateTaskHistoryItem = (function (_super) {
(0, tslib_1.__extends)(CreateTaskHistoryItem, _super);
function CreateTaskHistoryItem(modelManipulator, data) {
var _this = _super.call(this, modelManipulator) || this;
_this.data = data;
return _this;
}
CreateTaskHistoryItem.prototype.redo = function () {
this.taskId = this.modelManipulator.task.create(this.data, this.taskId ? this.taskId : null).internalId;
};
CreateTaskHistoryItem.prototype.undo = function () {
this.modelManipulator.task.remove(this.taskId);
};
return CreateTaskHistoryItem;
}(HistoryItem_1.HistoryItem));
exports.CreateTaskHistoryItem = CreateTaskHistoryItem;
/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskPropertyCommandValidation = void 0;
var tslib_1 = __webpack_require__(0);
var ConstraintViolationDialogParameters_1 = __webpack_require__(136);
var TaskPropertyCommandBase_1 = __webpack_require__(26);
var TaskPropertyCommandValidation = (function (_super) {
(0, tslib_1.__extends)(TaskPropertyCommandValidation, _super);
function TaskPropertyCommandValidation() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskPropertyCommandValidation.prototype.executeInternal = function () {
var _this = this;
var parameters = [];
for (var _i = 0; _i < arguments.length; _i++) {
parameters[_i] = arguments[_i];
}
var validationErrors = this.control.isValidateDependenciesRequired() ? this.validate.apply(this, parameters) : [];
var criticalErrors = validationErrors.filter(function (e) { return e.critical; });
if (!validationErrors.length || validationErrors.length > 1 && criticalErrors.length === 0)
return this.executeCore.apply(this, parameters);
else if (validationErrors.length === 1)
this.control.commandManager.showConstraintViolationDialog.execute(new ConstraintViolationDialogParameters_1.ConstraintViolationDialogParameters(validationErrors[0], function () { _this.executeCore.apply(_this, parameters); }));
return false;
};
TaskPropertyCommandValidation.prototype.executeCore = function () {
var parameters = [];
for (var _i = 0; _i < arguments.length; _i++) {
parameters[_i] = arguments[_i];
}
return false;
};
TaskPropertyCommandValidation.prototype.validate = function () {
var parameters = [];
for (var _i = 0; _i < arguments.length; _i++) {
parameters[_i] = arguments[_i];
}
return [];
};
return TaskPropertyCommandValidation;
}(TaskPropertyCommandBase_1.TaskPropertyCommandBase));
exports.TaskPropertyCommandValidation = TaskPropertyCommandValidation;
/***/ }),
/* 48 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MouseHandlerStateBase = void 0;
var tslib_1 = __webpack_require__(0);
var HandlerStateBase_1 = __webpack_require__(39);
var MouseHandlerStateBase = (function (_super) {
(0, tslib_1.__extends)(MouseHandlerStateBase, _super);
function MouseHandlerStateBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
MouseHandlerStateBase.prototype.onMouseDoubleClick = function (_evt) { };
MouseHandlerStateBase.prototype.onMouseDown = function (_evt) { };
MouseHandlerStateBase.prototype.onMouseUp = function (_evt) { };
MouseHandlerStateBase.prototype.onMouseMove = function (_evt) { };
MouseHandlerStateBase.prototype.onMouseWheel = function (_evt) { };
return MouseHandlerStateBase;
}(HandlerStateBase_1.HandlerStateBase));
exports.MouseHandlerStateBase = MouseHandlerStateBase;
/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MouseHandlerDragBaseState = void 0;
var tslib_1 = __webpack_require__(0);
var point_1 = __webpack_require__(4);
var evt_1 = __webpack_require__(10);
var MouseHandlerStateBase_1 = __webpack_require__(48);
var MouseHandlerDragBaseState = (function (_super) {
(0, tslib_1.__extends)(MouseHandlerDragBaseState, _super);
function MouseHandlerDragBaseState() {
return _super !== null && _super.apply(this, arguments) || this;
}
MouseHandlerDragBaseState.prototype.onMouseDown = function (evt) {
this.currentPosition = new point_1.Point(evt_1.EvtUtils.getEventX(evt), evt_1.EvtUtils.getEventY(evt));
if (this.taskEditController.dependencyId != null)
this.selectDependency(null);
};
MouseHandlerDragBaseState.prototype.onMouseUp = function (evt) {
this.onMouseUpInternal(evt);
this.handler.switchToDefaultState();
};
MouseHandlerDragBaseState.prototype.onMouseMove = function (evt) {
evt.preventDefault();
var position = new point_1.Point(evt_1.EvtUtils.getEventX(evt), evt_1.EvtUtils.getEventY(evt));
this.onMouseMoveInternal(position);
this.currentPosition = position;
};
MouseHandlerDragBaseState.prototype.onMouseUpInternal = function (_evt) { };
MouseHandlerDragBaseState.prototype.onMouseMoveInternal = function (_position) { };
return MouseHandlerDragBaseState;
}(MouseHandlerStateBase_1.MouseHandlerStateBase));
exports.MouseHandlerDragBaseState = MouseHandlerDragBaseState;
/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TouchHandlerDragBaseState = void 0;
var tslib_1 = __webpack_require__(0);
var TouchHandlerStateBase_1 = __webpack_require__(75);
var point_1 = __webpack_require__(4);
var touch_1 = __webpack_require__(27);
var TouchHandlerDragBaseState = (function (_super) {
(0, tslib_1.__extends)(TouchHandlerDragBaseState, _super);
function TouchHandlerDragBaseState() {
return _super !== null && _super.apply(this, arguments) || this;
}
TouchHandlerDragBaseState.prototype.onTouchStart = function (evt) {
this.currentPosition = new point_1.Point(touch_1.TouchUtils.getEventX(evt), touch_1.TouchUtils.getEventY(evt));
if (this.taskEditController.dependencyId != null)
this.selectDependency(null);
};
TouchHandlerDragBaseState.prototype.onTouchEnd = function (evt) {
this.onTouchEndInternal(evt);
this.handler.switchToDefaultState();
};
TouchHandlerDragBaseState.prototype.onTouchMove = function (evt) {
evt.preventDefault();
var position = new point_1.Point(touch_1.TouchUtils.getEventX(evt), touch_1.TouchUtils.getEventY(evt));
this.onTouchMoveInternal(position);
this.currentPosition = position;
};
TouchHandlerDragBaseState.prototype.onTouchEndInternal = function (_evt) { };
TouchHandlerDragBaseState.prototype.onTouchMoveInternal = function (_position) { };
return TouchHandlerDragBaseState;
}(TouchHandlerStateBase_1.TouchHandlerStateBase));
exports.TouchHandlerDragBaseState = TouchHandlerDragBaseState;
/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PredefinedStyles = void 0;
var PredefinedStyles = (function () {
function PredefinedStyles() {
}
PredefinedStyles.getPredefinedStringOrUndefined = function (value, predefined) {
var valueToCheck = value && predefined && value.toLowerCase() || undefined;
return valueToCheck && (predefined.filter(function (f) { return f.toLowerCase() === valueToCheck; })[0] || predefined.filter(function (f) { return valueToCheck.indexOf(f.toLowerCase()) > -1; })[0]);
};
PredefinedStyles.fontFamilies = ["helvetica", "times", "courier"];
PredefinedStyles.fontStyles = ["normal", "bold", "italic", "bolditalic"];
PredefinedStyles.headerFooterVisibility = ["everyPage", "firstPage", "never"];
PredefinedStyles.horizontalAlign = ["left", "center", "right"];
PredefinedStyles.overflow = ["linebreak", "ellipsize", "visible", "hidden"];
PredefinedStyles.pageBreak = ["auto", "avoid", "always"];
PredefinedStyles.rowPageBreak = ["auto", "avoid"];
PredefinedStyles.verticalAlign = ["top", "middle", "bottom"];
PredefinedStyles.width = ["auto", "wrap"];
return PredefinedStyles;
}());
exports.PredefinedStyles = PredefinedStyles;
/***/ }),
/* 52 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PdfTaskInfo = void 0;
var point_1 = __webpack_require__(4);
var Color_1 = __webpack_require__(17);
var StyleDef_1 = __webpack_require__(28);
var PdfTaskInfo = (function () {
function PdfTaskInfo() {
}
Object.defineProperty(PdfTaskInfo.prototype, "left", {
get: function () {
var _a;
return ((_a = this.sidePoints) === null || _a === void 0 ? void 0 : _a.length) > 3 ? this.sidePoints[0].x : 0;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PdfTaskInfo.prototype, "top", {
get: function () {
var _a;
return ((_a = this.sidePoints) === null || _a === void 0 ? void 0 : _a.length) > 3 ? this.sidePoints[1].y : 0;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PdfTaskInfo.prototype, "right", {
get: function () {
var _a;
return ((_a = this.sidePoints) === null || _a === void 0 ? void 0 : _a.length) > 3 ? this.sidePoints[2].x : 0;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PdfTaskInfo.prototype, "bottom", {
get: function () {
var _a;
return ((_a = this.sidePoints) === null || _a === void 0 ? void 0 : _a.length) > 3 ? this.sidePoints[3].y : 0;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PdfTaskInfo.prototype, "width", {
get: function () { return this.right - this.left; },
enumerable: false,
configurable: true
});
Object.defineProperty(PdfTaskInfo.prototype, "height", {
get: function () {
var height = this.bottom - this.top;
if (this.isParent)
height -= PdfTaskInfo.defaultParentHeightCorrection;
return height;
},
enumerable: false,
configurable: true
});
PdfTaskInfo.prototype.assign = function (source) {
var _a, _b, _c;
this.isMilestone = source.isMilestone;
this._copyPoints(source.sidePoints);
this.progressWidth = source.progressWidth;
this.isSmallTask = source.isSmallTask;
this.text = source.text;
this.textPosition = source.textPosition;
(_a = this.progressColor) !== null && _a !== void 0 ? _a : (this.progressColor = new Color_1.Color());
this.progressColor.assign(source.progressColor);
(_b = this.taskColor) !== null && _b !== void 0 ? _b : (this.taskColor = new Color_1.Color());
this.taskColor.assign(source.taskColor);
(_c = this.textStyle) !== null && _c !== void 0 ? _c : (this.textStyle = new StyleDef_1.StyleDef());
this.textStyle.assign(source.textStyle);
this.isParent = source.isParent;
};
PdfTaskInfo.prototype._copyPoints = function (source) {
var _this = this;
this.sidePoints = new Array();
source === null || source === void 0 ? void 0 : source.forEach(function (p) { return _this.sidePoints.push(new point_1.Point(p.x, p.y)); });
};
PdfTaskInfo.defaultParentHeightCorrection = 4;
return PdfTaskInfo;
}());
exports.PdfTaskInfo = PdfTaskInfo;
/***/ }),
/* 53 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CellDef = void 0;
var common_1 = __webpack_require__(1);
var StyleDef_1 = __webpack_require__(28);
var CellDef = (function () {
function CellDef(content, colSpan, styles) {
this.content = "";
if (typeof content === "string") {
this.content = content;
this.colSpan = colSpan;
if (styles)
this.appendStyles(styles);
}
else if (content)
this.assign(content);
}
Object.defineProperty(CellDef.prototype, "styles", {
get: function () {
if (!this._styles)
this._styles = new StyleDef_1.StyleDef();
return this._styles;
},
enumerable: false,
configurable: true
});
CellDef.prototype.assign = function (source) {
if ((0, common_1.isDefined)(source["content"]))
this.content = source["content"];
if ((0, common_1.isDefined)(source["colSpan"]))
this.colSpan = source["colSpan"];
if (source["styles"])
this.appendStyles(source["styles"]);
};
CellDef.prototype.appendStyles = function (source) {
if (source)
this.styles.assign(source);
};
CellDef.prototype.hasValue = function () { return true; };
CellDef.prototype.getValue = function () {
var result = {};
result["content"] = this.content;
if (this.colSpan > 1)
result["colSpan"] = this.colSpan;
if (this._styles)
result["styles"] = this._styles.getValue();
return result;
};
return CellDef;
}());
exports.CellDef = CellDef;
/***/ }),
/* 54 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GanttPdfExportProps = exports.PdfDataRange = exports.DataExportMode = exports.ExportMode = void 0;
var size_1 = __webpack_require__(11);
var common_1 = __webpack_require__(1);
var Margin_1 = __webpack_require__(40);
var ExportMode;
(function (ExportMode) {
ExportMode[ExportMode["all"] = 0] = "all";
ExportMode[ExportMode["treeList"] = 1] = "treeList";
ExportMode[ExportMode["chart"] = 2] = "chart";
})(ExportMode = exports.ExportMode || (exports.ExportMode = {}));
var DataExportMode;
(function (DataExportMode) {
DataExportMode[DataExportMode["all"] = 0] = "all";
DataExportMode[DataExportMode["visible"] = 1] = "visible";
})(DataExportMode = exports.DataExportMode || (exports.DataExportMode = {}));
var PdfDataRange = (function () {
function PdfDataRange(start, endDate, startIndex, endIndex) {
var source = !start || start instanceof Date ? { startDate: start, endDate: endDate, startIndex: startIndex, endIndex: endIndex } : start;
if (source)
this.assign(source);
}
PdfDataRange.prototype.assign = function (source) {
if ((0, common_1.isDefined)(source.startDate))
this.startDate = source.startDate instanceof Date ? source.startDate : new Date(source.startDate);
if ((0, common_1.isDefined)(source.endDate))
this.endDate = source.endDate instanceof Date ? source.endDate : new Date(source.endDate);
if ((0, common_1.isDefined)(source.startIndex))
this.startIndex = parseInt(source.startIndex);
if ((0, common_1.isDefined)(source.endIndex))
this.endIndex = parseInt(source.endIndex);
};
return PdfDataRange;
}());
exports.PdfDataRange = PdfDataRange;
var GanttPdfExportProps = (function () {
function GanttPdfExportProps(props) {
this.landscape = false;
this.margins = null;
this.exportMode = ExportMode.all;
this.exportDataMode = DataExportMode.visible;
if (props)
this.assign(props);
}
GanttPdfExportProps.prototype.assign = function (source) {
if (!source)
return;
if ((0, common_1.isDefined)(source["pdfDocument"]))
this.pdfDoc = source["pdfDocument"];
if ((0, common_1.isDefined)(source.pdfDoc))
this.pdfDoc = source.pdfDoc;
this.docCreateMethod = source.docCreateMethod;
if ((0, common_1.isDefined)(source.fileName))
this.fileName = source.fileName;
this.landscape = !!source.landscape;
if ((0, common_1.isDefined)(source.margins))
this.margins = new Margin_1.Margin(source.margins);
if ((0, common_1.isDefined)(source.format)) {
var formatSrc = source.format;
if (typeof formatSrc === "string")
this.format = formatSrc;
else {
var width = parseInt(formatSrc.width);
var height = parseInt(formatSrc.height);
this.pageSize = new size_1.Size(width, height);
}
}
if ((0, common_1.isDefined)(source.exportMode))
this.exportMode = this.getEnumValue(ExportMode, source.exportMode);
if ((0, common_1.isDefined)(source.dateRange)) {
var rangeSrc = source.dateRange;
var isEnum = typeof rangeSrc === "number" || typeof rangeSrc === "string";
if (isEnum)
this.exportDataMode = this.getEnumValue(DataExportMode, rangeSrc);
else
this.dateRange = new PdfDataRange(rangeSrc);
}
};
GanttPdfExportProps.prototype.getEnumValue = function (type, value) {
if (!(0, common_1.isDefined)(type[value]))
return null;
var num = parseInt(value);
if (!isNaN(num))
return num;
return type[value];
};
GanttPdfExportProps.autoFormatKey = "auto";
return GanttPdfExportProps;
}());
exports.GanttPdfExportProps = GanttPdfExportProps;
/***/ }),
/* 55 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GanttView = void 0;
var BarManager_1 = __webpack_require__(89);
var browser_1 = __webpack_require__(8);
var CommandManager_1 = __webpack_require__(90);
var CreateResourceHistoryItem_1 = __webpack_require__(62);
var CreateTaskHistoryItem_1 = __webpack_require__(46);
var DateRange_1 = __webpack_require__(14);
var DateTimeUtils_1 = __webpack_require__(7);
var DateUtils_1 = __webpack_require__(21);
var EventManager_1 = __webpack_require__(144);
var FullScreenHelperSettings_1 = __webpack_require__(164);
var FullScreenModeHelper_1 = __webpack_require__(165);
var Calculator_1 = __webpack_require__(167);
var HandlerSettings_1 = __webpack_require__(172);
var History_1 = __webpack_require__(173);
var common_1 = __webpack_require__(1);
var ModelChangesDispatcher_1 = __webpack_require__(175);
var ModelManipulator_1 = __webpack_require__(181);
var Exporter_1 = __webpack_require__(196);
var RenderHelper_1 = __webpack_require__(201);
var Settings_1 = __webpack_require__(216);
var size_1 = __webpack_require__(11);
var StripLineSettings_1 = __webpack_require__(82);
var TaskEditController_1 = __webpack_require__(70);
var TaskEditSettings_1 = __webpack_require__(220);
var ValidationController_1 = __webpack_require__(221);
var ValidationControllerSettings_1 = __webpack_require__(223);
var Enums_1 = __webpack_require__(2);
var VisualModel_1 = __webpack_require__(224);
var GanttViewApi_1 = __webpack_require__(241);
var GanttView = (function () {
function GanttView(element, ganttOwner, settings) {
var _this = this;
this.currentSelectedTaskID = "";
this.isFocus = false;
this._updateWithModelReloadLocked = false;
this.scaleCount = 2;
this.tickSize = new size_1.Size(0, 0);
this.currentZoom = 1;
this.stripLinesUpdaterId = null;
this.ganttOwner = ganttOwner;
this.settings = Settings_1.Settings.parse(settings);
this.initValidationController();
this.renderHelper = new RenderHelper_1.RenderHelper(this);
this.renderHelper.initMarkup(element);
this.loadOptionsFromGanttOwner();
this.renderHelper.init(this.tickSize, this.range, this.settings.viewType, this.viewModel, this.settings.firstDayOfWeek);
this.commandManager = new CommandManager_1.CommandManager(this);
this.barManager = new BarManager_1.BarManager(this.commandManager, this.ganttOwner.bars);
this.initTaskEditController();
this.initEventManager();
this.history = new History_1.History(this._getHistoryListener());
this.initFullScreenModeHelper();
this.onWindowResizelHandler = this.onBrowserWindowResize.bind(this);
window.addEventListener("resize", this.onWindowResizelHandler);
this.updateView();
this._scrollTimeOut = setTimeout(function () {
_this.scrollLeftByViewType();
}, 0);
this.initializeStripLinesUpdater();
this.initGanttViewApi();
}
GanttView.prototype.initGanttViewApi = function () {
this.ganttViewApi = new GanttViewApi_1.GanttViewApi(this);
};
GanttView.prototype._getHistoryListener = function () {
var listener = {
onTransactionStart: this.onHistoryTransactionStart.bind(this),
onTransactionEnd: this.onHistoryTransactionEnd.bind(this),
};
return listener;
};
GanttView.prototype.onHistoryTransactionStart = function () { this._updateWithModelReloadLocked = true; };
GanttView.prototype.onHistoryTransactionEnd = function () {
this._updateWithModelReloadLocked = false;
if (this._pendingUpdateInfo) {
this.updateWithDataReload(this._pendingUpdateInfo.keepExpandState);
this._pendingUpdateInfo = null;
}
};
GanttView.prototype.initValidationController = function () {
var _this = this;
var validationControllerSettings = ValidationControllerSettings_1.ValidationControllerSettings.parse({
getViewModel: function () { return _this.viewModel; },
getHistory: function () { return _this.history; },
getModelManipulator: function () { return _this.modelManipulator; },
getRange: function () { return _this.range; },
getValidationSettings: function () { return _this.settings.validation; },
updateOwnerInAutoParentMode: function () { _this.updateOwnerInAutoParentMode(); },
getIsValidateDependenciesRequired: function () { return _this.isValidateDependenciesRequired(); }
});
this.validationController = new ValidationController_1.ValidationController(validationControllerSettings);
};
GanttView.prototype.initTaskEditController = function () {
var _this = this;
var taskEditSettings = TaskEditSettings_1.TaskEditSettings.parse({
destroyTemplate: function (container) { _this.destroyTemplate(container); },
formatDate: function (date) { return _this.getDateFormat(date); },
getRenderHelper: function () { return _this.renderHelper; },
getGanttSettings: function () { return _this.settings; },
getViewModel: function () { return _this.viewModel; },
getCommandManager: function () { return _this.commandManager; },
getModelManipulator: function () { return _this.modelManipulator; },
getValidationController: function () { return _this.validationController; }
});
this.taskEditController = new TaskEditController_1.TaskEditController(taskEditSettings);
};
GanttView.prototype.initEventManager = function () {
var _this = this;
var handlerSettings = HandlerSettings_1.HandlerSettings.parse({
getRenderHelper: function () { return _this.renderHelper; },
getTaskEditController: function () { return _this.taskEditController; },
getHistory: function () { return _this.history; },
getTickSize: function () { return _this.tickSize; },
isFocus: function () { return _this.isFocus; },
getViewModel: function () { return _this.viewModel; },
zoomIn: function (leftPosition) { _this.zoomIn(leftPosition); },
zoomOut: function (leftPosition) { _this.zoomOut(leftPosition); },
selectDependency: function (id) { _this.selectDependency(id); },
showPopupMenu: function (info) { _this.showPopupMenu(info); },
changeGanttTaskSelection: function (id, selected) { _this.changeGanttTaskSelection(id, selected); }
});
this._eventManager = new EventManager_1.EventManager(handlerSettings);
};
Object.defineProperty(GanttView.prototype, "eventManager", {
get: function () {
return this._eventManager;
},
enumerable: false,
configurable: true
});
GanttView.prototype.initFullScreenModeHelper = function () {
var _this = this;
var fullScreenModeSeettings = FullScreenHelperSettings_1.FullScreenHelperSettings.parse({
getMainElement: function () { return _this.getOwnerControlMainElement(); },
adjustControl: function () { _this.adjustOwnerControl(); }
});
this.fullScreenModeHelper = new FullScreenModeHelper_1.FullScreenModeHelper(fullScreenModeSeettings);
};
GanttView.prototype.getDateRange = function (modelStartDate, modelEndDate) {
var start = this.settings.startDateRange || DateUtils_1.DateUtils.adjustStartDateByViewType(new Date(modelStartDate.getTime() - this.getVisibleAreaTime()), this.settings.viewType, this.settings.firstDayOfWeek);
var end = this.settings.endDateRange || DateUtils_1.DateUtils.adjustEndDateByViewType(new Date(modelEndDate.getTime() + this.getVisibleAreaTime()), this.settings.viewType, this.settings.firstDayOfWeek);
return new DateRange_1.DateRange(start, end);
};
GanttView.prototype.getVisibleAreaTime = function () {
var visibleTickCount = Math.ceil(this.renderHelper.getTaskAreaContainerWidth() / this.tickSize.width);
return visibleTickCount * DateUtils_1.DateUtils.getTickTimeSpan(this.settings.viewType);
};
GanttView.prototype.zoomIn = function (leftPos) {
if (leftPos === void 0) { leftPos = this.renderHelper.getTaskAreaContainerWidth() / 2; }
this.ganttViewApi.zoomIn(leftPos);
};
GanttView.prototype.zoomOut = function (leftPos) {
if (leftPos === void 0) { leftPos = this.renderHelper.getTaskAreaContainerWidth() / 2; }
this.ganttViewApi.zoomOut(leftPos);
};
GanttView.prototype.scrollToDate = function (date) {
if (date) {
var scrollDate = date instanceof Date ? DateUtils_1.DateUtils.getOrCreateUTCDate(date) : DateUtils_1.DateUtils.parse(date);
this.scrollToDateCore(scrollDate, 0);
}
};
GanttView.prototype.showDialog = function (name, parameters, callback, afterClosing) {
this.ganttOwner.showDialog(name, parameters, callback, afterClosing);
};
GanttView.prototype.showPopupMenu = function (info) {
this.ganttOwner.showPopupMenu(info);
};
GanttView.prototype.collapseAll = function () {
this.ganttOwner.collapseAll();
};
GanttView.prototype.expandAll = function () {
this.ganttOwner.expandAll();
};
GanttView.prototype.onGanttViewContextMenu = function (evt, key, type) {
return this.ganttOwner.onGanttViewContextMenu(evt, key, type);
};
GanttView.prototype.changeGanttTaskSelection = function (id, selected) {
this.ganttOwner.changeGanttTaskSelection(id, selected);
};
GanttView.prototype.hideTaskEditControl = function () {
this.taskEditController.hide();
};
GanttView.prototype.scrollLeftByViewType = function () {
var adjustedStartDate = DateUtils_1.DateUtils.roundStartDate(this.dataRange.start, this.settings.viewType);
this.scrollToDateCore(adjustedStartDate, 1);
};
GanttView.prototype.scrollToDateCore = function (date, addLeftPos) {
this.renderHelper.setTaskAreaContainerScrollLeftToDate(date, addLeftPos);
};
GanttView.prototype.onVisualModelChanged = function () {
this.resetAndUpdate();
};
GanttView.prototype.initializeStripLinesUpdater = function () {
var _this = this;
if (this.settings.stripLines.showCurrentTime)
this.stripLinesUpdaterId = setInterval(function () {
_this.renderHelper.recreateStripLines();
}, Math.max(this.settings.stripLines.currentTimeUpdateInterval, 100));
};
GanttView.prototype.clearStripLinesUpdater = function () {
if (this.stripLinesUpdaterId)
clearInterval(this.stripLinesUpdaterId);
this.stripLinesUpdaterId = null;
};
GanttView.prototype.getGanttViewStartDate = function (tasks) {
if (!tasks)
return new Date();
var dates = tasks.map(function (t) { return typeof t.start === "string" ? new Date(t.start) : t.start; }).filter(function (d) { return (0, common_1.isDefined)(d); });
return dates.length > 0 ? dates.reduce(function (min, d) { return d < min ? d : min; }, dates[0]) : new Date();
};
GanttView.prototype.getGanttViewEndDate = function (tasks) {
if (!tasks)
return new Date();
var dates = tasks.map(function (t) { return typeof t.end === "string" ? new Date(t.end) : t.end; }).filter(function (d) { return (0, common_1.isDefined)(d); });
return dates.length > 0 ? dates.reduce(function (max, d) { return d > max ? d : max; }, dates[0]) : new Date();
};
GanttView.prototype.getTask = function (index) {
var item = this.getViewItem(index);
return item === null || item === void 0 ? void 0 : item.task;
};
GanttView.prototype.getViewItem = function (index) {
var _a;
return (_a = this.viewModel) === null || _a === void 0 ? void 0 : _a.items[index];
};
GanttView.prototype.isValidateDependenciesRequired = function () {
return this.settings.validation.validateDependencies && this.settings.showDependencies;
};
GanttView.prototype.updateTickSizeWidth = function () {
this.tickSize.width = this.renderHelper.etalonScaleItemWidths * this.currentZoom;
};
GanttView.prototype.updateView = function () {
this.onBeginUpdateView();
this.renderHelper.setTimeScaleContainerScrollLeft(this.taskAreaContainerScrollLeft);
this.processScroll(false);
this.processScroll(true);
this.ganttOwner.onGanttScroll(this.taskAreaContainerScrollTop);
this.onEndUpdateView();
};
GanttView.prototype.onBeginUpdateView = function () {
this[GanttView.taskAreaScrollTopKey] = this.renderHelper.taskAreaContainerScrollTop;
this[GanttView.taskAreaScrollLeftKey] = this.renderHelper.taskAreaContainerScrollLeft;
};
GanttView.prototype.onEndUpdateView = function () {
delete this[GanttView.taskAreaScrollTopKey];
delete this[GanttView.taskAreaScrollLeftKey];
delete this[GanttView.taskTextHeightKey];
};
Object.defineProperty(GanttView.prototype, "taskAreaContainerScrollTop", {
get: function () {
var _a;
return (_a = this[GanttView.taskAreaScrollTopKey]) !== null && _a !== void 0 ? _a : this.renderHelper.taskAreaContainerScrollTop;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttView.prototype, "taskAreaContainerScrollLeft", {
get: function () {
var _a;
return (_a = this[GanttView.taskAreaScrollLeftKey]) !== null && _a !== void 0 ? _a : this.renderHelper.taskAreaContainerScrollLeft;
},
enumerable: false,
configurable: true
});
GanttView.prototype.processScroll = function (isVertical) {
this.hideTaskEditControl();
this.renderHelper.processScroll(isVertical);
};
GanttView.prototype.allowTaskAreaBorders = function (isVerticalScroll) {
return isVerticalScroll ? this.settings.areHorizontalBordersEnabled : this.settings.areVerticalBordersEnabled;
};
GanttView.prototype.getScaleItemText = function (index, scale) {
return this.renderHelper.getScaleItemText(index, scale);
};
GanttView.prototype.getTaskText = function (index) {
return this.renderHelper.getTaskText(index);
};
GanttView.prototype.rowHasChildren = function (index) {
var item = this.getViewItem(index);
return (item === null || item === void 0 ? void 0 : item.children.length) > 0;
};
GanttView.prototype.rowHasSelection = function (index) {
var item = this.getViewItem(index);
return item === null || item === void 0 ? void 0 : item.selected;
};
GanttView.prototype.getAllVisibleTaskIndices = function (start, end) { return this.viewModel.getAllVisibleTaskIndices(start, end); };
GanttView.prototype.getVisibleDependencyKeysByTaskRange = function (indices) {
var model = this.viewModel;
var taskKeys = indices.map(function (i) { return model.tasks.items[i].internalId; });
var dependencies = model.dependencies.items;
return dependencies.filter(function (d) { return taskKeys.indexOf(d.successorId) > -1 || taskKeys.indexOf(d.predecessorId) > -1; }).map(function (d) { return d.internalId; });
};
GanttView.prototype.getTreeListTableStyle = function () {
var _a, _b;
return (_b = (_a = this.ganttOwner).getTreeListTableStyle) === null || _b === void 0 ? void 0 : _b.call(_a);
};
GanttView.prototype.getTreeListColCount = function () {
var _a, _b;
return (_b = (_a = this.ganttOwner).getTreeListColCount) === null || _b === void 0 ? void 0 : _b.call(_a);
};
GanttView.prototype.getTreeListHeaderInfo = function (colIndex) {
var _a, _b;
return (_b = (_a = this.ganttOwner).getTreeListHeaderInfo) === null || _b === void 0 ? void 0 : _b.call(_a, colIndex);
};
GanttView.prototype.getTreeListCellInfo = function (rowIndex, colIndex) {
var _a, _b;
return (_b = (_a = this.ganttOwner).getTreeListCellInfo) === null || _b === void 0 ? void 0 : _b.call(_a, rowIndex, colIndex);
};
GanttView.prototype.exportToPdf = function (options) {
var _a;
(_a = options["docCreateMethod"]) !== null && _a !== void 0 ? _a : (options["docCreateMethod"] = this.getDefaultPdfDocCreateMethod());
var exporter = new Exporter_1.PdfGanttExporter(new Calculator_1.GanttExportCalculator(this, options));
return exporter.export();
};
GanttView.prototype.getDefaultPdfDocCreateMethod = function () {
var _a;
return (_a = window["jspdf"]) === null || _a === void 0 ? void 0 : _a["jsPDF"];
};
GanttView.prototype.getTaskDependencies = function (taskInternalId) {
return this.viewModel.dependencies.items.filter(function (d) { return d.predecessorId == taskInternalId || d.successorId == taskInternalId; });
};
GanttView.prototype.isHighlightRowElementAllowed = function (index) {
var viewItem = this.getViewItem(index);
return index % 2 !== 0 && this.settings.areAlternateRowsEnabled || viewItem.children.length > 0;
};
GanttView.prototype.calculateAutoViewType = function (startDate, endDate) {
var diffInHours = (endDate.getTime() - startDate.getTime()) / (1000 * 3600);
if (diffInHours > 24 * 365)
return Enums_1.ViewType.Years;
if (diffInHours > 24 * 30)
return Enums_1.ViewType.Months;
if (diffInHours > 24 * 7)
return Enums_1.ViewType.Weeks;
if (diffInHours > 24)
return Enums_1.ViewType.Days;
if (diffInHours > 6)
return Enums_1.ViewType.SixHours;
if (diffInHours > 1)
return Enums_1.ViewType.Hours;
return Enums_1.ViewType.TenMinutes;
};
GanttView.prototype.getExternalTaskAreaContainer = function (parent) {
return this.ganttOwner.getExternalTaskAreaContainer(parent);
};
GanttView.prototype.prepareExternalTaskAreaContainer = function (element, info) {
return this.ganttOwner.prepareExternalTaskAreaContainer(element, info);
};
GanttView.prototype.getHeaderHeight = function () {
return this.ganttOwner.getHeaderHeight();
};
GanttView.prototype.changeTaskExpanded = function (publicId, expanded) {
var task = this.getTaskByPublicId(publicId);
if (task)
this.viewModel.changeTaskExpanded(task.internalId, expanded);
};
GanttView.prototype.expandTask = function (id) { this.viewModel.changeTaskExpanded(id, true); };
GanttView.prototype.collapseTask = function (id) { this.viewModel.changeTaskExpanded(id, false); };
GanttView.prototype.showTask = function (id) { this.viewModel.changeTaskVisibility(id, true); };
GanttView.prototype.hideTask = function (id) { this.viewModel.changeTaskVisibility(id, false); };
GanttView.prototype.getTaskVisibility = function (id) { return this.viewModel.getTaskVisibility(id); };
GanttView.prototype.unselectCurrentSelectedTask = function () { this.unselectTask(this.currentSelectedTaskID); };
GanttView.prototype.getTaskSelected = function (id) { return this.viewModel.getTaskSelected(id); };
GanttView.prototype.setViewType = function (viewType, autoPositioning) {
if (autoPositioning === void 0) { autoPositioning = true; }
this.ganttViewApi.setViewType(viewType, autoPositioning);
};
GanttView.prototype.setViewTypeRange = function (min, max) {
this.ganttViewApi.setViewTypeRange(min, max);
};
GanttView.prototype.setTaskTitlePosition = function (taskTitlePosition) {
if (this.settings.taskTitlePosition !== taskTitlePosition) {
this.settings.taskTitlePosition = taskTitlePosition;
this.resetAndUpdate();
}
};
GanttView.prototype.setShowResources = function (showResources) {
if (this.settings.showResources !== showResources) {
this.settings.showResources = showResources;
this.resetAndUpdate();
}
};
GanttView.prototype.toggleResources = function () {
this.setShowResources(!this.settings.showResources);
};
GanttView.prototype.setShowDependencies = function (showDependencies) {
if (this.settings.showDependencies !== showDependencies) {
this.settings.showDependencies = showDependencies;
this.resetAndUpdate();
}
};
GanttView.prototype.toggleDependencies = function () {
this.setShowDependencies(!this.settings.showDependencies);
};
GanttView.prototype.setFirstDayOfWeek = function (firstDayOfWeek) {
if (this.settings.firstDayOfWeek !== firstDayOfWeek) {
this.settings.firstDayOfWeek = firstDayOfWeek;
this.resetAndUpdate();
}
};
GanttView.prototype.setStartDateRange = function (start) {
if (!DateTimeUtils_1.DateTimeUtils.areDatesEqual(this.settings.startDateRange, start)) {
this.settings.startDateRange = new Date(start);
this.resetAndUpdate();
}
};
GanttView.prototype.setEndDateRange = function (end) {
if (!DateTimeUtils_1.DateTimeUtils.areDatesEqual(this.settings.endDateRange, end)) {
this.settings.endDateRange = new Date(end);
this.resetAndUpdate();
}
};
GanttView.prototype.loadOptionsFromGanttOwner = function () {
var _this = this;
var _a;
this.tickSize.height = this.ganttOwner.getRowHeight();
var tasksData = this.ganttOwner.getGanttTasksData();
this.dataRange = new DateRange_1.DateRange(this.getGanttViewStartDate(tasksData), this.getGanttViewEndDate(tasksData));
if (this.settings.viewType == undefined)
this.settings.viewType = this.calculateAutoViewType(this.dataRange.start, this.dataRange.end);
this.updateTickSizeWidth();
this.range = this.getDateRange(this.dataRange.start, this.dataRange.end);
this.dispatcher = new ModelChangesDispatcher_1.ModelChangesDispatcher();
var modelChangesListener = this.ganttOwner.getModelChangesListener();
if (modelChangesListener)
this.dispatcher.onModelChanged.add(modelChangesListener);
this.viewModel = new VisualModel_1.ViewVisualModel(this, tasksData, this.ganttOwner.getGanttDependenciesData(), this.ganttOwner.getGanttResourcesData(), this.ganttOwner.getGanttResourceAssignmentsData(), this.range, this.ganttOwner.getGanttWorkTimeRules());
this.modelManipulator = new ModelManipulator_1.ModelManipulator(this.viewModel, this.dispatcher);
(_a = this.history) === null || _a === void 0 ? void 0 : _a.historyItems.forEach(function (i) { return i.setModelManipulator(_this.modelManipulator); });
};
GanttView.prototype.resetAndUpdate = function () {
this.range = this.getDateRange(this.dataRange.start, this.dataRange.end);
this.viewModel.updateRange(this.range);
this.renderHelper.resetAndUpdate(this.tickSize, this.range, this.settings.viewType, this.viewModel, this.settings.firstDayOfWeek);
if (browser_1.Browser.IE)
this.taskEditController.createElements();
this.updateView();
};
GanttView.prototype.cleanMarkup = function () {
this.renderHelper.taskAreaManagerDetachEvents();
this.taskEditController.detachEvents();
window.removeEventListener("resize", this.onWindowResizelHandler);
this.clearStripLinesUpdater();
this.renderHelper.reset();
clearTimeout(this._scrollTimeOut);
};
GanttView.prototype.checkAndProcessModelChanges = function () {
var tasks = this.ganttOwner.getGanttTasksData();
var changed = this.viewModel.refreshTaskDataIfRequires(tasks);
if (changed)
this.resetAndUpdate();
return changed;
};
GanttView.prototype.updateRowHeights = function (height) {
if (this.tickSize.height !== height) {
this.tickSize.height = height;
var leftPosition = this.renderHelper.getTaskAreaContainerScrollLeft();
this.resetAndUpdate();
this.renderHelper.setTaskAreaContainerScrollLeft(leftPosition);
}
};
GanttView.prototype.selectTask = function (id) {
this.selectDependency(null);
this.viewModel.changeTaskSelected(id, true);
this.currentSelectedTaskID = id;
this.updateBarManager();
};
GanttView.prototype.unselectTask = function (id) {
this.viewModel.changeTaskSelected(id, false);
this.updateBarManager();
};
GanttView.prototype.selectTaskById = function (publicId) {
this.unselectCurrentSelectedTask();
var task = this.getTaskByPublicId(publicId);
if (task)
this.selectTask(task.internalId);
};
GanttView.prototype.selectDependency = function (id) {
this.taskEditController.selectDependency(id);
this.renderHelper.createConnectorLines();
};
GanttView.prototype.getTaskAreaContainer = function () {
return this.renderHelper.taskAreaContainer;
};
GanttView.prototype.setWidth = function (value) {
this.renderHelper.setMainElementWidth(value);
};
GanttView.prototype.setHeight = function (value) {
this.renderHelper.setMainElementHeight(value);
};
GanttView.prototype.setAllowSelection = function (value) {
this.settings.allowSelectTask = value;
};
GanttView.prototype.setEditingSettings = function (value) {
this.settings.editing = value;
this.updateBarManager();
};
GanttView.prototype.setValidationSettings = function (value) {
this.settings.validation = value;
};
GanttView.prototype.setRowLinesVisible = function (value) {
this.settings.areHorizontalBordersEnabled = value;
this.renderHelper.prepareTaskAreaContainer();
this.resetAndUpdate();
};
GanttView.prototype.setStripLines = function (stripLines) {
this.settings.stripLines = StripLineSettings_1.StripLineSettings.parse(stripLines);
this.clearStripLinesUpdater();
this.initializeStripLinesUpdater();
this.renderHelper.recreateStripLines();
};
GanttView.prototype.deleteTask = function (key) {
var task = this.getTaskByPublicId(key.toString());
if (task)
this.commandManager.removeTaskCommand.execute(task.internalId, false, true);
};
GanttView.prototype.insertTask = function (data) {
if (data) {
var parentId = data.parentId != null ? String(data.parentId) : null;
var parent_1 = this.getTaskByPublicId(parentId);
var rootId = this.viewModel.getRootTaskId();
var start = typeof data.start === "string" ? new Date(data.start) : data.start;
var end = typeof data.end === "string" ? new Date(data.end) : data.end;
var taskData = {
parentId: rootId && parentId === rootId ? parentId : parent_1 === null || parent_1 === void 0 ? void 0 : parent_1.internalId,
title: data.title,
start: start,
end: end,
progress: parseInt(data.progress) || 0,
color: data.color
};
if (this.commandManager.createTaskCommand.execute(taskData))
return this.getLastInsertedTaskId();
}
return "";
};
GanttView.prototype.updateTask = function (key, data) {
var task = this.getTaskByPublicId(key.toString());
var dataToExecute = this._getTaskDataForUpdate(data, task);
if (dataToExecute)
this.commandManager.updateTaskCommand.execute(task.internalId, dataToExecute);
};
GanttView.prototype.getTaskData = function (key) {
var task = this.getTaskByPublicId(key.toString());
if (task)
return this.viewModel.getTaskObjectForDataSource(task);
};
GanttView.prototype.insertDependency = function (data) {
if (!data)
return;
var predecessorId = String(data.predecessorId);
var predecessor = this.getTaskByPublicId(predecessorId);
var successorId = String(data.successorId);
var successor = this.getTaskByPublicId(successorId);
var type = data.type;
if (predecessor && successor && this.validationController.canCreateDependency(predecessorId, successorId))
this.commandManager.createDependencyCommand.execute(predecessor.internalId, successor.internalId, type);
};
GanttView.prototype.deleteDependency = function (key) {
var internalKey = this.viewModel.convertPublicToInternalKey("dependency", key);
if ((0, common_1.isDefined)(internalKey))
this.commandManager.removeDependencyCommand.execute(internalKey);
};
GanttView.prototype.getDependencyData = function (key) {
return this.viewModel.getDependencyObjectForDataSource(key);
};
GanttView.prototype.insertResource = function (data, taskKeys) {
var _this = this;
if (data) {
var callback = function (id) {
if ((0, common_1.isDefined)(taskKeys))
for (var i = 0; i < taskKeys.length; i++)
_this.assignResourceToTask(id, taskKeys[i]);
};
this.commandManager.createResourceCommand.execute(String(data.text), data.color && String(data.color), callback);
}
};
GanttView.prototype.deleteResource = function (key) {
var internalKey = this.viewModel.convertPublicToInternalKey("resource", key);
if ((0, common_1.isDefined)(internalKey))
this.commandManager.removeResourceCommand.execute(internalKey);
};
GanttView.prototype.assignResourceToTask = function (resourceKey, taskKey) {
var resourceInternalKey = this.viewModel.convertPublicToInternalKey("resource", resourceKey);
var taskInternalKey = this.viewModel.convertPublicToInternalKey("task", taskKey);
if ((0, common_1.isDefined)(resourceInternalKey) && (0, common_1.isDefined)(taskInternalKey))
this.commandManager.assignResourceCommand.execute(resourceInternalKey, taskInternalKey);
};
GanttView.prototype.unassignResourceFromTask = function (resourceKey, taskKey) {
var assignment = this.viewModel.findAssignment(resourceKey, taskKey);
if (assignment)
this.commandManager.deassignResourceCommand.execute(assignment.internalId);
};
GanttView.prototype.unassignAllResourcesFromTask = function (taskPublicKey) {
var _this = this;
var taskInternalKey = this.viewModel.convertPublicToInternalKey("task", taskPublicKey);
var assignments = this.viewModel.findAllTaskAssignments(taskInternalKey);
assignments.forEach(function (assignment) { return _this.commandManager.deassignResourceCommand.execute(assignment.internalId); });
};
GanttView.prototype.getResourceData = function (key) {
return this.viewModel.getResourceObjectForDataSource(key);
};
GanttView.prototype.getResourceAssignmentData = function (key) {
return this.viewModel.getResourceAssignmentObjectForDataSource(key);
};
GanttView.prototype.getTaskResources = function (key) {
var model = this.viewModel;
var task = model.getItemByPublicId("task", key);
return task && model.getAssignedResources(task).items;
};
GanttView.prototype.getVisibleTaskKeys = function () { return this.viewModel.getVisibleTasks().map(function (t) { return t.id; }); };
GanttView.prototype.getVisibleDependencyKeys = function () { return this.viewModel.getVisibleDependencies().map(function (d) { return d.id; }); };
GanttView.prototype.getVisibleResourceKeys = function () { return this.viewModel.getVisibleResources().map(function (r) { return r.id; }); };
GanttView.prototype.getVisibleResourceAssignmentKeys = function () { return this.viewModel.getVisibleResourceAssignments().map(function (a) { return a.id; }); };
GanttView.prototype.getTasksExpandedState = function () { return this.viewModel.getTasksExpandedState(); };
GanttView.prototype.applyTasksExpandedState = function (state) { this.viewModel.applyTasksExpandedState(state); };
GanttView.prototype.updateWithDataReload = function (keepExpandState) {
if (this._updateWithModelReloadLocked) {
this._pendingUpdateInfo = { keepExpandState: keepExpandState };
return;
}
var state = keepExpandState && this.getTasksExpandedState();
this.loadOptionsFromGanttOwner();
if (keepExpandState)
this.applyTasksExpandedState(state);
else
this.resetAndUpdate();
};
GanttView.prototype.setTaskValue = function (id, fieldName, newValue) {
var manager = this.commandManager;
var task = this.getTaskByPublicId(id);
if (task) {
if (fieldName === "title") {
var checkedNewValue = newValue ? newValue : "";
return manager.changeTaskTitleCommand.execute(task.internalId, checkedNewValue);
}
if (fieldName === "progress") {
var newProgress = Math.max(newValue, 0);
newProgress = Math.min(newValue, 100);
return manager.changeTaskProgressCommand.execute(task.internalId, newProgress);
}
if (fieldName === "start")
return manager.changeTaskStartCommand.execute(task.internalId, DateTimeUtils_1.DateTimeUtils.getMinDate(newValue, task.end));
if (fieldName === "end")
return manager.changeTaskEndCommand.execute(task.internalId, DateTimeUtils_1.DateTimeUtils.getMaxDate(newValue, task.start));
}
return false;
};
GanttView.prototype.getLastInsertedTaskId = function () {
var createTaskItems = this.history.historyItems.filter(function (i) { return i instanceof CreateTaskHistoryItem_1.CreateTaskHistoryItem; });
var lastItem = createTaskItems[createTaskItems.length - 1];
return lastItem && lastItem.taskId;
};
GanttView.prototype.getLastInsertedResource = function () {
var createTaskItems = this.history.historyItems.filter(function (i) { return i instanceof CreateResourceHistoryItem_1.CreateResourceHistoryItem; });
var lastItem = createTaskItems[createTaskItems.length - 1];
return lastItem && lastItem.resource;
};
GanttView.prototype.getTaskByPublicId = function (id) {
return this.viewModel.tasks.getItemByPublicId(id);
};
GanttView.prototype.getPrevTask = function (taskId) {
var item = this.viewModel.findItem(taskId);
var parent = item.parent || this.viewModel.root;
var index = parent.children.indexOf(item) - 1;
return index > -1 ? item.parent.children[index].task : item.parent.task;
};
GanttView.prototype.updateCreatedTaskIdAfterServerUpdate = function (internalId, id) {
var item = this.viewModel.findItem(internalId);
var task = item && item.task;
if (task)
task.id = id;
};
GanttView.prototype.getTaskIdByInternalId = function (internalId) {
var item = this.viewModel.findItem(internalId);
var task = item && item.task;
return task ? task.id : null;
};
GanttView.prototype.isTaskHasChildren = function (taskId) {
var item = this.viewModel.findItem(taskId);
return item && item.children.length > 0;
};
GanttView.prototype.requireFirstLoadParentAutoCalc = function () {
var owner = this.ganttOwner;
return owner.getRequireFirstLoadParentAutoCalc && owner.getRequireFirstLoadParentAutoCalc();
};
GanttView.prototype.updateOwnerInAutoParentMode = function () {
if (this.viewModel.parentAutoCalc)
this.dispatcher.notifyParentDataRecalculated(this.viewModel.getCurrentTaskData());
};
GanttView.prototype.getOwnerControlMainElement = function () {
var owner = this.ganttOwner;
return owner.getMainElement && owner.getMainElement();
};
GanttView.prototype.adjustOwnerControl = function () {
var owner = this.ganttOwner;
if (owner.adjustControl)
owner.adjustControl();
};
GanttView.prototype.onBrowserWindowResize = function () {
if (this.fullScreenModeHelper.isInFullScreenMode)
this.fullScreenModeHelper.adjustControlInFullScreenMode();
else
this.adjustOwnerControl();
};
GanttView.prototype.applySettings = function (settings, preventViewUpdate) {
if (preventViewUpdate === void 0) { preventViewUpdate = false; }
var ganttSettings = Settings_1.Settings.parse(settings);
var preventUpdate = preventViewUpdate || this.settings.equal(ganttSettings);
this.settings = ganttSettings;
if (!preventUpdate)
this.resetAndUpdate();
};
GanttView.prototype.getDataUpdateErrorCallback = function () {
var _this = this;
var history = this.history;
var currentHistoryItemInfo = history.getCurrentProcessingItemInfo();
return function () {
_this.dispatcher.lock();
history.rollBackAndRemove(currentHistoryItemInfo);
_this.dispatcher.unlock();
_this.updateBarManager();
};
};
GanttView.prototype.setTaskTooltipContentTemplate = function (taskTooltipContentTemplate) {
this.settings.taskTooltipContentTemplate = taskTooltipContentTemplate;
};
GanttView.prototype.setTaskProgressTooltipContentTemplate = function (taskProgressTooltipContentTemplate) {
this.settings.taskProgressTooltipContentTemplate = taskProgressTooltipContentTemplate;
};
GanttView.prototype.setTaskTimeTooltipContentTemplate = function (taskTimeTooltipContentTemplate) {
this.settings.taskTimeTooltipContentTemplate = taskTimeTooltipContentTemplate;
};
GanttView.prototype.setTaskContentTemplate = function (taskContentTemplate) {
this.settings.taskContentTemplate = taskContentTemplate;
};
GanttView.prototype.updateBarManager = function () {
this.barManager.updateItemsState([]);
};
GanttView.prototype.onTaskClick = function (key, evt) {
if (!this.ganttOwner.onTaskClick)
return true;
return this.ganttOwner.onTaskClick(key, evt);
};
GanttView.prototype.onTaskDblClick = function (key, evt) {
if (!this.ganttOwner.onTaskDblClick)
return true;
return this.ganttOwner.onTaskDblClick(key, evt);
};
GanttView.prototype.getDateFormat = function (date) {
return this.ganttOwner.getFormattedDateText ? this.ganttOwner.getFormattedDateText(date) : this.getDefaultDateFormat(date);
};
GanttView.prototype.getDefaultDateFormat = function (date) {
return ("0" + date.getDate()).slice(-2) + "/" + ("0" + (date.getMonth() + 1)).slice(-2) + "/" + date.getFullYear() + " " + ("0" + date.getHours()).slice(-2) + ":" + ("0" + date.getMinutes()).slice(-2);
};
GanttView.prototype.destroyTemplate = function (container) {
this.ganttOwner.destroyTemplate ? this.ganttOwner.destroyTemplate(container) : container.innerHTML = "";
};
GanttView.prototype.showTaskEditDialog = function () {
this.commandManager.showTaskEditDialog.execute();
};
GanttView.prototype.showTaskDetailsDialog = function (taskPublicKey) {
var task = this.getTaskByPublicId(taskPublicKey);
if (task)
this.commandManager.showTaskEditDialog.execute(task, true);
};
GanttView.prototype.showResourcesDialog = function () {
this.commandManager.showResourcesDialog.execute();
};
GanttView.prototype.getCommandByKey = function (key) {
return this.commandManager.getCommand(key);
};
GanttView.prototype._getTaskDataForUpdate = function (data, task) {
var result = {};
if (task && data) {
if ((0, common_1.isDefined)(data.title) && data.title !== task.title)
result["title"] = data.title;
if ((0, common_1.isDefined)(data.progress) && data.progress !== task.progress)
result["progress"] = data.progress;
if ((0, common_1.isDefined)(data.start) && data.start !== task.start)
result["start"] = data.start;
if ((0, common_1.isDefined)(data.end) && data.end !== task.end)
result["end"] = data.end;
if ((0, common_1.isDefined)(data.color) && data.color !== task.color)
result["color"] = data.color;
}
return Object.keys(result).length > 0 ? result : null;
};
GanttView.cachedPrefix = "cached_";
GanttView.taskAreaScrollLeftKey = GanttView.cachedPrefix + "taskAreaScrollLeft";
GanttView.taskAreaScrollTopKey = GanttView.cachedPrefix + "taskAreaScrollTop";
GanttView.taskTextHeightKey = GanttView.cachedPrefix + "taskTextHeight";
return GanttView;
}());
exports.GanttView = GanttView;
/***/ }),
/* 56 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Resource = void 0;
var tslib_1 = __webpack_require__(0);
var common_1 = __webpack_require__(1);
var DataObject_1 = __webpack_require__(20);
var Resource = (function (_super) {
(0, tslib_1.__extends)(Resource, _super);
function Resource() {
var _this = _super.call(this) || this;
_this.text = "";
_this.color = "";
return _this;
}
Resource.prototype.assignFromObject = function (sourceObj) {
if ((0, common_1.isDefined)(sourceObj)) {
_super.prototype.assignFromObject.call(this, sourceObj);
this.text = sourceObj.text;
if ((0, common_1.isDefined)(sourceObj.color))
this.color = sourceObj.color;
}
};
return Resource;
}(DataObject_1.DataObject));
exports.Resource = Resource;
/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var list_1 = __webpack_require__(96);
var MathUtils = (function () {
function MathUtils() {
}
MathUtils.round = function (value, digits) {
if (digits === void 0) { digits = 0; }
var factor = MathUtils.powFactor[digits];
return Math.round(value * factor) / factor;
};
MathUtils.numberCloseTo = function (num, to, accuracy) {
if (accuracy === void 0) { accuracy = 0.00001; }
return Math.abs(num - to) < accuracy;
};
MathUtils.restrictValue = function (val, minVal, maxVal) {
if (maxVal < minVal)
maxVal = minVal;
if (val > maxVal)
return maxVal;
else if (val < minVal)
return minVal;
return val;
};
MathUtils.getRandomInt = function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
MathUtils.generateGuid = function () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0;
var v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
};
MathUtils.powFactor = list_1.ListUtils.initByCallback(20, function (ind) { return Math.pow(10, ind); });
MathUtils.somePrimes = [1009, 1013,
1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069,
1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223,
1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291,
1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373,
1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511,
1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583,
1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657,
1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811,
1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889,
1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987,
1993, 1997, 1999, 2003];
return MathUtils;
}());
exports.MathUtils = MathUtils;
/***/ }),
/* 58 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__extends", function() { return __extends; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__assign", function() { return __assign; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__rest", function() { return __rest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__decorate", function() { return __decorate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__param", function() { return __param; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__metadata", function() { return __metadata; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__awaiter", function() { return __awaiter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__generator", function() { return __generator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__createBinding", function() { return __createBinding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__exportStar", function() { return __exportStar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__values", function() { return __values; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spreadArrays", function() { return __spreadArrays; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncGenerator", function() { return __asyncGenerator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncDelegator", function() { return __asyncDelegator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncValues", function() { return __asyncValues; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__makeTemplateObject", function() { return __makeTemplateObject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importStar", function() { return __importStar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importDefault", function() { return __importDefault; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__classPrivateFieldGet", function() { return __classPrivateFieldGet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__classPrivateFieldSet", function() { return __classPrivateFieldSet; });
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
}
return __assign.apply(this, arguments);
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
var __createBinding = Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
function __exportStar(m, o) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
var __setModuleDefault = Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
}
/***/ }),
/* 59 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourceAssigningArguments = void 0;
var tslib_1 = __webpack_require__(0);
var BaseArguments_1 = __webpack_require__(9);
var ResourceAssigningArguments = (function (_super) {
(0, tslib_1.__extends)(ResourceAssigningArguments, _super);
function ResourceAssigningArguments(resourceId, taskId) {
var _this = _super.call(this, null) || this;
_this.values = {
resourceId: resourceId,
taskId: taskId
};
return _this;
}
Object.defineProperty(ResourceAssigningArguments.prototype, "resourceId", {
get: function () { return this.values.resourceId; },
enumerable: false,
configurable: true
});
Object.defineProperty(ResourceAssigningArguments.prototype, "taskId", {
get: function () { return this.values.taskId; },
enumerable: false,
configurable: true
});
return ResourceAssigningArguments;
}(BaseArguments_1.BaseArguments));
exports.ResourceAssigningArguments = ResourceAssigningArguments;
/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AssignResourceHistoryItem = void 0;
var tslib_1 = __webpack_require__(0);
var HistoryItem_1 = __webpack_require__(12);
var AssignResourceHistoryItem = (function (_super) {
(0, tslib_1.__extends)(AssignResourceHistoryItem, _super);
function AssignResourceHistoryItem(modelManipulator, resourceId, taskId) {
var _this = _super.call(this, modelManipulator) || this;
_this.resourceId = resourceId;
_this.taskId = taskId;
return _this;
}
AssignResourceHistoryItem.prototype.redo = function () {
this.assignment = this.modelManipulator.resource.assign(this.resourceId, this.taskId, this.assignment ? this.assignment.internalId : null);
};
AssignResourceHistoryItem.prototype.undo = function () {
this.modelManipulator.resource.deassig(this.assignment.internalId);
};
return AssignResourceHistoryItem;
}(HistoryItem_1.HistoryItem));
exports.AssignResourceHistoryItem = AssignResourceHistoryItem;
/***/ }),
/* 61 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DependencyCommandBase = void 0;
var tslib_1 = __webpack_require__(0);
var CommandBase_1 = __webpack_require__(5);
var SimpleCommandState_1 = __webpack_require__(6);
var DependencyCommandBase = (function (_super) {
(0, tslib_1.__extends)(DependencyCommandBase, _super);
function DependencyCommandBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
DependencyCommandBase.prototype.getState = function () {
return new SimpleCommandState_1.SimpleCommandState(this.isEnabled());
};
return DependencyCommandBase;
}(CommandBase_1.CommandBase));
exports.DependencyCommandBase = DependencyCommandBase;
/***/ }),
/* 62 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CreateResourceHistoryItem = void 0;
var tslib_1 = __webpack_require__(0);
var HistoryItem_1 = __webpack_require__(12);
var CreateResourceHistoryItem = (function (_super) {
(0, tslib_1.__extends)(CreateResourceHistoryItem, _super);
function CreateResourceHistoryItem(modelManipulator, text, color, callback) {
if (color === void 0) { color = ""; }
var _this = _super.call(this, modelManipulator) || this;
_this.text = text;
_this.color = color;
_this.createCallback = callback;
return _this;
}
CreateResourceHistoryItem.prototype.redo = function () {
this.resource = this.modelManipulator.resource.create(this.text, this.color, this.resource ? this.resource.internalId : null, this.createCallback);
};
CreateResourceHistoryItem.prototype.undo = function () {
this.modelManipulator.resource.remove(this.resource.internalId);
};
return CreateResourceHistoryItem;
}(HistoryItem_1.HistoryItem));
exports.CreateResourceHistoryItem = CreateResourceHistoryItem;
/***/ }),
/* 63 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskInsertingArguments = void 0;
var tslib_1 = __webpack_require__(0);
var BaseArguments_1 = __webpack_require__(9);
var TaskInsertingArguments = (function (_super) {
(0, tslib_1.__extends)(TaskInsertingArguments, _super);
function TaskInsertingArguments(key, data) {
var _this = _super.call(this, key) || this;
_this.values = data !== null && data !== void 0 ? data : {};
return _this;
}
Object.defineProperty(TaskInsertingArguments.prototype, "start", {
get: function () { return this.values.start; },
enumerable: false,
configurable: true
});
Object.defineProperty(TaskInsertingArguments.prototype, "end", {
get: function () { return this.values.end; },
enumerable: false,
configurable: true
});
Object.defineProperty(TaskInsertingArguments.prototype, "title", {
get: function () { return this.values.title; },
enumerable: false,
configurable: true
});
Object.defineProperty(TaskInsertingArguments.prototype, "progress", {
get: function () { return this.values.progress; },
enumerable: false,
configurable: true
});
Object.defineProperty(TaskInsertingArguments.prototype, "parentId", {
get: function () { return this.values.parentId; },
enumerable: false,
configurable: true
});
Object.defineProperty(TaskInsertingArguments.prototype, "color", {
get: function () { return this.values.color; },
enumerable: false,
configurable: true
});
return TaskInsertingArguments;
}(BaseArguments_1.BaseArguments));
exports.TaskInsertingArguments = TaskInsertingArguments;
/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskColorHistoryItem = void 0;
var tslib_1 = __webpack_require__(0);
var TaskPropertiesHistoryItemBase_1 = __webpack_require__(15);
var TaskColorHistoryItem = (function (_super) {
(0, tslib_1.__extends)(TaskColorHistoryItem, _super);
function TaskColorHistoryItem() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskColorHistoryItem.prototype.getPropertiesManipulator = function () {
return this.modelManipulator.task.properties.color;
};
return TaskColorHistoryItem;
}(TaskPropertiesHistoryItemBase_1.TaskPropertiesHistoryItemBase));
exports.TaskColorHistoryItem = TaskColorHistoryItem;
/***/ }),
/* 65 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskMoveHistoryItem = void 0;
var tslib_1 = __webpack_require__(0);
var TaskPropertiesHistoryItemBase_1 = __webpack_require__(15);
var TaskMoveHistoryItem = (function (_super) {
(0, tslib_1.__extends)(TaskMoveHistoryItem, _super);
function TaskMoveHistoryItem() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskMoveHistoryItem.prototype.getPropertiesManipulator = function () {
return this.modelManipulator.task.properties.move;
};
return TaskMoveHistoryItem;
}(TaskPropertiesHistoryItemBase_1.TaskPropertiesHistoryItemBase));
exports.TaskMoveHistoryItem = TaskMoveHistoryItem;
/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Time = void 0;
var Time = (function () {
function Time(h, min, sec, msec) {
if (h === void 0) { h = 0; }
if (min === void 0) { min = 0; }
if (sec === void 0) { sec = 0; }
if (msec === void 0) { msec = 0; }
this._hour = 0;
this._min = 0;
this._sec = 0;
this._msec = 0;
this._fullmsec = 0;
this.hour = h;
this.min = min;
this.sec = sec;
this.msec = msec;
}
Object.defineProperty(Time.prototype, "hour", {
get: function () { return this._hour; },
set: function (h) {
if (h >= 0 && h < 24) {
this._hour = h;
this.updateFullMilleconds();
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(Time.prototype, "min", {
get: function () { return this._min; },
set: function (m) {
if (m >= 0 && m < 60) {
this._min = m;
this.updateFullMilleconds();
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(Time.prototype, "sec", {
get: function () { return this._sec; },
set: function (s) {
if (s >= 0 && s < 60) {
this._sec = s;
this.updateFullMilleconds();
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(Time.prototype, "msec", {
get: function () { return this._msec; },
set: function (ms) {
if (ms >= 0 && ms < 1000) {
this._msec = ms;
this.updateFullMilleconds();
}
},
enumerable: false,
configurable: true
});
Time.prototype.updateFullMilleconds = function () {
var minutes = this._hour * 60 + this._min;
var sec = minutes * 60 + this._sec;
this._fullmsec = sec * 1000 + this._msec;
};
Time.prototype.getTimeInMilleconds = function () {
return this._fullmsec;
};
return Time;
}());
exports.Time = Time;
/***/ }),
/* 67 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TimeRange = void 0;
var DateTimeUtils_1 = __webpack_require__(7);
var TimeRange = (function () {
function TimeRange(start, end) {
var diff = DateTimeUtils_1.DateTimeUtils.caclTimeDifference(start, end);
if (diff >= 0) {
this._start = start;
this._end = end;
}
else {
this._start = end;
this._end = start;
}
}
Object.defineProperty(TimeRange.prototype, "start", {
get: function () { return this._start; },
set: function (time) {
if (time && DateTimeUtils_1.DateTimeUtils.caclTimeDifference(time, this._end) >= 0)
this._start = time;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TimeRange.prototype, "end", {
get: function () { return this._end; },
set: function (time) {
if (time && DateTimeUtils_1.DateTimeUtils.caclTimeDifference(this._start, time) >= 0)
this._end = time;
},
enumerable: false,
configurable: true
});
TimeRange.prototype.isTimeInRange = function (time) {
return DateTimeUtils_1.DateTimeUtils.caclTimeDifference(this._start, time) >= 0 && DateTimeUtils_1.DateTimeUtils.caclTimeDifference(time, this._end) >= 0;
};
TimeRange.prototype.hasIntersect = function (range) {
return this.isTimeInRange(range.start) || this.isTimeInRange(range.end) || range.isTimeInRange(this.start) || range.isTimeInRange(this.end);
};
TimeRange.prototype.concatWith = function (range) {
if (!this.hasIntersect(range))
return false;
this.start = DateTimeUtils_1.DateTimeUtils.getMinTime(this.start, range.start);
this.end = DateTimeUtils_1.DateTimeUtils.getMaxTime(this.end, range.end);
return true;
};
return TimeRange;
}());
exports.TimeRange = TimeRange;
/***/ }),
/* 68 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DayOfWeekMonthlyOccurrence = void 0;
var DayOfWeekMonthlyOccurrence;
(function (DayOfWeekMonthlyOccurrence) {
DayOfWeekMonthlyOccurrence[DayOfWeekMonthlyOccurrence["First"] = 0] = "First";
DayOfWeekMonthlyOccurrence[DayOfWeekMonthlyOccurrence["Second"] = 1] = "Second";
DayOfWeekMonthlyOccurrence[DayOfWeekMonthlyOccurrence["Third"] = 2] = "Third";
DayOfWeekMonthlyOccurrence[DayOfWeekMonthlyOccurrence["Forth"] = 3] = "Forth";
DayOfWeekMonthlyOccurrence[DayOfWeekMonthlyOccurrence["Last"] = 4] = "Last";
})(DayOfWeekMonthlyOccurrence = exports.DayOfWeekMonthlyOccurrence || (exports.DayOfWeekMonthlyOccurrence = {}));
/***/ }),
/* 69 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.HandlerBase = void 0;
var TaskEditController_1 = __webpack_require__(70);
var Enums_1 = __webpack_require__(2);
var HandlerBase = (function () {
function HandlerBase(settings) {
this.settings = settings;
this.switchToDefaultState();
}
HandlerBase.prototype.switchState = function (state) {
if (this.state)
this.state.finish();
this.state = state;
this.state.start();
};
HandlerBase.prototype.switchToDefaultState = function () {
throw new Error("Not implemented");
};
HandlerBase.prototype.getEventSource = function (initSource) {
var source = initSource.nodeType === Node.ELEMENT_NODE ? initSource : initSource.parentNode;
var className = source.classList[0];
return HandlerBase.classToSource[className] || Enums_1.MouseEventSource.TaskArea;
};
HandlerBase.classToSource = (_a = {},
_a[TaskEditController_1.TaskEditController.CLASSNAMES.TASK_EDIT_PROGRESS] = Enums_1.MouseEventSource.TaskEdit_Progress,
_a[TaskEditController_1.TaskEditController.CLASSNAMES.TASK_EDIT_START] = Enums_1.MouseEventSource.TaskEdit_Start,
_a[TaskEditController_1.TaskEditController.CLASSNAMES.TASK_EDIT_END] = Enums_1.MouseEventSource.TaskEdit_End,
_a[TaskEditController_1.TaskEditController.CLASSNAMES.TASK_EDIT_FRAME] = Enums_1.MouseEventSource.TaskEdit_Frame,
_a[TaskEditController_1.TaskEditController.CLASSNAMES.TASK_EDIT_DEPENDENCY_RIGTH] = Enums_1.MouseEventSource.TaskEdit_DependencyStart,
_a[TaskEditController_1.TaskEditController.CLASSNAMES.TASK_EDIT_DEPENDENCY_LEFT] = Enums_1.MouseEventSource.TaskEdit_DependencyFinish,
_a[TaskEditController_1.TaskEditController.CLASSNAMES.TASK_EDIT_SUCCESSOR_DEPENDENCY_RIGTH] = Enums_1.MouseEventSource.Successor_DependencyStart,
_a[TaskEditController_1.TaskEditController.CLASSNAMES.TASK_EDIT_SUCCESSOR_DEPENDENCY_LEFT] = Enums_1.MouseEventSource.Successor_DependencyFinish,
_a);
return HandlerBase;
}());
exports.HandlerBase = HandlerBase;
/***/ }),
/* 70 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskEditController = void 0;
var Enums_1 = __webpack_require__(2);
var DateRange_1 = __webpack_require__(14);
var dom_1 = __webpack_require__(3);
var browser_1 = __webpack_require__(8);
var TaskEditTooltip_1 = __webpack_require__(146);
var TooltipSettings_1 = __webpack_require__(71);
var TaskEditController = (function () {
function TaskEditController(settings) {
this.showInfoDelay = 1000;
this.taskIndex = -1;
this.successorIndex = -1;
this.isEditingInProgress = false;
this.disableTaskEditBox = false;
this.isTaskEditBoxShown = false;
this.settings = settings;
this.createElements();
}
Object.defineProperty(TaskEditController.prototype, "taskId", {
get: function () {
return this.viewModel.items[this.taskIndex].task.internalId;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskEditController.prototype, "successorId", {
get: function () {
return this.viewModel.items[this.successorIndex].task.internalId;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskEditController.prototype, "task", {
get: function () {
return this.viewItem.task;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskEditController.prototype, "viewItem", {
get: function () {
return this.viewModel.items[this.taskIndex];
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskEditController.prototype, "renderHelper", {
get: function () {
return this.settings.getRenderHelper();
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskEditController.prototype, "ganttSettings", {
get: function () {
return this.settings.getGanttSettings();
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskEditController.prototype, "viewModel", {
get: function () {
return this.settings.getViewModel();
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskEditController.prototype, "commandManager", {
get: function () {
return this.settings.getCommandManager();
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskEditController.prototype, "validationController", {
get: function () {
return this.settings.getValidationController();
},
enumerable: false,
configurable: true
});
TaskEditController.prototype.raiseTaskMoving = function (task, newStart, newEnd, callback) {
return this.settings.getModelManipulator().dispatcher.raiseTaskMoving(task, newStart, newEnd, callback);
};
Object.defineProperty(TaskEditController.prototype, "tooltip", {
get: function () {
var _a;
(_a = this._tooltip) !== null && _a !== void 0 ? _a : (this._tooltip = new TaskEditTooltip_1.TaskEditTooltip(this.baseElement, this.tooltipSettings, this.renderHelper.elementTextHelperCultureInfo));
this._tooltip.tooltipSettings = this.tooltipSettings;
return this._tooltip;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskEditController.prototype, "tooltipSettings", {
get: function () {
var _this = this;
var tooltipSettings = TooltipSettings_1.TooltipSettings.parse({
getHeaderHeight: this.settings.getRenderHelper().header.clientHeight,
getTaskProgressTooltipContentTemplate: this.ganttSettings.taskProgressTooltipContentTemplate,
getTaskTimeTooltipContentTemplate: this.ganttSettings.taskTimeTooltipContentTemplate,
getTaskTooltipContentTemplate: this.ganttSettings.taskTooltipContentTemplate,
destroyTemplate: function (container) { _this.settings.destroyTemplate(container); },
formatDate: function (date) { return _this.settings.formatDate(date); }
});
return tooltipSettings;
},
enumerable: false,
configurable: true
});
TaskEditController.prototype.show = function (taskIndex, delay) {
if (delay === void 0) { delay = 0; }
if (this.isEditingInProgress || this.disableTaskEditBox)
return;
this.taskIndex = taskIndex;
this.hide();
this.changeWrapInfo();
this.baseElement.className = TaskEditController.CLASSNAMES.TASK_EDIT_BOX;
this.displayDependency();
if (this.task.isMilestone() && !this.viewItem.isCustom)
this.baseElement.className = this.baseElement.className + " milestone";
else {
var isHideTaskEditBox = !this.ganttSettings.editing.enabled || !this.ganttSettings.editing.allowTaskUpdate;
if (isHideTaskEditBox)
this.baseElement.className = this.baseElement.className + " hide-updating";
if (this.viewItem.isCustom) {
this.baseElement.classList.add(TaskEditController.CLASSNAMES.TASK_EDIT_BOX_CUSTOM);
delay = this.showInfoDelay;
}
}
this.taskDateRange = new DateRange_1.DateRange(this.task.start, this.task.end);
this.displayTaskEditBox(delay);
this.displayProgressEdit();
this.displayStartEndEditElements();
};
TaskEditController.prototype.displayStartEndEditElements = function () {
if (!this.canUpdateTask()) {
this.startEdit.style.display = "none";
this.endEdit.style.display = "none";
}
else {
this.startEdit.style.display = "block";
this.endEdit.style.display = "block";
}
};
TaskEditController.prototype.displayProgressEdit = function () {
var isEditingAllowed = this.ganttSettings.editing.enabled && this.ganttSettings.editing.allowTaskUpdate;
if (!this.viewItem.isCustom && this.canUpdateTask() && isEditingAllowed && this.wrapInfo.size.width > this.wrapInfo.size.height) {
this.progressEdit.style.display = "block";
this.progressEdit.style.left = ((this.task.progress / 100) * this.wrapInfo.size.width - (this.progressEdit.offsetWidth / 2)) + "px";
}
else
this.progressEdit.style.display = "none";
};
TaskEditController.prototype.displayDependency = function () {
if (!this.ganttSettings.editing.enabled || !this.ganttSettings.editing.allowDependencyInsert || !this.ganttSettings.showDependencies)
this.baseElement.className = this.baseElement.className + " hide-dependency";
};
TaskEditController.prototype.changeWrapInfo = function () {
this.updateWrapInfo();
this.wrapInfo.assignPosition(this.baseElement);
this.wrapInfo.assignSize(this.baseElement);
};
TaskEditController.prototype.displayTaskEditBox = function (delay) {
var _this = this;
if (delay === void 0) { delay = 0; }
var showFunc = function () {
_this.renderHelper.taskArea.appendChild(_this.baseElement);
_this.isTaskEditBoxShown = true;
};
if (delay)
this.timerId = setTimeout(showFunc, delay);
else
showFunc();
};
TaskEditController.prototype.hide = function () {
this.isTaskEditBoxShown = false;
var parentNode = this.baseElement.parentNode;
if (parentNode)
parentNode.removeChild(this.baseElement);
this.tooltip.hide();
clearTimeout(this.timerId);
};
TaskEditController.prototype.cancel = function () {
clearTimeout(this.timerId);
};
TaskEditController.prototype.showTaskInfo = function (posX, delay) {
if (delay === void 0) { delay = 500; }
if (this.timerId)
delay = this.showInfoDelay;
this.tooltip.showInfo(this.task, posX, delay);
};
TaskEditController.prototype.updateWrapInfo = function () {
this.wrapInfo = this.getTaskWrapperElementInfo(this.taskIndex);
this.wrapInfo.position.x--;
};
TaskEditController.prototype.isAllowedToConnectTasks = function (taskIndex) {
var _a;
var successorViewItem = this.viewModel.items[taskIndex];
return this.validationController.canCreateDependency(this.taskId, (_a = successorViewItem.task) === null || _a === void 0 ? void 0 : _a.internalId);
};
TaskEditController.prototype.showDependencySuccessor = function (taskIndex) {
if (this.isAllowedToConnectTasks(taskIndex)) {
this.successorIndex = taskIndex;
var wrapInfo = this.getTaskWrapperElementInfo(taskIndex);
wrapInfo.assignPosition(this.dependencySuccessorBaseElement);
wrapInfo.assignSize(this.dependencySuccessorBaseElement);
wrapInfo.assignSize(this.dependencySuccessorFrame);
this.renderHelper.taskArea.appendChild(this.dependencySuccessorBaseElement);
}
};
TaskEditController.prototype.hideDependencySuccessor = function () {
var parentNode = this.dependencySuccessorBaseElement.parentNode;
if (parentNode)
parentNode.removeChild(this.dependencySuccessorBaseElement);
this.successorIndex = -1;
};
TaskEditController.prototype.processProgress = function (position) {
this.isEditingInProgress = true;
var progressOffset = position.x - this.wrapInfo.position.x;
var progress = 0;
if (position.x > this.wrapInfo.position.x)
if (position.x < this.wrapInfo.position.x + this.wrapInfo.size.width)
progress = Math.round((progressOffset) / this.baseElement.clientWidth * 100);
else
progress = 100;
this.progressEdit.style.left = ((progress / 100) *
this.wrapInfo.size.width - (this.progressEdit.offsetWidth / 2)) + "px";
this.tooltip.showProgress(progress, dom_1.DomUtils.getAbsolutePositionX(this.progressEdit) + this.progressEdit.offsetWidth / 2);
};
TaskEditController.prototype.confirmProgress = function () {
this.isEditingInProgress = false;
var progress = Math.round((this.progressEdit.offsetLeft + (this.progressEdit.offsetWidth / 2)) / this.wrapInfo.size.width * 100);
this.commandManager.changeTaskProgressCommand.execute(this.taskId, progress);
};
TaskEditController.prototype.processEnd = function (position) {
this.baseElement.className = this.baseElement.className + " move";
this.isEditingInProgress = true;
var positionX = position.x > this.wrapInfo.position.x ? position.x : this.wrapInfo.position.x;
var width = positionX - this.wrapInfo.position.x;
this.baseElement.style.width = (width < 1 ? 0 : width) + "px";
var startDate = this.task.start;
var date = this.renderHelper.gridLayoutCalculator.getDateByPos(positionX);
date.setSeconds(0);
if (date < startDate || width < 1)
this.taskDateRange.end.setTime(startDate.getTime());
else
this.taskDateRange.end = this.getCorrectedDate(this.task.end, date);
this.tooltip.showTime(startDate, this.taskDateRange.end, dom_1.DomUtils.getAbsolutePositionX(this.baseElement) + this.baseElement.clientWidth);
};
TaskEditController.prototype.confirmEnd = function () {
this.baseElement.className = TaskEditController.CLASSNAMES.TASK_EDIT_BOX;
this.isEditingInProgress = false;
this.commandManager.changeTaskEndCommand.execute(this.taskId, this.taskDateRange.end);
this.hide();
this.updateWrapInfo();
};
TaskEditController.prototype.processStart = function (position) {
this.baseElement.className = this.baseElement.className + " move";
this.isEditingInProgress = true;
var positionX = position.x < this.wrapInfo.position.x + this.wrapInfo.size.width ? position.x : this.wrapInfo.position.x + this.wrapInfo.size.width;
var width = this.wrapInfo.size.width - (positionX - this.wrapInfo.position.x);
this.baseElement.style.left = positionX + "px";
this.baseElement.style.width = (width < 1 ? 0 : width) + "px";
var endDate = this.task.end;
var date = this.renderHelper.gridLayoutCalculator.getDateByPos(positionX);
date.setSeconds(0);
if (date > endDate || width < 1)
this.taskDateRange.start.setTime(endDate.getTime());
else
this.taskDateRange.start = this.getCorrectedDate(this.task.start, date);
this.tooltip.showTime(this.taskDateRange.start, endDate, dom_1.DomUtils.getAbsolutePositionX(this.baseElement));
};
TaskEditController.prototype.confirmStart = function () {
this.baseElement.className = TaskEditController.CLASSNAMES.TASK_EDIT_BOX;
this.isEditingInProgress = false;
this.commandManager.changeTaskStartCommand.execute(this.taskId, this.taskDateRange.start);
this.hide();
this.updateWrapInfo();
};
TaskEditController.prototype.processMove = function (delta) {
if (this.ganttSettings.editing.enabled && this.ganttSettings.editing.allowTaskUpdate && this.isTaskEditBoxShown) {
this.baseElement.className = this.baseElement.className + " move";
var left = this.baseElement.offsetLeft + delta;
this.baseElement.style.left = left + "px";
var startDate = this.renderHelper.gridLayoutCalculator.getDateByPos(left);
this.taskDateRange.start = this.getCorrectedDate(this.task.start, startDate);
var dateDiff = this.task.start.getTime() - this.taskDateRange.start.getTime();
var endDate = new Date(this.task.end.getTime() - dateDiff);
this.taskDateRange.end = endDate;
this.isEditingInProgress = this.raiseTaskMoving(this.task, this.taskDateRange.start, this.taskDateRange.end, this.onTaskMovingCallback.bind(this));
if (this.isEditingInProgress)
this.tooltip.showTime(this.taskDateRange.start, this.taskDateRange.end, dom_1.DomUtils.getAbsolutePositionX(this.baseElement));
return this.isEditingInProgress;
}
return true;
};
TaskEditController.prototype.onTaskMovingCallback = function (newStart, newEnd) {
if (this.taskDateRange.start === newStart && this.taskDateRange.end === newEnd)
return;
var calculator = this.renderHelper.gridLayoutCalculator;
var newLeft = calculator.getPosByDate(newStart);
var newWidth = calculator.getPosByDate(newEnd) - newLeft;
this.baseElement.style.left = newLeft + "px";
this.baseElement.style.width = (newWidth < 1 ? 0 : newWidth) + "px";
this.taskDateRange.start = newStart;
this.taskDateRange.end = newEnd;
};
TaskEditController.prototype.confirmMove = function () {
if (this.ganttSettings.editing.enabled && this.ganttSettings.editing.allowTaskUpdate) {
if (!this.ganttSettings.editing.allowDependencyInsert)
this.baseElement.className = this.baseElement.className + " hide-dependency";
if (this.isEditingInProgress) {
this.baseElement.className = TaskEditController.CLASSNAMES.TASK_EDIT_BOX;
this.commandManager.taskMoveCommand.execute(this.taskId, this.taskDateRange.start, this.taskDateRange.end);
this.updateWrapInfo();
this.hide();
this.isEditingInProgress = false;
}
}
};
TaskEditController.prototype.getCorrectedDate = function (referenceDate, newDate) {
if (this.ganttSettings.viewType > Enums_1.ViewType.SixHours) {
var year = newDate.getFullYear();
var month = newDate.getMonth();
var day = newDate.getDate();
var hours = this.ganttSettings.viewType === Enums_1.ViewType.Days ? newDate.getHours() : referenceDate.getHours();
var minutes = referenceDate.getMinutes();
var sec = referenceDate.getSeconds();
var msec = referenceDate.getMilliseconds();
return new Date(year, month, day, hours, minutes, sec, msec);
}
return newDate;
};
TaskEditController.prototype.startDependency = function (pos) {
this.dependencyLine = document.createElement("DIV");
this.dependencyLine.className = TaskEditController.CLASSNAMES.TASK_EDIT_DEPENDENCY_LINE;
this.renderHelper.taskArea.appendChild(this.dependencyLine);
this.startPosition = pos;
};
TaskEditController.prototype.processDependency = function (pos) {
this.isEditingInProgress = true;
this.drawline(this.startPosition, pos);
};
TaskEditController.prototype.endDependency = function (type) {
this.isEditingInProgress = false;
if (type != null)
this.commandManager.createDependencyCommand.execute(this.task.internalId, this.successorId, type);
var parentNode = this.dependencyLine.parentNode;
if (parentNode)
parentNode.removeChild(this.dependencyLine);
this.dependencyLine = null;
this.hideDependencySuccessor();
this.hide();
};
TaskEditController.prototype.selectDependency = function (id) {
if (this.ganttSettings.editing.allowDependencyDelete)
this.dependencyId = id;
};
TaskEditController.prototype.isDependencySelected = function (id) {
return this.dependencyId && this.dependencyId === id;
};
TaskEditController.prototype.deleteSelectedDependency = function () {
if (this.dependencyId)
this.commandManager.removeDependencyCommand.execute(this.dependencyId);
};
TaskEditController.prototype.getTaskWrapperElementInfo = function (taskIndex) {
var calculator = this.renderHelper.gridLayoutCalculator;
var info = calculator.getTaskWrapperElementInfo(taskIndex);
info.size.width = calculator.getTaskWidth(taskIndex);
info.size.height = calculator.getTaskHeight(taskIndex);
return info;
};
TaskEditController.prototype.createElements = function () {
this.baseElement = document.createElement("DIV");
this.baseFrame = document.createElement("DIV");
this.baseFrame.className = TaskEditController.CLASSNAMES.TASK_EDIT_FRAME;
this.baseElement.appendChild(this.baseFrame);
this.progressEdit = document.createElement("DIV");
this.progressEdit.className = TaskEditController.CLASSNAMES.TASK_EDIT_PROGRESS;
this.baseFrame.appendChild(this.progressEdit);
this.progressEdit.appendChild(document.createElement("DIV"));
this.dependencyFinish = document.createElement("DIV");
this.dependencyFinish.classList.add(TaskEditController.CLASSNAMES.TASK_EDIT_DEPENDENCY_RIGTH);
if (browser_1.Browser.TouchUI)
this.dependencyFinish.classList.add(TaskEditController.CLASSNAMES.TASK_EDIT_TOUCH);
this.baseFrame.appendChild(this.dependencyFinish);
this.dependencyStart = document.createElement("DIV");
this.dependencyStart.classList.add(TaskEditController.CLASSNAMES.TASK_EDIT_DEPENDENCY_LEFT);
if (browser_1.Browser.TouchUI)
this.dependencyStart.classList.add(TaskEditController.CLASSNAMES.TASK_EDIT_TOUCH);
this.baseFrame.appendChild(this.dependencyStart);
this.startEdit = document.createElement("DIV");
this.startEdit.className = TaskEditController.CLASSNAMES.TASK_EDIT_START;
this.baseFrame.appendChild(this.startEdit);
this.endEdit = document.createElement("DIV");
this.endEdit.className = TaskEditController.CLASSNAMES.TASK_EDIT_END;
this.baseFrame.appendChild(this.endEdit);
this.dependencySuccessorBaseElement = document.createElement("DIV");
this.dependencySuccessorBaseElement.className = TaskEditController.CLASSNAMES.TASK_EDIT_BOX_SUCCESSOR;
this.dependencySuccessorFrame = document.createElement("DIV");
this.dependencySuccessorFrame.className = TaskEditController.CLASSNAMES.TASK_EDIT_FRAME_SUCCESSOR;
this.dependencySuccessorBaseElement.appendChild(this.dependencySuccessorFrame);
this.dependencySuccessorStart = document.createElement("DIV");
this.dependencySuccessorStart.classList.add(TaskEditController.CLASSNAMES.TASK_EDIT_SUCCESSOR_DEPENDENCY_RIGTH);
if (browser_1.Browser.TouchUI)
this.dependencySuccessorStart.classList.add(TaskEditController.CLASSNAMES.TASK_EDIT_TOUCH);
this.dependencySuccessorFrame.appendChild(this.dependencySuccessorStart);
this.dependencySuccessorFinish = document.createElement("DIV");
this.dependencySuccessorFinish.classList.add(TaskEditController.CLASSNAMES.TASK_EDIT_SUCCESSOR_DEPENDENCY_LEFT);
if (browser_1.Browser.TouchUI)
this.dependencySuccessorFinish.classList.add(TaskEditController.CLASSNAMES.TASK_EDIT_TOUCH);
this.dependencySuccessorFrame.appendChild(this.dependencySuccessorFinish);
this._tooltip = new TaskEditTooltip_1.TaskEditTooltip(this.baseElement, this.tooltipSettings, this.renderHelper.elementTextHelperCultureInfo);
this.attachEvents();
};
TaskEditController.prototype.attachEvents = function () {
this.onMouseLeaveHandler = function () {
if (!this.isEditingInProgress)
this.hide();
}.bind(this);
this.baseElement.addEventListener("mouseleave", this.onMouseLeaveHandler);
};
TaskEditController.prototype.drawline = function (start, end) {
if (start.x > end.x) {
var temp = end;
end = start;
start = temp;
}
var angle = Math.atan((start.y - end.y) / (end.x - start.x));
angle = (angle * 180 / Math.PI);
angle = -angle;
var length = Math.sqrt((start.x - end.x) * (start.x - end.x) + (start.y - end.y) * (start.y - end.y));
this.dependencyLine.style.left = start.x + "px";
this.dependencyLine.style.top = start.y + "px";
this.dependencyLine.style.width = length + "px";
this.dependencyLine.style.transform = "rotate(" + angle + "deg)";
};
TaskEditController.prototype.canUpdateTask = function () {
return !this.viewModel.isTaskToCalculateByChildren(this.task.internalId);
};
TaskEditController.prototype.detachEvents = function () {
var _a;
(_a = this.baseElement) === null || _a === void 0 ? void 0 : _a.removeEventListener("mouseleave", this.onMouseLeaveHandler);
};
TaskEditController.CLASSNAMES = {
TASK_EDIT_BOX: "dx-gantt-task-edit-wrapper",
TASK_EDIT_BOX_CUSTOM: "dx-gantt-task-edit-wrapper-custom",
TASK_EDIT_FRAME: "dx-gantt-task-edit-frame",
TASK_EDIT_PROGRESS: "dx-gantt-task-edit-progress",
TASK_EDIT_DEPENDENCY_RIGTH: "dx-gantt-task-edit-dependency-r",
TASK_EDIT_DEPENDENCY_LEFT: "dx-gantt-task-edit-dependency-l",
TASK_EDIT_START: "dx-gantt-task-edit-start",
TASK_EDIT_END: "dx-gantt-task-edit-end",
TASK_EDIT_DEPENDENCY_LINE: "dx-gantt-task-edit-dependency-line",
TASK_EDIT_BOX_SUCCESSOR: "dx-gantt-task-edit-wrapper-successor",
TASK_EDIT_FRAME_SUCCESSOR: "dx-gantt-task-edit-frame-successor",
TASK_EDIT_SUCCESSOR_DEPENDENCY_RIGTH: "dx-gantt-task-edit-successor-dependency-r",
TASK_EDIT_SUCCESSOR_DEPENDENCY_LEFT: "dx-gantt-task-edit-successor-dependency-l",
TASK_EDIT_TOUCH: "dx-gantt-edit-touch"
};
return TaskEditController;
}());
exports.TaskEditController = TaskEditController;
/***/ }),
/* 71 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TooltipSettings = void 0;
var common_1 = __webpack_require__(1);
var TooltipSettings = (function () {
function TooltipSettings() {
}
TooltipSettings.parse = function (settings) {
var result = new TooltipSettings();
if (settings) {
if ((0, common_1.isDefined)(settings.getHeaderHeight))
result.getHeaderHeight = settings.getHeaderHeight;
if ((0, common_1.isDefined)(settings.getTaskTooltipContentTemplate))
result.getTaskTooltipContentTemplate = settings.getTaskTooltipContentTemplate;
if ((0, common_1.isDefined)(settings.getTaskProgressTooltipContentTemplate))
result.getTaskProgressTooltipContentTemplate = settings.getTaskProgressTooltipContentTemplate;
if ((0, common_1.isDefined)(settings.getTaskTimeTooltipContentTemplate))
result.getTaskTimeTooltipContentTemplate = settings.getTaskTimeTooltipContentTemplate;
if ((0, common_1.isDefined)(settings.destroyTemplate))
result.destroyTemplate = settings.destroyTemplate;
if ((0, common_1.isDefined)(settings.formatDate))
result.formatDate = settings.formatDate;
}
return result;
};
return TooltipSettings;
}());
exports.TooltipSettings = TooltipSettings;
/***/ }),
/* 72 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GridElementInfo = void 0;
var point_1 = __webpack_require__(4);
var size_1 = __webpack_require__(11);
var margins_1 = __webpack_require__(148);
var GridElementInfo = (function () {
function GridElementInfo(className, position, size) {
this.id = GridElementInfo.id++;
this.position = new point_1.Point(undefined, undefined);
this.size = new size_1.Size(0, 0);
this.margins = new margins_1.Margins(undefined, undefined, undefined, undefined);
this.attr = {};
this.style = {};
this.additionalInfo = {};
if (className)
this.className = className;
if (position)
this.setPosition(position);
if (size)
this.setSize(size);
}
GridElementInfo.prototype.setSize = function (size) {
this.size.width = size.width;
this.size.height = size.height;
};
GridElementInfo.prototype.setPosition = function (position) {
this.position.x = position.x;
this.position.y = position.y;
};
GridElementInfo.prototype.assignToElement = function (element) {
this.assignPosition(element);
this.assignSize(element);
this.assignMargins(element);
if (this.className)
element.className = this.className;
};
GridElementInfo.prototype.assignPosition = function (element) {
if (this.position.x != null)
element.style.left = this.position.x + "px";
if (this.position.y != null)
element.style.top = this.position.y + "px";
};
GridElementInfo.prototype.assignSize = function (element) {
if (this.size.width)
element.style.width = this.size.width + "px";
if (this.size.height)
element.style.height = this.size.height + "px";
};
GridElementInfo.prototype.assignMargins = function (element) {
if (this.margins.left)
element.style.marginLeft = this.margins.left + "px";
if (this.margins.top)
element.style.marginTop = this.margins.top + "px";
if (this.margins.right)
element.style.marginRight = this.margins.right + "px";
if (this.margins.bottom)
element.style.marginBottom = this.margins.bottom + "px";
};
GridElementInfo.prototype.setAttribute = function (name, value) {
this.attr[name] = value;
};
GridElementInfo.id = 0;
return GridElementInfo;
}());
exports.GridElementInfo = GridElementInfo;
/***/ }),
/* 73 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StripLine = void 0;
var common_1 = __webpack_require__(1);
var StripLine = (function () {
function StripLine(start, end, title, cssClass, isCurrent) {
this.isCurrent = false;
this.start = start;
this.end = end;
this.title = title;
this.cssClass = cssClass;
this.isCurrent = isCurrent;
}
StripLine.parse = function (settings) {
var result = new StripLine();
if (settings) {
if ((0, common_1.isDefined)(settings.start))
result.start = settings.start;
if ((0, common_1.isDefined)(settings.end))
result.end = settings.end;
if ((0, common_1.isDefined)(settings.title))
result.title = settings.title;
if ((0, common_1.isDefined)(settings.cssClass))
result.cssClass = settings.cssClass;
}
return result;
};
StripLine.prototype.clone = function () {
return new StripLine(this.start, this.end, this.title, this.cssClass, this.isCurrent);
};
StripLine.prototype.equal = function (stripLine) {
var result = true;
result = result && this.start == stripLine.start;
result = result && this.end == stripLine.end;
result = result && this.title == stripLine.title;
result = result && this.cssClass == stripLine.cssClass;
return result;
};
return StripLine;
}());
exports.StripLine = StripLine;
/***/ }),
/* 74 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MouseHandlerDependencyState = exports.dependencyMap = void 0;
var tslib_1 = __webpack_require__(0);
var point_1 = __webpack_require__(4);
var dom_1 = __webpack_require__(3);
var evt_1 = __webpack_require__(10);
var MouseHandlerStateBase_1 = __webpack_require__(48);
var Enums_1 = __webpack_require__(2);
var Enums_2 = __webpack_require__(24);
exports.dependencyMap = [];
exports.dependencyMap[Enums_1.MouseEventSource.TaskEdit_DependencyStart] = [];
exports.dependencyMap[Enums_1.MouseEventSource.TaskEdit_DependencyFinish] = [];
exports.dependencyMap[Enums_1.MouseEventSource.TaskEdit_DependencyStart][Enums_1.MouseEventSource.Successor_DependencyStart] = Enums_2.DependencyType.SS;
exports.dependencyMap[Enums_1.MouseEventSource.TaskEdit_DependencyStart][Enums_1.MouseEventSource.Successor_DependencyFinish] = Enums_2.DependencyType.SF;
exports.dependencyMap[Enums_1.MouseEventSource.TaskEdit_DependencyFinish][Enums_1.MouseEventSource.Successor_DependencyStart] = Enums_2.DependencyType.FS;
exports.dependencyMap[Enums_1.MouseEventSource.TaskEdit_DependencyFinish][Enums_1.MouseEventSource.Successor_DependencyFinish] = Enums_2.DependencyType.FF;
var MouseHandlerDependencyState = (function (_super) {
(0, tslib_1.__extends)(MouseHandlerDependencyState, _super);
function MouseHandlerDependencyState() {
return _super !== null && _super.apply(this, arguments) || this;
}
MouseHandlerDependencyState.prototype.onMouseDown = function (evt) {
var sourceElement = evt_1.EvtUtils.getEventSource(evt);
this.source = this.handler.getEventSource(sourceElement);
var pos = this.getRelativePos(new point_1.Point(dom_1.DomUtils.getAbsolutePositionX(sourceElement) + sourceElement.clientWidth / 2, dom_1.DomUtils.getAbsolutePositionY(sourceElement) + sourceElement.clientHeight / 2));
this.taskEditController.startDependency(pos);
};
MouseHandlerDependencyState.prototype.onMouseUp = function (evt) {
if (evt instanceof PointerEvent) {
var relativePosStart = this.getRelativePos(new point_1.Point(dom_1.DomUtils.getAbsolutePositionX(this.taskEditController.dependencySuccessorStart) + this.taskEditController.dependencySuccessorStart.clientWidth / 2, dom_1.DomUtils.getAbsolutePositionY(this.taskEditController.dependencySuccessorStart) + this.taskEditController.dependencySuccessorStart.clientHeight / 2));
var relativePosEnd = this.getRelativePos(new point_1.Point(dom_1.DomUtils.getAbsolutePositionX(this.taskEditController.dependencySuccessorFinish) + this.taskEditController.dependencySuccessorFinish.clientWidth / 2, dom_1.DomUtils.getAbsolutePositionY(this.taskEditController.dependencySuccessorFinish) + this.taskEditController.dependencySuccessorFinish.clientHeight / 2));
var relativeTouchPos = this.getRelativePos(new point_1.Point(evt_1.EvtUtils.getEventX(evt), evt_1.EvtUtils.getEventY(evt)));
var target = this.isTouchNearby(relativeTouchPos, relativePosStart) ? Enums_1.MouseEventSource.Successor_DependencyStart :
this.isTouchNearby(relativeTouchPos, relativePosEnd) ? Enums_1.MouseEventSource.Successor_DependencyFinish : null;
var type = target === Enums_1.MouseEventSource.Successor_DependencyStart || target == Enums_1.MouseEventSource.Successor_DependencyFinish ?
exports.dependencyMap[this.source][target] : null;
this.taskEditController.endDependency(type);
}
else {
var target = this.handler.getEventSource(evt_1.EvtUtils.getEventSource(evt));
var type = target === Enums_1.MouseEventSource.Successor_DependencyStart || target == Enums_1.MouseEventSource.Successor_DependencyFinish ?
exports.dependencyMap[this.source][target] : null;
this.taskEditController.endDependency(type);
}
this.handler.switchToDefaultState();
};
MouseHandlerDependencyState.prototype.onMouseMove = function (evt) {
evt.preventDefault();
var relativePos = this.getRelativePos(new point_1.Point(evt_1.EvtUtils.getEventX(evt), evt_1.EvtUtils.getEventY(evt)));
var hoverTaskIndex = Math.floor(relativePos.y / this.tickSize.height);
this.taskEditController.processDependency(relativePos);
if (this.viewModel.tasks.items[hoverTaskIndex])
this.taskEditController.showDependencySuccessor(hoverTaskIndex);
};
MouseHandlerDependencyState.prototype.isTouchNearby = function (touchPos, elementPos) {
if (Math.abs(elementPos.x - touchPos.x) <= 10 && Math.abs(elementPos.y - touchPos.y) <= 10)
return true;
return false;
};
return MouseHandlerDependencyState;
}(MouseHandlerStateBase_1.MouseHandlerStateBase));
exports.MouseHandlerDependencyState = MouseHandlerDependencyState;
/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TouchHandlerStateBase = void 0;
var tslib_1 = __webpack_require__(0);
var HandlerStateBase_1 = __webpack_require__(39);
var TouchHandlerStateBase = (function (_super) {
(0, tslib_1.__extends)(TouchHandlerStateBase, _super);
function TouchHandlerStateBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
TouchHandlerStateBase.prototype.onTouchStart = function (_evt) { };
TouchHandlerStateBase.prototype.onDoubleTap = function (_evt) { };
TouchHandlerStateBase.prototype.onTouchEnd = function (_evt) { };
TouchHandlerStateBase.prototype.onTouchMove = function (_evt) { };
return TouchHandlerStateBase;
}(HandlerStateBase_1.HandlerStateBase));
exports.TouchHandlerStateBase = TouchHandlerStateBase;
/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PdfDependencyLineInfo = void 0;
var point_1 = __webpack_require__(4);
var Color_1 = __webpack_require__(17);
var PdfDependencyLineInfo = (function () {
function PdfDependencyLineInfo() {
}
PdfDependencyLineInfo.prototype.assign = function (source) {
var _a;
this._copyPoints(source.points);
this.arrowInfo = source.arrowInfo;
(_a = this.fillColor) !== null && _a !== void 0 ? _a : (this.fillColor = new Color_1.Color());
this.fillColor.assign(source.fillColor);
};
PdfDependencyLineInfo.prototype._copyPoints = function (source) {
var _this = this;
this.points = new Array();
source === null || source === void 0 ? void 0 : source.forEach(function (p) { return _this.points.push(new point_1.Point(p.x, p.y)); });
};
return PdfDependencyLineInfo;
}());
exports.PdfDependencyLineInfo = PdfDependencyLineInfo;
/***/ }),
/* 77 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PdfTaskResourcesInfo = void 0;
var common_1 = __webpack_require__(1);
var StyleDef_1 = __webpack_require__(28);
var PdfTaskResourcesInfo = (function () {
function PdfTaskResourcesInfo(text, style, x, y) {
if (text)
this.text = text;
if (style)
this.style = new StyleDef_1.StyleDef(style);
if ((0, common_1.isDefined)(x))
this.x = x;
if ((0, common_1.isDefined)(y))
this.y = y;
}
PdfTaskResourcesInfo.prototype.assign = function (source) {
this.text = source.text;
this.style = new StyleDef_1.StyleDef(source.style);
this.x = source.x;
this.y = source.y;
};
return PdfTaskResourcesInfo;
}());
exports.PdfTaskResourcesInfo = PdfTaskResourcesInfo;
/***/ }),
/* 78 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Width = void 0;
var PredefinedStyles_1 = __webpack_require__(51);
var dom_1 = __webpack_require__(3);
var Width = (function () {
function Width(width) {
this.assign(width);
}
Width.prototype.assign = function (source) {
if (source instanceof Width)
this._widthInternal = source._widthInternal;
else {
var num = typeof source === "number" ? source : parseInt(source);
if (!isNaN(num))
this._widthInternal = num;
else
this.assignFromString(source);
}
};
Width.prototype.assignFromString = function (source) {
if (source) {
var px = dom_1.DomUtils.pxToInt(source);
if (px)
this._widthInternal = px;
else
this._widthInternal = PredefinedStyles_1.PredefinedStyles.getPredefinedStringOrUndefined(source, PredefinedStyles_1.PredefinedStyles.width);
}
};
Width.prototype.hasValue = function () {
return !!this._widthInternal;
};
Width.prototype.getValue = function () {
return this._widthInternal;
};
return Width;
}());
exports.Width = Width;
/***/ }),
/* 79 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PdfTimeMarkerInfo = void 0;
var point_1 = __webpack_require__(4);
var size_1 = __webpack_require__(11);
var common_1 = __webpack_require__(1);
var Color_1 = __webpack_require__(17);
var PdfTimeMarkerInfo = (function () {
function PdfTimeMarkerInfo(start, size, color, lineColor, isStripLine) {
this.lineColor = new Color_1.Color();
this.color = new Color_1.Color();
if (start)
this.start = new point_1.Point(start.x, start.y);
if (size)
this.size = new size_1.Size(size.width, size.height);
if (color)
this.color.assign(color);
if (lineColor)
this.lineColor.assign(lineColor);
if ((0, common_1.isDefined)(isStripLine))
this.isStripLine = isStripLine;
}
PdfTimeMarkerInfo.prototype.assign = function (source) {
var _a, _b, _c, _d;
if (source) {
this.start = new point_1.Point((_a = source.start) === null || _a === void 0 ? void 0 : _a.x, (_b = source.start) === null || _b === void 0 ? void 0 : _b.y);
this.size = new size_1.Size((_c = source.size) === null || _c === void 0 ? void 0 : _c.width, (_d = source.size) === null || _d === void 0 ? void 0 : _d.height);
this.isStripLine = source.isStripLine;
this.color.assign(source.color);
this.lineColor.assign(source.lineColor);
}
};
return PdfTimeMarkerInfo;
}());
exports.PdfTimeMarkerInfo = PdfTimeMarkerInfo;
/***/ }),
/* 80 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HistoryItemState = void 0;
var HistoryItemState = (function () {
function HistoryItemState(id, value) {
this.id = id;
this.value = value;
}
return HistoryItemState;
}());
exports.HistoryItemState = HistoryItemState;
/***/ }),
/* 81 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EllipsisHelper = void 0;
var EllipsisHelper = (function () {
function EllipsisHelper() {
}
EllipsisHelper.limitPdfTextWithEllipsis = function (text, pdfDoc, size) {
if (!(pdfDoc === null || pdfDoc === void 0 ? void 0 : pdfDoc.getTextWidth) || !size)
return text;
var pdfTextWidth = pdfDoc.getTextWidth(text.toString());
if (pdfTextWidth > size) {
var outputText = EllipsisHelper.ellipsis;
var pos = 0;
while (pdfDoc.getTextWidth(outputText) < size) {
var char = text[pos];
outputText = outputText.substr(0, pos) + char + outputText.substr(pos);
pos++;
}
return outputText;
}
return text;
};
EllipsisHelper.ellipsis = "...";
return EllipsisHelper;
}());
exports.EllipsisHelper = EllipsisHelper;
/***/ }),
/* 82 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StripLineSettings = void 0;
var common_1 = __webpack_require__(1);
var StripLine_1 = __webpack_require__(73);
var StripLineSettings = (function () {
function StripLineSettings() {
this.showCurrentTime = false;
this.currentTimeUpdateInterval = 60000;
this.stripLines = [];
}
StripLineSettings.parse = function (settings) {
var result = new StripLineSettings();
if (settings) {
if ((0, common_1.isDefined)(settings.showCurrentTime))
result.showCurrentTime = settings.showCurrentTime;
if ((0, common_1.isDefined)(settings.currentTimeUpdateInterval))
result.currentTimeUpdateInterval = settings.currentTimeUpdateInterval;
if ((0, common_1.isDefined)(settings.currentTimeTitle))
result.currentTimeTitle = settings.currentTimeTitle;
if ((0, common_1.isDefined)(settings.currentTimeCssClass))
result.currentTimeCssClass = settings.currentTimeCssClass;
if ((0, common_1.isDefined)(settings.stripLines))
for (var i = 0; i < settings.stripLines.length; i++)
result.stripLines.push(StripLine_1.StripLine.parse(settings.stripLines[i]));
}
return result;
};
StripLineSettings.prototype.equal = function (settings) {
var result = true;
result = result && this.showCurrentTime == settings.showCurrentTime;
result = result && this.currentTimeUpdateInterval == settings.currentTimeUpdateInterval;
result = result && this.currentTimeTitle == settings.currentTimeTitle;
result = result && this.currentTimeCssClass == settings.currentTimeCssClass;
result = result && this.stripLines.length === settings.stripLines.length;
if (result)
for (var i = 0; i < settings.stripLines.length; i++)
result = result && this.stripLines[i].equal(settings.stripLines[i]);
return result;
};
return StripLineSettings;
}());
exports.StripLineSettings = StripLineSettings;
/***/ }),
/* 83 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Dependency = void 0;
var tslib_1 = __webpack_require__(0);
var common_1 = __webpack_require__(1);
var DataObject_1 = __webpack_require__(20);
var Enums_1 = __webpack_require__(24);
var Dependency = (function (_super) {
(0, tslib_1.__extends)(Dependency, _super);
function Dependency() {
var _this = _super.call(this) || this;
_this.predecessorId = "";
_this.successorId = "";
_this.type = null;
return _this;
}
Object.defineProperty(Dependency.prototype, "isStartDependency", {
get: function () {
return this.type === Enums_1.DependencyType.SS || this.type === Enums_1.DependencyType.SF;
},
enumerable: false,
configurable: true
});
Dependency.prototype.assignFromObject = function (sourceObj) {
if ((0, common_1.isDefined)(sourceObj)) {
_super.prototype.assignFromObject.call(this, sourceObj);
this.internalId = String(sourceObj.id);
this.predecessorId = String(sourceObj.predecessorId);
this.successorId = String(sourceObj.successorId);
this.type = this.parseType(sourceObj.type);
}
};
Dependency.prototype.parseType = function (type) {
if ((0, common_1.isDefined)(type)) {
var text = type.toString().toUpperCase();
switch (text) {
case "SS":
case "1":
return Enums_1.DependencyType.SS;
case "FF":
case "2":
return Enums_1.DependencyType.FF;
case "SF":
case "3":
return Enums_1.DependencyType.SF;
default: return Enums_1.DependencyType.FS;
}
}
else
return Enums_1.DependencyType.FS;
};
return Dependency;
}(DataObject_1.DataObject));
exports.Dependency = Dependency;
/***/ }),
/* 84 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourceAssignment = void 0;
var tslib_1 = __webpack_require__(0);
var common_1 = __webpack_require__(1);
var DataObject_1 = __webpack_require__(20);
var ResourceAssignment = (function (_super) {
(0, tslib_1.__extends)(ResourceAssignment, _super);
function ResourceAssignment() {
var _this = _super.call(this) || this;
_this.taskId = "";
_this.resourceId = "";
return _this;
}
ResourceAssignment.prototype.assignFromObject = function (sourceObj) {
if ((0, common_1.isDefined)(sourceObj)) {
_super.prototype.assignFromObject.call(this, sourceObj);
this.taskId = String(sourceObj.taskId);
this.resourceId = String(sourceObj.resourceId);
}
};
return ResourceAssignment;
}(DataObject_1.DataObject));
exports.ResourceAssignment = ResourceAssignment;
/***/ }),
/* 85 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecurrenceFactory = void 0;
var common_1 = __webpack_require__(1);
var Daily_1 = __webpack_require__(86);
var Weekly_1 = __webpack_require__(236);
var Monthly_1 = __webpack_require__(237);
var Yearly_1 = __webpack_require__(239);
var RecurrenceFactory = (function () {
function RecurrenceFactory() {
}
RecurrenceFactory.createRecurrenceByType = function (type) {
if (!type)
return null;
var correctedType = type.toLowerCase();
switch (correctedType) {
case "daily":
return new Daily_1.Daily();
case "weekly":
return new Weekly_1.Weekly();
case "monthly":
return new Monthly_1.Monthly();
case "yearly":
return new Yearly_1.Yearly();
}
return null;
};
RecurrenceFactory.createRecurrenceFromObject = function (sourceObj) {
if (!sourceObj)
return null;
var recurrence = this.createRecurrenceByType(sourceObj.type);
if (recurrence)
recurrence.assignFromObject(sourceObj);
return recurrence;
};
RecurrenceFactory.getEnumValue = function (type, value) {
if (!(0, common_1.isDefined)(type[value]))
return null;
var num = parseInt(value);
if (!isNaN(num))
return num;
return type[value];
};
return RecurrenceFactory;
}());
exports.RecurrenceFactory = RecurrenceFactory;
/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Daily = void 0;
var tslib_1 = __webpack_require__(0);
var RecurrenceBase_1 = __webpack_require__(41);
var DateTimeUtils_1 = __webpack_require__(7);
var Daily = (function (_super) {
(0, tslib_1.__extends)(Daily, _super);
function Daily() {
return _super !== null && _super.apply(this, arguments) || this;
}
Daily.prototype.checkDate = function (date) { return true; };
Daily.prototype.checkInterval = function (date) {
return DateTimeUtils_1.DateTimeUtils.getDaysBetween(this.start, date) % this.interval == 0;
};
Daily.prototype.calculatePointByInterval = function (date) {
var daysToAdd = this.interval;
if (!this.isRecurrencePoint(date))
daysToAdd -= DateTimeUtils_1.DateTimeUtils.getDaysBetween(this.start, date) % this.interval;
return DateTimeUtils_1.DateTimeUtils.addDays(date, daysToAdd);
};
Daily.prototype.calculateNearestPoint = function (date) {
return DateTimeUtils_1.DateTimeUtils.addDays(date, 1);
};
return Daily;
}(RecurrenceBase_1.RecurrenceBase));
exports.Daily = Daily;
/***/ }),
/* 87 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GanttView = exports.default = void 0;
__webpack_require__(88);
var GanttView_1 = __webpack_require__(55);
Object.defineProperty(exports, "default", { enumerable: true, get: function () { return GanttView_1.GanttView; } });
Object.defineProperty(exports, "GanttView", { enumerable: true, get: function () { return GanttView_1.GanttView; } });
/***/ }),
/* 88 */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/* 89 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BarManager = void 0;
var BarManager = (function () {
function BarManager(commandManager, bars) {
this.commandManager = commandManager;
this.bars = bars;
}
BarManager.prototype.updateContextMenu = function () {
for (var i = 0, bar = void 0; bar = this.bars[i]; i++)
if (bar.isContextMenu()) {
bar.updateItemsList();
var commandKeys = bar.getCommandKeys();
for (var j = 0; j < commandKeys.length; j++)
this.updateBarItem(bar, commandKeys[j]);
}
};
BarManager.prototype.updateItemsState = function (queryCommands) {
var anyQuerySended = !!queryCommands.length;
var _loop_1 = function (i, bar) {
if (bar.isVisible()) {
var commandKeys_1 = bar.getCommandKeys();
var _loop_2 = function (j) {
if (anyQuerySended && !queryCommands.filter(function (q) { return q == commandKeys_1[j]; }).length)
return "continue";
this_1.updateBarItem(bar, commandKeys_1[j]);
};
for (var j = 0; j < commandKeys_1.length; j++) {
_loop_2(j);
}
bar.completeUpdate();
}
};
var this_1 = this;
for (var i = 0, bar = void 0; bar = this.bars[i]; i++) {
_loop_1(i, bar);
}
};
BarManager.prototype.updateBarItem = function (bar, commandKey) {
var command = this.commandManager.getCommand(commandKey);
if (command) {
var commandState = command.getState();
bar.setItemVisible(commandKey, commandState.visible);
if (commandState.visible) {
bar.setItemEnabled(commandKey, commandState.enabled);
bar.setItemValue(commandKey, commandState.value);
}
}
};
return BarManager;
}());
exports.BarManager = BarManager;
/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommandManager = void 0;
var ConfirmationDialog_1 = __webpack_require__(91);
var ConstraintViolationDialog_1 = __webpack_require__(92);
var ResourcesDialog_1 = __webpack_require__(93);
var TaskEditDialog_1 = __webpack_require__(100);
var ClientCommand_1 = __webpack_require__(102);
var CollapseAllCommand_1 = __webpack_require__(103);
var ExpandAllCommand_1 = __webpack_require__(104);
var CreateDependencyCommand_1 = __webpack_require__(105);
var RemoveDependencyCommand_1 = __webpack_require__(108);
var ToggleDependencies_1 = __webpack_require__(110);
var FullScreenCommand_1 = __webpack_require__(111);
var RedoCommand_1 = __webpack_require__(112);
var UndoCommand_1 = __webpack_require__(113);
var AssignResourceCommand_1 = __webpack_require__(114);
var CreateResourceCommand_1 = __webpack_require__(115);
var DeassignResourceCommand_1 = __webpack_require__(117);
var ResourceColorCommand_1 = __webpack_require__(118);
var RemoveResourceCommand_1 = __webpack_require__(122);
var ToggleResource_1 = __webpack_require__(125);
var CreateSubTaskCommand_1 = __webpack_require__(126);
var CreateTaskCommand_1 = __webpack_require__(127);
var RemoveTaskCommand_1 = __webpack_require__(128);
var TaskAddContextItemCommand_1 = __webpack_require__(131);
var TaskColorCommand_1 = __webpack_require__(132);
var TaskDescriptionCommand_1 = __webpack_require__(133);
var TaskEndCommand_1 = __webpack_require__(135);
var TaskMoveCommand_1 = __webpack_require__(137);
var TaskProgressCommand_1 = __webpack_require__(138);
var TaskStartCommand_1 = __webpack_require__(139);
var TaskTitleCommand_1 = __webpack_require__(140);
var UpdateTaskCommand_1 = __webpack_require__(141);
var ZoomInCommand_1 = __webpack_require__(142);
var ZoomOutCommand_1 = __webpack_require__(143);
var CommandManager = (function () {
function CommandManager(control) {
this.control = control;
this.commands = {};
this.createCommand(ClientCommand_1.GanttClientCommand.CreateTask, this.createTaskCommand);
this.createCommand(ClientCommand_1.GanttClientCommand.CreateSubTask, this.createSubTaskCommand);
this.createCommand(ClientCommand_1.GanttClientCommand.RemoveTask, this.removeTaskCommand);
this.createCommand(ClientCommand_1.GanttClientCommand.RemoveDependency, this.removeDependencyCommand);
this.createCommand(ClientCommand_1.GanttClientCommand.TaskInformation, this.showTaskEditDialog);
this.createCommand(ClientCommand_1.GanttClientCommand.ResourceManager, this.showResourcesDialog);
this.createCommand(ClientCommand_1.GanttClientCommand.TaskAddContextItem, new TaskAddContextItemCommand_1.TaskAddContextItemCommand(this.control));
this.createCommand(ClientCommand_1.GanttClientCommand.Undo, new UndoCommand_1.UndoCommand(this.control));
this.createCommand(ClientCommand_1.GanttClientCommand.Redo, new RedoCommand_1.RedoCommand(this.control));
this.createCommand(ClientCommand_1.GanttClientCommand.ZoomIn, new ZoomInCommand_1.ZoomInCommand(this.control));
this.createCommand(ClientCommand_1.GanttClientCommand.ZoomOut, new ZoomOutCommand_1.ZoomOutCommand(this.control));
this.createCommand(ClientCommand_1.GanttClientCommand.FullScreen, new FullScreenCommand_1.ToggleFullScreenCommand(this.control));
this.createCommand(ClientCommand_1.GanttClientCommand.CollapseAll, new CollapseAllCommand_1.CollapseAllCommand(this.control));
this.createCommand(ClientCommand_1.GanttClientCommand.ExpandAll, new ExpandAllCommand_1.ExpandAllCommand(this.control));
this.createCommand(ClientCommand_1.GanttClientCommand.ToggleResources, this.toggleResources);
this.createCommand(ClientCommand_1.GanttClientCommand.ToggleDependencies, this.toggleDependencies);
}
Object.defineProperty(CommandManager.prototype, "createTaskCommand", {
get: function () { return new CreateTaskCommand_1.CreateTaskCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "createSubTaskCommand", {
get: function () { return new CreateSubTaskCommand_1.CreateSubTaskCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "removeTaskCommand", {
get: function () { return new RemoveTaskCommand_1.RemoveTaskCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "changeTaskTitleCommand", {
get: function () { return new TaskTitleCommand_1.TaskTitleCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "changeTaskDescriptionCommand", {
get: function () { return new TaskDescriptionCommand_1.TaskDescriptionCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "changeTaskProgressCommand", {
get: function () { return new TaskProgressCommand_1.TaskProgressCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "changeTaskColorCommand", {
get: function () { return new TaskColorCommand_1.TaskColorCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "changeTaskStartCommand", {
get: function () { return new TaskStartCommand_1.TaskStartCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "taskMoveCommand", {
get: function () { return new TaskMoveCommand_1.TaskMoveCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "changeTaskEndCommand", {
get: function () { return new TaskEndCommand_1.TaskEndCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "updateTaskCommand", {
get: function () { return new UpdateTaskCommand_1.UpdateTaskCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "createDependencyCommand", {
get: function () { return new CreateDependencyCommand_1.CreateDependencyCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "removeDependencyCommand", {
get: function () { return new RemoveDependencyCommand_1.RemoveDependencyCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "createResourceCommand", {
get: function () { return new CreateResourceCommand_1.CreateResourceCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "removeResourceCommand", {
get: function () { return new RemoveResourceCommand_1.RemoveResourceCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "assignResourceCommand", {
get: function () { return new AssignResourceCommand_1.AssignResourceCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "deassignResourceCommand", {
get: function () { return new DeassignResourceCommand_1.DeassignResourceCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "changeResourceColorCommand", {
get: function () { return new ResourceColorCommand_1.ResourceColorCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "showTaskEditDialog", {
get: function () { return new TaskEditDialog_1.TaskEditDialogCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "showConstraintViolationDialog", {
get: function () { return new ConstraintViolationDialog_1.ConstraintViolationDialogCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "showConfirmationDialog", {
get: function () { return new ConfirmationDialog_1.ConfirmationDialog(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "showResourcesDialog", {
get: function () { return new ResourcesDialog_1.ResourcesDialogCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "toggleResources", {
get: function () { return new ToggleResource_1.ToggleResourceCommand(this.control); },
enumerable: false,
configurable: true
});
Object.defineProperty(CommandManager.prototype, "toggleDependencies", {
get: function () { return new ToggleDependencies_1.ToggleDependenciesCommand(this.control); },
enumerable: false,
configurable: true
});
CommandManager.prototype.getCommand = function (key) {
return this.commands[key];
};
CommandManager.prototype.createCommand = function (commandId, command) {
this.commands[commandId] = command;
};
return CommandManager;
}());
exports.CommandManager = CommandManager;
/***/ }),
/* 91 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConfirmationDialog = void 0;
var tslib_1 = __webpack_require__(0);
var DialogBase_1 = __webpack_require__(30);
var ConfirmationDialog = (function (_super) {
(0, tslib_1.__extends)(ConfirmationDialog, _super);
function ConfirmationDialog() {
return _super !== null && _super.apply(this, arguments) || this;
}
ConfirmationDialog.prototype.applyParameters = function (_newParameters, oldParameters) {
this.history.beginTransaction();
oldParameters.callback();
this.history.endTransaction();
this.control.barManager.updateItemsState([]);
return true;
};
ConfirmationDialog.prototype.createParameters = function (options) {
return options;
};
ConfirmationDialog.prototype.getDialogName = function () {
return "Confirmation";
};
return ConfirmationDialog;
}(DialogBase_1.DialogBase));
exports.ConfirmationDialog = ConfirmationDialog;
/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConstraintViolationDialogCommand = void 0;
var tslib_1 = __webpack_require__(0);
var RemoveDependencyHistoryItem_1 = __webpack_require__(31);
var DialogBase_1 = __webpack_require__(30);
var DialogEnums_1 = __webpack_require__(32);
var ConstraintViolationDialogCommand = (function (_super) {
(0, tslib_1.__extends)(ConstraintViolationDialogCommand, _super);
function ConstraintViolationDialogCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
ConstraintViolationDialogCommand.prototype.applyParameters = function (newParameters, oldParameters) {
if (newParameters.option === DialogEnums_1.ConstraintViolationOption.DoNothing)
return false;
if (newParameters.option === DialogEnums_1.ConstraintViolationOption.RemoveDependency) {
this.history.beginTransaction();
this.history.addAndRedo(new RemoveDependencyHistoryItem_1.RemoveDependencyHistoryItem(this.modelManipulator, oldParameters.validationError.dependencyId));
oldParameters.callback();
this.history.endTransaction();
this.control.barManager.updateItemsState([]);
}
if (newParameters.option === DialogEnums_1.ConstraintViolationOption.KeepDependency) {
oldParameters.callback();
this.control.barManager.updateItemsState([]);
}
return true;
};
ConstraintViolationDialogCommand.prototype.createParameters = function (options) {
var dependency = this.control.viewModel.dependencies.getItemById(options.validationError.dependencyId);
var successorTask = this.control.viewModel.tasks.getItemById(dependency.successorId);
var predecessorTask = this.control.viewModel.tasks.getItemById(dependency.predecessorId);
options.successorTaskTitle = successorTask.title;
options.predecessorTaskTitle = predecessorTask.title;
return options;
};
ConstraintViolationDialogCommand.prototype.getDialogName = function () {
return "ConstraintViolation";
};
return ConstraintViolationDialogCommand;
}(DialogBase_1.DialogBase));
exports.ConstraintViolationDialogCommand = ConstraintViolationDialogCommand;
/***/ }),
/* 93 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourcesDialogCommand = void 0;
var tslib_1 = __webpack_require__(0);
var ResourceCollection_1 = __webpack_require__(22);
var DialogBase_1 = __webpack_require__(30);
var DialogEnums_1 = __webpack_require__(32);
var ConfirmationDialogParameters_1 = __webpack_require__(43);
var ResourcesDialogParameters_1 = __webpack_require__(99);
var ResourcesDialogCommand = (function (_super) {
(0, tslib_1.__extends)(ResourcesDialogCommand, _super);
function ResourcesDialogCommand() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.resourcesForDelete = [];
return _this;
}
ResourcesDialogCommand.prototype.onBeforeDialogShow = function (params) {
return this.modelManipulator.dispatcher.raiseResourceManagerDialogShowing(params, function (args) {
params.resources = args.values.resources;
});
};
ResourcesDialogCommand.prototype.applyParameters = function (newParameters, oldParameters) {
this.history.beginTransaction();
for (var i = 0; i < newParameters.resources.length; i++) {
var resource = oldParameters.resources.getItemById(newParameters.resources.getItem(i).internalId);
if (!resource)
this.control.commandManager.createResourceCommand.execute(newParameters.resources.getItem(i).text);
}
for (var i = 0; i < oldParameters.resources.length; i++) {
var resource = newParameters.resources.getItemById(oldParameters.resources.getItem(i).internalId);
if (!resource)
this.resourcesForDelete.push(oldParameters.resources.getItem(i));
}
this.history.endTransaction();
return false;
};
ResourcesDialogCommand.prototype.createParameters = function (callBack) {
this.callBack = callBack;
var param = new ResourcesDialogParameters_1.ResourcesDialogParameters();
param.resources = new ResourceCollection_1.ResourceCollection();
param.resources.addRange(this.control.viewModel.resources.items);
return param;
};
ResourcesDialogCommand.prototype.afterClosing = function () {
var _this = this;
if (this.resourcesForDelete.length) {
var confirmationDialog = this.control.commandManager.showConfirmationDialog;
var confirmationDialogParameters = new ConfirmationDialogParameters_1.ConfirmationDialogParameters(DialogEnums_1.ConfirmationType.ResourcesDelete, function () {
_this.history.beginTransaction();
for (var i = 0; i < _this.resourcesForDelete.length; i++)
_this.control.commandManager.removeResourceCommand.execute(_this.resourcesForDelete[i].internalId);
_this.history.endTransaction();
});
confirmationDialogParameters.message = this.resourcesForDelete.reduce(function (a, b) { return (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], a, true), [b.text], false); }, []).join(", ");
if (this.callBack)
confirmationDialog.afterClosing = function () { return _this.callBack(); };
confirmationDialog.execute(confirmationDialogParameters);
}
else if (this.callBack)
this.callBack();
};
ResourcesDialogCommand.prototype.getDialogName = function () {
return "Resources";
};
return ResourcesDialogCommand;
}(DialogBase_1.DialogBase));
exports.ResourcesDialogCommand = ResourcesDialogCommand;
/***/ }),
/* 94 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GanttJsonUtils = void 0;
var json_1 = __webpack_require__(95);
var GanttJsonUtils = (function () {
function GanttJsonUtils() {
}
GanttJsonUtils.parseJson = function (json) {
return json_1.JsonUtils.isValid(json) ? JSON.parse(json) : null;
};
return GanttJsonUtils;
}());
exports.GanttJsonUtils = GanttJsonUtils;
/***/ }),
/* 95 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var JsonUtils = (function () {
function JsonUtils() {
}
JsonUtils.isValid = function (json) {
return !(/[^,:{}[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(json.replace(/"(\\.|[^"\\])*"/g, '')));
};
return JsonUtils;
}());
exports.JsonUtils = JsonUtils;
/***/ }),
/* 96 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var min_max_1 = __webpack_require__(97);
var comparers_1 = __webpack_require__(98);
var ListUtils = (function () {
function ListUtils() {
}
ListUtils.remove = function (list, element) {
var index = list.indexOf(element, 0);
if (index >= 0)
list.splice(index, 1);
};
ListUtils.removeBy = function (list, callback) {
var len = list.length;
for (var index = 0; index < len; index++) {
if (callback(list[index], index))
return list.splice(index, 1)[0];
}
return null;
};
ListUtils.shallowCopy = function (list) {
return list.slice();
};
ListUtils.deepCopy = function (list) {
return ListUtils.map(list, function (val) { return val.clone(); });
};
ListUtils.initByValue = function (numElements, initValue) {
var result = [];
for (; numElements > 0; numElements--)
result.push(initValue);
return result;
};
ListUtils.initByCallback = function (numElements, initCallback) {
var result = [];
for (var index = 0; index < numElements; index++)
result.push(initCallback(index));
return result;
};
ListUtils.forEachOnInterval = function (interval, callback) {
var end = interval.end;
for (var index = interval.start; index < end; index++)
callback(index);
};
ListUtils.reverseForEachOnInterval = function (interval, callback) {
var start = interval.start;
for (var index = interval.end - 1; index >= start; index--)
callback(index);
};
ListUtils.reducedMap = function (list, callback, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
var result = [];
for (var index = startIndex; index < endIndex; index++) {
var newItem = callback(list[index], index);
if (newItem !== null)
result.push(newItem);
}
return result;
};
ListUtils.filter = function (list, callback, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
var result = [];
for (var index = startIndex; index < endIndex; index++) {
var item = list[index];
if (callback(item, index))
result.push(item);
}
return result;
};
ListUtils.map = function (list, callback, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
var result = [];
for (var index = startIndex; index < endIndex; index++)
result.push(callback(list[index], index));
return result;
};
ListUtils.indexBy = function (list, callback, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
for (var ind = startIndex; ind < endIndex; ind++) {
if (callback(list[ind], ind))
return ind;
}
return -1;
};
ListUtils.reverseIndexBy = function (list, callback, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = list.length - 1; }
if (endIndex === void 0) { endIndex = 0; }
for (var ind = startIndex; ind >= endIndex; ind--) {
if (callback(list[ind], ind))
return ind;
}
return -1;
};
ListUtils.elementBy = function (list, callback, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
var ind = ListUtils.indexBy(list, callback, startIndex, endIndex);
return ind < 0 ? null : list[ind];
};
ListUtils.reverseElementBy = function (list, callback, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = list.length - 1; }
if (endIndex === void 0) { endIndex = 0; }
var ind = ListUtils.reverseIndexBy(list, callback, startIndex, endIndex);
return ind < 0 ? null : list[ind];
};
ListUtils.last = function (list) {
return list[list.length - 1];
};
ListUtils.setLast = function (list, newVal) {
return list[list.length - 1] = newVal;
};
ListUtils.incLast = function (list) {
return ++list[list.length - 1];
};
ListUtils.decLast = function (list) {
return --list[list.length - 1];
};
ListUtils.equals = function (a, b) {
return a.length === b.length && ListUtils.allOf2(a, b, function (a, b) { return a.equals(b); });
};
ListUtils.equalsByReference = function (a, b) {
var aLen = a.length;
var bLen = a.length;
if (aLen !== bLen)
return false;
for (var i = 0; i < aLen; i++) {
if (a[i] !== b[i])
return false;
}
return true;
};
ListUtils.unique = function (list, cmp, equal, finalizeObj) {
if (equal === void 0) { equal = cmp; }
if (finalizeObj === void 0) { finalizeObj = function () { }; }
var len = list.length;
if (len === 0)
return [];
list = list.sort(cmp);
var prevValue = list[0];
var result = ListUtils.reducedMap(list, function (v) {
if (equal(prevValue, v) !== 0) {
prevValue = v;
return v;
}
finalizeObj(v);
return null;
}, 1, len);
result.unshift(list[0]);
return result;
};
ListUtils.uniqueNumber = function (list) {
list = list.sort(comparers_1.Comparers.number);
var prevValue = Number.NaN;
for (var i = list.length - 1; i >= 0; i--) {
if (prevValue === list[i])
list.splice(i, 1);
else
prevValue = list[i];
}
return list;
};
ListUtils.forEach = function (list, callback, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
for (var index = startIndex; index < endIndex; index++)
callback(list[index], index);
};
ListUtils.forEach2 = function (listA, listB, callback, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = listA.length; }
for (var index = startIndex; index < endIndex; index++)
callback(listA[index], listB[index], index);
};
ListUtils.reverseForEach = function (list, callback, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = list.length - 1; }
if (endIndex === void 0) { endIndex = 0; }
for (var index = startIndex; index >= endIndex; index--)
callback(list[index], index);
};
ListUtils.reverseIndexOf = function (list, element, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = list.length - 1; }
if (endIndex === void 0) { endIndex = 0; }
for (var index = startIndex; index >= endIndex; index--) {
if (list[index] === element)
return index;
}
return -1;
};
ListUtils.accumulate = function (list, initAccValue, callback, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
var acc = initAccValue;
for (var ind = startIndex; ind < endIndex; ind++)
acc = callback(acc, list[ind], ind);
return acc;
};
ListUtils.accumulateNumber = function (list, callback, initAccValue, startIndex, endIndex) {
if (initAccValue === void 0) { initAccValue = 0; }
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
var acc = initAccValue;
for (var ind = startIndex; ind < endIndex; ind++)
acc += callback(list[ind], ind, acc);
return acc;
};
ListUtils.anyOf = function (list, callback, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
for (var index = startIndex; index < endIndex; index++) {
if (callback(list[index], index))
return true;
}
return false;
};
ListUtils.unsafeAnyOf = function (list, callback, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
for (var index = startIndex; index < endIndex; index++) {
var currResult = callback(list[index], index);
if (currResult)
return currResult;
}
return null;
};
ListUtils.reverseAnyOf = function (list, callback, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = list.length - 1; }
if (endIndex === void 0) { endIndex = 0; }
for (var index = startIndex; index >= endIndex; index--) {
if (callback(list[index], index))
return true;
}
return false;
};
ListUtils.unsafeReverseAnyOf = function (list, callback, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = list.length - 1; }
if (endIndex === void 0) { endIndex = 0; }
for (var index = startIndex; index >= endIndex; index--) {
var currResult = callback(list[index], index);
if (currResult)
return currResult;
}
return null;
};
ListUtils.anyOf2 = function (listA, listB, callback, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = listA.length; }
for (var index = startIndex; index < endIndex; index++) {
if (callback(listA[index], listB[index], index))
return true;
}
return false;
};
ListUtils.allOf = function (list, callback, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
for (var index = startIndex; index < endIndex; index++) {
if (!callback(list[index], index))
return false;
}
return true;
};
ListUtils.allOf2 = function (listA, listB, callback, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = listA.length; }
for (var index = startIndex; index < endIndex; index++) {
if (!callback(listA[index], listB[index], index))
return false;
}
return true;
};
ListUtils.allOfOnInterval = function (interval, callback) {
var endIndex = interval.end;
for (var index = interval.start; index < endIndex; index++) {
if (!callback(index))
return false;
}
return true;
};
ListUtils.addListOnTail = function (resultList, addedList) {
for (var i = 0, elem = void 0; elem = addedList[i]; i++)
resultList.push(elem);
return resultList;
};
ListUtils.joinLists = function (converter) {
var lists = [];
for (var _i = 1; _i < arguments.length; _i++) {
lists[_i - 1] = arguments[_i];
}
return ListUtils.accumulate(lists, [], function (accList, list) {
ListUtils.addListOnTail(accList, converter(list));
return accList;
});
};
ListUtils.push = function (list, element) {
list.push(element);
return list;
};
ListUtils.countIf = function (list, callback) {
return ListUtils.accumulateNumber(list, function (elem, ind) { return callback(elem, ind) ? 1 : 0; });
};
ListUtils.clear = function (list) {
list.splice(0);
};
ListUtils.merge = function (list, cmp, shouldMerge, merge, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
list = list.slice(startIndex, endIndex);
if (endIndex - startIndex < 2)
return list;
list = list.sort(cmp);
var prevObj = list[startIndex];
var result = [prevObj];
for (var ind = startIndex + 1; ind < endIndex; ind++) {
var obj = list[ind];
if (shouldMerge(prevObj, obj))
merge(prevObj, obj);
else {
prevObj = obj;
result.push(prevObj);
}
}
return result;
};
ListUtils.min = function (list, getValue, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
var res = ListUtils.minExtended(list, getValue, startIndex, endIndex);
return res ? res.minElement : null;
};
ListUtils.max = function (list, getValue, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
var res = ListUtils.maxExtended(list, getValue, startIndex, endIndex);
return res ? res.maxElement : null;
};
ListUtils.minMax = function (list, getValue, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
var res = ListUtils.minMaxExtended(list, getValue, startIndex, endIndex);
return res ? new min_max_1.MinMax(res.minElement, res.maxElement) : null;
};
ListUtils.minExtended = function (list, getValue, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
if (list.length === 0)
return null;
var minElement = list[startIndex];
var minValue = getValue(minElement);
for (var index = startIndex + 1; index < endIndex; index++) {
var elem = list[index];
var elemValue = getValue(elem);
if (elemValue < minValue) {
minValue = elemValue;
minElement = elem;
}
}
return new min_max_1.ExtendedMin(minElement, minValue);
};
ListUtils.maxExtended = function (list, getValue, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
if (list.length === 0)
return null;
var maxElement = list[startIndex];
var maxValue = getValue(maxElement);
for (var index = startIndex + 1; index < endIndex; index++) {
var elem = list[index];
var elemValue = getValue(elem);
if (elemValue > maxValue) {
maxValue = elemValue;
maxElement = elem;
}
}
return new min_max_1.ExtendedMax(maxElement, maxValue);
};
ListUtils.minMaxExtended = function (list, getValue, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
if (list.length === 0)
return null;
var minElement = list[startIndex];
var maxElement = minElement;
var minValue = getValue(minElement);
var maxValue = minValue;
for (var index = startIndex + 1; index < endIndex; index++) {
var elem = list[index];
var elemValue = getValue(elem);
if (elemValue < minValue) {
minValue = elemValue;
minElement = elem;
}
else if (elemValue > maxValue) {
maxValue = elemValue;
maxElement = elem;
}
}
return new min_max_1.ExtendedMinMax(minElement, minValue, maxElement, maxValue);
};
ListUtils.minByCmp = function (list, cmp, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
if (list.length === 0)
return null;
var found = list[startIndex];
for (var index = startIndex + 1; index < endIndex; index++) {
var elem = list[index];
if (cmp(elem, found) < 0)
found = elem;
}
return found;
};
ListUtils.maxByCmp = function (list, cmp, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
if (list.length === 0)
return null;
var found = list[startIndex];
for (var index = startIndex + 1; index < endIndex; index++) {
var elem = list[index];
if (cmp(elem, found) > 0)
found = elem;
}
return found;
};
ListUtils.minMaxByCmp = function (list, cmp, startIndex, endIndex) {
if (startIndex === void 0) { startIndex = 0; }
if (endIndex === void 0) { endIndex = list.length; }
if (list.length === 0)
return null;
var min = list[startIndex];
var max = min;
for (var index = startIndex + 1; index < endIndex; index++) {
var elem = list[index];
var res = cmp(elem, min);
if (res > 0)
max = elem;
else if (res < 0)
min = elem;
}
return new min_max_1.MinMax(min, max);
};
return ListUtils;
}());
exports.ListUtils = ListUtils;
/***/ }),
/* 97 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = __webpack_require__(58);
var MinMax = (function () {
function MinMax(minElement, maxElement) {
this.minElement = minElement;
this.maxElement = maxElement;
}
return MinMax;
}());
exports.MinMax = MinMax;
var MinMaxNumber = (function (_super) {
tslib_1.__extends(MinMaxNumber, _super);
function MinMaxNumber() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(MinMaxNumber.prototype, "length", {
get: function () {
return this.maxElement - this.minElement;
},
enumerable: true,
configurable: true
});
return MinMaxNumber;
}(MinMax));
exports.MinMaxNumber = MinMaxNumber;
var ExtendedMin = (function () {
function ExtendedMin(minElement, minValue) {
this.minElement = minElement;
this.minValue = minValue;
}
return ExtendedMin;
}());
exports.ExtendedMin = ExtendedMin;
var ExtendedMax = (function () {
function ExtendedMax(maxElement, maxValue) {
this.maxElement = maxElement;
this.maxValue = maxValue;
}
return ExtendedMax;
}());
exports.ExtendedMax = ExtendedMax;
var ExtendedMinMax = (function (_super) {
tslib_1.__extends(ExtendedMinMax, _super);
function ExtendedMinMax(minElement, minValue, maxElement, maxValue) {
var _this = _super.call(this, minElement, maxElement) || this;
_this.minValue = minValue;
_this.maxValue = maxValue;
return _this;
}
return ExtendedMinMax;
}(MinMax));
exports.ExtendedMinMax = ExtendedMinMax;
/***/ }),
/* 98 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Comparers = (function () {
function Comparers() {
}
Comparers.number = function (a, b) {
return a - b;
};
Comparers.string = function (a, b) {
return ((a === b) ? 0 : ((a > b) ? 1 : -1));
};
Comparers.stringIgnoreCase = function (a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
return ((a === b) ? 0 : ((a > b) ? 1 : -1));
};
return Comparers;
}());
exports.Comparers = Comparers;
var Equals = (function () {
function Equals() {
}
Equals.simpleType = function (a, b) {
return a === b;
};
Equals.object = function (a, b) {
return a && b && (a === b || a.equals(b));
};
return Equals;
}());
exports.Equals = Equals;
/***/ }),
/* 99 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourcesDialogParameters = void 0;
var tslib_1 = __webpack_require__(0);
var ResourceCollection_1 = __webpack_require__(22);
var DialogParametersBase_1 = __webpack_require__(33);
var ResourcesDialogParameters = (function (_super) {
(0, tslib_1.__extends)(ResourcesDialogParameters, _super);
function ResourcesDialogParameters() {
return _super !== null && _super.apply(this, arguments) || this;
}
ResourcesDialogParameters.prototype.clone = function () {
var clone = new ResourcesDialogParameters();
clone.resources = new ResourceCollection_1.ResourceCollection();
clone.resources.addRange(this.resources.items);
return clone;
};
return ResourcesDialogParameters;
}(DialogParametersBase_1.DialogParametersBase));
exports.ResourcesDialogParameters = ResourcesDialogParameters;
/***/ }),
/* 100 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskEditDialogCommand = void 0;
var tslib_1 = __webpack_require__(0);
var ResourceCollection_1 = __webpack_require__(22);
var ResourceAssigningArguments_1 = __webpack_require__(59);
var AssignResourceHistoryItem_1 = __webpack_require__(60);
var DeassignResourceHistoryItem_1 = __webpack_require__(34);
var TaskEndHistoryItem_1 = __webpack_require__(35);
var TaskProgressHistoryItem_1 = __webpack_require__(36);
var TaskStartHistoryItem_1 = __webpack_require__(37);
var TaskTitleHistoryItem_1 = __webpack_require__(44);
var DialogBase_1 = __webpack_require__(30);
var TaskEditParameters_1 = __webpack_require__(101);
var TaskEditDialogCommand = (function (_super) {
(0, tslib_1.__extends)(TaskEditDialogCommand, _super);
function TaskEditDialogCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskEditDialogCommand.prototype.onBeforeDialogShow = function (params) {
return this.modelManipulator.dispatcher.raiseTaskTaskEditDialogShowing(params, function (args) {
var newValues = args.values;
params.start = newValues.start;
params.end = newValues.end;
params.progress = newValues.progress;
params.title = newValues.title;
params.readOnlyFields = args.readOnlyFields;
params.hiddenFields = args.hiddenFields;
});
};
TaskEditDialogCommand.prototype.applyParameters = function (newParameters, oldParameters) {
this.history.beginTransaction();
var success = this.control.modelManipulator.dispatcher.raiseTaskMultipleUpdating(this.control.viewModel.tasks.getItemById(oldParameters.id), newParameters, function (newValues) {
newParameters.title = newValues.title ? newValues.title : "";
newParameters.progress = newValues.progress;
newParameters.start = typeof newValues.start === "string" ? new Date(newValues.start) : newValues.start || new Date(0);
newParameters.end = typeof newValues.end === "string" ? new Date(newValues.end) : newValues.end || new Date(0);
});
if (success) {
if (newParameters.title !== oldParameters.title)
this.history.addAndRedo(new TaskTitleHistoryItem_1.TaskTitleHistoryItem(this.modelManipulator, oldParameters.id, newParameters.title));
if (newParameters.progress !== oldParameters.progress)
this.history.addAndRedo(new TaskProgressHistoryItem_1.TaskProgressHistoryItem(this.modelManipulator, oldParameters.id, newParameters.progress));
if (newParameters.end.getTime() < newParameters.start.getTime())
newParameters.end = newParameters.start;
if (newParameters.start !== oldParameters.start) {
this.history.addAndRedo(new TaskStartHistoryItem_1.TaskStartHistoryItem(this.modelManipulator, oldParameters.id, newParameters.start));
if (this.control.isValidateDependenciesRequired())
this.control.validationController.moveStartDependTasks(oldParameters.id, oldParameters.start);
}
if (newParameters.end !== oldParameters.end) {
this.history.addAndRedo(new TaskEndHistoryItem_1.TaskEndHistoryItem(this.modelManipulator, oldParameters.id, newParameters.end));
if (this.control.isValidateDependenciesRequired())
this.control.validationController.moveEndDependTasks(oldParameters.id, oldParameters.end);
}
}
for (var i = 0; i < newParameters.assigned.length; i++) {
var resource = oldParameters.assigned.getItemById(newParameters.assigned.getItem(i).internalId);
if (!resource) {
var resourceId = newParameters.assigned.getItem(i).internalId;
var taskId = oldParameters.id;
var args = new ResourceAssigningArguments_1.ResourceAssigningArguments(resourceId, taskId);
this.modelManipulator.dispatcher.notifyResourceAssigning(args);
if (!args.cancel)
this.history.addAndRedo(new AssignResourceHistoryItem_1.AssignResourceHistoryItem(this.modelManipulator, args.resourceId, args.taskId));
}
}
var _loop_1 = function (i) {
var assigned = oldParameters.assigned.getItem(i);
var resource = newParameters.assigned.getItemById(assigned.internalId);
if (!resource) {
var assignment = this_1.control.viewModel.assignments.items.filter(function (assignment) { return assignment.resourceId === assigned.internalId && assignment.taskId === oldParameters.id; })[0];
if (this_1.modelManipulator.dispatcher.fireResourceUnassigning(assignment))
this_1.history.addAndRedo(new DeassignResourceHistoryItem_1.DeassignResourceHistoryItem(this_1.modelManipulator, assignment.internalId));
}
};
var this_1 = this;
for (var i = 0; i < oldParameters.assigned.length; i++) {
_loop_1(i);
}
var updateParents = newParameters.start !== oldParameters.start || newParameters.end !== oldParameters.end || newParameters.progress !== oldParameters.progress;
if (success && updateParents)
this.validationController.updateParentsIfRequired(oldParameters.id);
this.history.endTransaction();
return false;
};
TaskEditDialogCommand.prototype.createParameters = function (options) {
var _this = this;
options = options || this.control.viewModel.tasks.getItemById(this.control.currentSelectedTaskID);
var param = new TaskEditParameters_1.TaskEditParameters();
param.id = options.internalId;
param.title = options.title;
param.progress = options.progress;
param.start = options.start;
param.end = options.end;
param.assigned = this.control.viewModel.getAssignedResources(options);
param.resources = new ResourceCollection_1.ResourceCollection();
param.resources.addRange(this.control.viewModel.resources.items);
param.showResourcesDialogCommand = this.control.commandManager.showResourcesDialog;
param.showTaskEditDialogCommand = this.control.commandManager.showTaskEditDialog;
param.enableEdit = this.isTaskEditEnabled();
param.enableRangeEdit = this.isTaskRangeEditEnabled(options);
param.isValidationRequired = this.control.isValidateDependenciesRequired();
param.getCorrectDateRange = function (taskId, startDate, endDate) { return _this.control.validationController.getCorrectDateRange(taskId, startDate, endDate); };
return param;
};
TaskEditDialogCommand.prototype.isTaskEditEnabled = function () {
var settings = this.control.settings;
return settings.editing.enabled && settings.editing.allowTaskUpdate;
};
TaskEditDialogCommand.prototype.isTaskRangeEditEnabled = function (task) {
return !this.control.viewModel.isTaskToCalculateByChildren(task.internalId);
};
TaskEditDialogCommand.prototype.isEnabled = function () {
var gantt = this.control;
var selectedItem = gantt.viewModel.findItem(gantt.currentSelectedTaskID);
return (!!selectedItem && selectedItem.selected) || this.isApiCall;
};
TaskEditDialogCommand.prototype.getState = function () {
var state = _super.prototype.getState.call(this);
state.visible = state.visible && !this.control.taskEditController.dependencyId;
return state;
};
TaskEditDialogCommand.prototype.getDialogName = function () {
return "TaskEdit";
};
return TaskEditDialogCommand;
}(DialogBase_1.DialogBase));
exports.TaskEditDialogCommand = TaskEditDialogCommand;
/***/ }),
/* 101 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskEditParameters = void 0;
var tslib_1 = __webpack_require__(0);
var ResourceCollection_1 = __webpack_require__(22);
var DialogParametersBase_1 = __webpack_require__(33);
var TaskEditParameters = (function (_super) {
(0, tslib_1.__extends)(TaskEditParameters, _super);
function TaskEditParameters() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.enableEdit = true;
_this.enableRangeEdit = true;
_this.isValidationRequired = false;
_this.hiddenFields = [];
_this.readOnlyFields = [];
return _this;
}
TaskEditParameters.prototype.clone = function () {
var clone = new TaskEditParameters();
clone.id = this.id;
clone.title = this.title;
clone.progress = this.progress;
clone.start = this.start;
clone.end = this.end;
clone.assigned = new ResourceCollection_1.ResourceCollection();
clone.assigned.addRange(this.assigned.items);
clone.resources = new ResourceCollection_1.ResourceCollection();
clone.resources.addRange(this.resources.items);
clone.showResourcesDialogCommand = this.showResourcesDialogCommand;
clone.showTaskEditDialogCommand = this.showTaskEditDialogCommand;
clone.enableEdit = this.enableEdit;
clone.enableRangeEdit = this.enableRangeEdit;
clone.hiddenFields = this.hiddenFields.slice();
clone.readOnlyFields = this.readOnlyFields.slice();
clone.isValidationRequired = this.isValidationRequired;
clone.getCorrectDateRange = this.getCorrectDateRange;
return clone;
};
return TaskEditParameters;
}(DialogParametersBase_1.DialogParametersBase));
exports.TaskEditParameters = TaskEditParameters;
/***/ }),
/* 102 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GanttClientCommand = void 0;
var GanttClientCommand;
(function (GanttClientCommand) {
GanttClientCommand[GanttClientCommand["CreateTask"] = 0] = "CreateTask";
GanttClientCommand[GanttClientCommand["CreateSubTask"] = 1] = "CreateSubTask";
GanttClientCommand[GanttClientCommand["RemoveTask"] = 2] = "RemoveTask";
GanttClientCommand[GanttClientCommand["RemoveDependency"] = 3] = "RemoveDependency";
GanttClientCommand[GanttClientCommand["TaskInformation"] = 4] = "TaskInformation";
GanttClientCommand[GanttClientCommand["TaskAddContextItem"] = 5] = "TaskAddContextItem";
GanttClientCommand[GanttClientCommand["Undo"] = 6] = "Undo";
GanttClientCommand[GanttClientCommand["Redo"] = 7] = "Redo";
GanttClientCommand[GanttClientCommand["ZoomIn"] = 8] = "ZoomIn";
GanttClientCommand[GanttClientCommand["ZoomOut"] = 9] = "ZoomOut";
GanttClientCommand[GanttClientCommand["FullScreen"] = 10] = "FullScreen";
GanttClientCommand[GanttClientCommand["CollapseAll"] = 11] = "CollapseAll";
GanttClientCommand[GanttClientCommand["ExpandAll"] = 12] = "ExpandAll";
GanttClientCommand[GanttClientCommand["ResourceManager"] = 13] = "ResourceManager";
GanttClientCommand[GanttClientCommand["ToggleResources"] = 14] = "ToggleResources";
GanttClientCommand[GanttClientCommand["ToggleDependencies"] = 15] = "ToggleDependencies";
})(GanttClientCommand = exports.GanttClientCommand || (exports.GanttClientCommand = {}));
/***/ }),
/* 103 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CollapseAllCommand = void 0;
var tslib_1 = __webpack_require__(0);
var CommandBase_1 = __webpack_require__(5);
var SimpleCommandState_1 = __webpack_require__(6);
var CollapseAllCommand = (function (_super) {
(0, tslib_1.__extends)(CollapseAllCommand, _super);
function CollapseAllCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
CollapseAllCommand.prototype.getState = function () {
return new SimpleCommandState_1.SimpleCommandState(this.isEnabled());
};
CollapseAllCommand.prototype.execute = function () {
return _super.prototype.execute.call(this);
};
CollapseAllCommand.prototype.executeInternal = function () {
this.control.collapseAll();
return true;
};
CollapseAllCommand.prototype.isEnabled = function () {
return true;
};
return CollapseAllCommand;
}(CommandBase_1.CommandBase));
exports.CollapseAllCommand = CollapseAllCommand;
/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExpandAllCommand = void 0;
var tslib_1 = __webpack_require__(0);
var CommandBase_1 = __webpack_require__(5);
var SimpleCommandState_1 = __webpack_require__(6);
var ExpandAllCommand = (function (_super) {
(0, tslib_1.__extends)(ExpandAllCommand, _super);
function ExpandAllCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
ExpandAllCommand.prototype.getState = function () {
return new SimpleCommandState_1.SimpleCommandState(this.isEnabled());
};
ExpandAllCommand.prototype.execute = function () {
return _super.prototype.execute.call(this);
};
ExpandAllCommand.prototype.executeInternal = function () {
this.control.expandAll();
return true;
};
ExpandAllCommand.prototype.isEnabled = function () {
return true;
};
return ExpandAllCommand;
}(CommandBase_1.CommandBase));
exports.ExpandAllCommand = ExpandAllCommand;
/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CreateDependencyCommand = void 0;
var tslib_1 = __webpack_require__(0);
var Enums_1 = __webpack_require__(24);
var DependencyInsertingArguments_1 = __webpack_require__(106);
var InsertDependencyHistoryItem_1 = __webpack_require__(107);
var DependencyCommandBase_1 = __webpack_require__(61);
var CreateDependencyCommand = (function (_super) {
(0, tslib_1.__extends)(CreateDependencyCommand, _super);
function CreateDependencyCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
CreateDependencyCommand.prototype.execute = function (predecessorId, successorId, type) {
return _super.prototype.execute.call(this, predecessorId, successorId, type);
};
CreateDependencyCommand.prototype.executeInternal = function (predecessorId, successorId, type) {
if (this.control.viewModel.dependencies.items.filter(function (d) { return (d.predecessorId === predecessorId && d.successorId === successorId) ||
(d.successorId === predecessorId && d.predecessorId === successorId); }).length)
return false;
var args = new DependencyInsertingArguments_1.DependencyInsertingArguments(predecessorId, successorId, type);
this.modelManipulator.dispatcher.notifyDependencyInserting(args);
if (args.cancel)
return false;
predecessorId = args.predecessorId;
successorId = args.successorId;
type = args.type;
this.control.history.beginTransaction();
this.history.addAndRedo(new InsertDependencyHistoryItem_1.InsertDependencyHistoryItem(this.modelManipulator, predecessorId, successorId, type));
if (this.control.isValidateDependenciesRequired()) {
var predecessorTask = this.control.viewModel.tasks.getItemById(predecessorId);
if (type === Enums_1.DependencyType.SF || type === Enums_1.DependencyType.SS)
this.control.validationController.moveStartDependTasks(predecessorId, predecessorTask.start);
else
this.control.validationController.moveEndDependTasks(predecessorId, predecessorTask.end);
}
this.control.history.endTransaction();
return true;
};
CreateDependencyCommand.prototype.isEnabled = function () {
return _super.prototype.isEnabled.call(this) && this.control.settings.editing.allowDependencyInsert;
};
return CreateDependencyCommand;
}(DependencyCommandBase_1.DependencyCommandBase));
exports.CreateDependencyCommand = CreateDependencyCommand;
/***/ }),
/* 106 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DependencyInsertingArguments = void 0;
var tslib_1 = __webpack_require__(0);
var BaseArguments_1 = __webpack_require__(9);
var DependencyInsertingArguments = (function (_super) {
(0, tslib_1.__extends)(DependencyInsertingArguments, _super);
function DependencyInsertingArguments(predecessorId, successorId, type) {
var _this = _super.call(this, null) || this;
_this.values = {
predecessorId: predecessorId,
successorId: successorId,
type: type
};
return _this;
}
Object.defineProperty(DependencyInsertingArguments.prototype, "predecessorId", {
get: function () { return this.values.predecessorId; },
enumerable: false,
configurable: true
});
Object.defineProperty(DependencyInsertingArguments.prototype, "successorId", {
get: function () { return this.values.successorId; },
enumerable: false,
configurable: true
});
Object.defineProperty(DependencyInsertingArguments.prototype, "type", {
get: function () { return this.values.type; },
enumerable: false,
configurable: true
});
return DependencyInsertingArguments;
}(BaseArguments_1.BaseArguments));
exports.DependencyInsertingArguments = DependencyInsertingArguments;
/***/ }),
/* 107 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InsertDependencyHistoryItem = void 0;
var tslib_1 = __webpack_require__(0);
var HistoryItem_1 = __webpack_require__(12);
var InsertDependencyHistoryItem = (function (_super) {
(0, tslib_1.__extends)(InsertDependencyHistoryItem, _super);
function InsertDependencyHistoryItem(modelManipulator, predecessorId, successorId, type) {
var _this = _super.call(this, modelManipulator) || this;
_this.predecessorId = predecessorId;
_this.successorId = successorId;
_this.type = type;
return _this;
}
InsertDependencyHistoryItem.prototype.redo = function () {
this.dependency = this.modelManipulator.dependency.insertDependency(this.predecessorId, this.successorId, this.type, this.dependency ? this.dependency.internalId : null);
};
InsertDependencyHistoryItem.prototype.undo = function () {
this.modelManipulator.dependency.removeDependency(this.dependency.internalId);
};
return InsertDependencyHistoryItem;
}(HistoryItem_1.HistoryItem));
exports.InsertDependencyHistoryItem = InsertDependencyHistoryItem;
/***/ }),
/* 108 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RemoveDependencyCommand = void 0;
var tslib_1 = __webpack_require__(0);
var DialogEnums_1 = __webpack_require__(32);
var ConfirmationDialogParameters_1 = __webpack_require__(43);
var DependencyRemovingArguments_1 = __webpack_require__(109);
var RemoveDependencyHistoryItem_1 = __webpack_require__(31);
var DependencyCommandBase_1 = __webpack_require__(61);
var RemoveDependencyCommand = (function (_super) {
(0, tslib_1.__extends)(RemoveDependencyCommand, _super);
function RemoveDependencyCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
RemoveDependencyCommand.prototype.execute = function (id, confirmRequired) {
var _this = this;
if (confirmRequired === void 0) { confirmRequired = true; }
if (confirmRequired) {
this.control.commandManager.showConfirmationDialog.execute(new ConfirmationDialogParameters_1.ConfirmationDialogParameters(DialogEnums_1.ConfirmationType.DependencyDelete, function () { _this.executeInternal(id); }));
return false;
}
return _super.prototype.execute.call(this, id);
};
RemoveDependencyCommand.prototype.executeInternal = function (id) {
id = id || this.control.taskEditController.dependencyId;
if (id != null) {
var dependency = this.control.viewModel.dependencies.items.filter(function (d) { return d.internalId === id; })[0];
if (dependency) {
var args = new DependencyRemovingArguments_1.DependencyRemovingArguments(dependency);
this.modelManipulator.dispatcher.notifyDependencyRemoving(args);
if (!args.cancel) {
this.history.addAndRedo(new RemoveDependencyHistoryItem_1.RemoveDependencyHistoryItem(this.modelManipulator, id));
if (id === this.control.taskEditController.dependencyId)
this.control.taskEditController.selectDependency(null);
this.control.barManager.updateItemsState([]);
return true;
}
}
}
return false;
};
RemoveDependencyCommand.prototype.isEnabled = function () {
return _super.prototype.isEnabled.call(this) && this.control.settings.editing.allowDependencyDelete;
};
RemoveDependencyCommand.prototype.getState = function () {
var state = _super.prototype.getState.call(this);
state.visible = state.enabled && this.control.taskEditController.dependencyId != null;
return state;
};
return RemoveDependencyCommand;
}(DependencyCommandBase_1.DependencyCommandBase));
exports.RemoveDependencyCommand = RemoveDependencyCommand;
/***/ }),
/* 109 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DependencyRemovingArguments = void 0;
var tslib_1 = __webpack_require__(0);
var BaseArguments_1 = __webpack_require__(9);
var DependencyRemovingArguments = (function (_super) {
(0, tslib_1.__extends)(DependencyRemovingArguments, _super);
function DependencyRemovingArguments(dependency) {
var _this = _super.call(this, dependency.id) || this;
_this.values = dependency;
return _this;
}
return DependencyRemovingArguments;
}(BaseArguments_1.BaseArguments));
exports.DependencyRemovingArguments = DependencyRemovingArguments;
/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ToggleDependenciesCommand = void 0;
var tslib_1 = __webpack_require__(0);
var CommandBase_1 = __webpack_require__(5);
var SimpleCommandState_1 = __webpack_require__(6);
var ToggleDependenciesCommand = (function (_super) {
(0, tslib_1.__extends)(ToggleDependenciesCommand, _super);
function ToggleDependenciesCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
ToggleDependenciesCommand.prototype.getState = function () {
return new SimpleCommandState_1.SimpleCommandState(true);
};
ToggleDependenciesCommand.prototype.execute = function () {
return _super.prototype.execute.call(this);
};
ToggleDependenciesCommand.prototype.executeInternal = function () {
this.control.toggleDependencies();
return true;
};
return ToggleDependenciesCommand;
}(CommandBase_1.CommandBase));
exports.ToggleDependenciesCommand = ToggleDependenciesCommand;
/***/ }),
/* 111 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ToggleFullScreenCommand = void 0;
var tslib_1 = __webpack_require__(0);
var CommandBase_1 = __webpack_require__(5);
var SimpleCommandState_1 = __webpack_require__(6);
var ToggleFullScreenCommand = (function (_super) {
(0, tslib_1.__extends)(ToggleFullScreenCommand, _super);
function ToggleFullScreenCommand() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.isInFullScreenMode = false;
_this.fullScreenTempVars = {};
return _this;
}
ToggleFullScreenCommand.prototype.getState = function () {
var state = new SimpleCommandState_1.SimpleCommandState(true);
state.value = this.control.fullScreenModeHelper.isInFullScreenMode;
return state;
};
ToggleFullScreenCommand.prototype.execute = function () {
return _super.prototype.execute.call(this);
};
ToggleFullScreenCommand.prototype.executeInternal = function () {
this.control.fullScreenModeHelper.toggle();
return true;
};
return ToggleFullScreenCommand;
}(CommandBase_1.CommandBase));
exports.ToggleFullScreenCommand = ToggleFullScreenCommand;
/***/ }),
/* 112 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RedoCommand = void 0;
var tslib_1 = __webpack_require__(0);
var CommandBase_1 = __webpack_require__(5);
var SimpleCommandState_1 = __webpack_require__(6);
var RedoCommand = (function (_super) {
(0, tslib_1.__extends)(RedoCommand, _super);
function RedoCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
RedoCommand.prototype.getState = function () {
var state = new SimpleCommandState_1.SimpleCommandState(this.isEnabled());
state.visible = this.control.settings.editing.enabled;
return state;
};
RedoCommand.prototype.execute = function () {
return _super.prototype.execute.call(this);
};
RedoCommand.prototype.executeInternal = function () {
this.history.redo();
return true;
};
RedoCommand.prototype.isEnabled = function () {
return _super.prototype.isEnabled.call(this) && this.history.canRedo();
};
return RedoCommand;
}(CommandBase_1.CommandBase));
exports.RedoCommand = RedoCommand;
/***/ }),
/* 113 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UndoCommand = void 0;
var tslib_1 = __webpack_require__(0);
var CommandBase_1 = __webpack_require__(5);
var SimpleCommandState_1 = __webpack_require__(6);
var UndoCommand = (function (_super) {
(0, tslib_1.__extends)(UndoCommand, _super);
function UndoCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
UndoCommand.prototype.getState = function () {
var state = new SimpleCommandState_1.SimpleCommandState(this.isEnabled());
state.visible = this.control.settings.editing.enabled;
return state;
};
UndoCommand.prototype.execute = function () {
return _super.prototype.execute.call(this);
};
UndoCommand.prototype.executeInternal = function () {
this.history.undo();
return true;
};
UndoCommand.prototype.isEnabled = function () {
return _super.prototype.isEnabled.call(this) && this.history.canUndo();
};
return UndoCommand;
}(CommandBase_1.CommandBase));
exports.UndoCommand = UndoCommand;
/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AssignResourceCommand = void 0;
var tslib_1 = __webpack_require__(0);
var ResourceAssigningArguments_1 = __webpack_require__(59);
var AssignResourceHistoryItem_1 = __webpack_require__(60);
var ResourceCommandBase_1 = __webpack_require__(38);
var AssignResourceCommand = (function (_super) {
(0, tslib_1.__extends)(AssignResourceCommand, _super);
function AssignResourceCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
AssignResourceCommand.prototype.execute = function (resourceId, taskId) {
return _super.prototype.execute.call(this, resourceId, taskId);
};
AssignResourceCommand.prototype.executeInternal = function (resourceId, taskId) {
var assignment = this.control.viewModel.assignments.items.filter(function (r) { return r.resourceId === resourceId && r.taskId === taskId; })[0];
if (!assignment) {
var converter = this.control.viewModel;
var args = new ResourceAssigningArguments_1.ResourceAssigningArguments(converter.convertInternalToPublicKey("resource", resourceId), converter.convertInternalToPublicKey("task", taskId));
this.modelManipulator.dispatcher.notifyResourceAssigning(args);
if (!args.cancel) {
this.history.addAndRedo(new AssignResourceHistoryItem_1.AssignResourceHistoryItem(this.modelManipulator, converter.convertPublicToInternalKey("resource", args.resourceId), converter.convertPublicToInternalKey("task", args.taskId)));
return true;
}
}
return false;
};
AssignResourceCommand.prototype.isEnabled = function () {
return _super.prototype.isEnabled.call(this) && this.control.settings.editing.allowTaskResourceUpdate;
};
return AssignResourceCommand;
}(ResourceCommandBase_1.ResourceCommandBase));
exports.AssignResourceCommand = AssignResourceCommand;
/***/ }),
/* 115 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CreateResourceCommand = void 0;
var tslib_1 = __webpack_require__(0);
var ResourceInsertingArguments_1 = __webpack_require__(116);
var CreateResourceHistoryItem_1 = __webpack_require__(62);
var ResourceCommandBase_1 = __webpack_require__(38);
var CreateResourceCommand = (function (_super) {
(0, tslib_1.__extends)(CreateResourceCommand, _super);
function CreateResourceCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
CreateResourceCommand.prototype.execute = function (text, color, callback) {
if (color === void 0) { color = ""; }
return _super.prototype.execute.call(this, text, color, callback);
};
CreateResourceCommand.prototype.executeInternal = function (text, color, callback) {
if (color === void 0) { color = ""; }
var args = new ResourceInsertingArguments_1.ResourceInsertingArguments(text, color);
this.modelManipulator.dispatcher.notifyResourceCreating(args);
if (!args.cancel)
this.history.addAndRedo(new CreateResourceHistoryItem_1.CreateResourceHistoryItem(this.modelManipulator, args.text, args.color, callback));
return !args.cancel;
};
CreateResourceCommand.prototype.isEnabled = function () {
return _super.prototype.isEnabled.call(this) && this.control.settings.editing.allowResourceInsert;
};
return CreateResourceCommand;
}(ResourceCommandBase_1.ResourceCommandBase));
exports.CreateResourceCommand = CreateResourceCommand;
/***/ }),
/* 116 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourceInsertingArguments = void 0;
var tslib_1 = __webpack_require__(0);
var BaseArguments_1 = __webpack_require__(9);
var ResourceInsertingArguments = (function (_super) {
(0, tslib_1.__extends)(ResourceInsertingArguments, _super);
function ResourceInsertingArguments(text, color) {
if (color === void 0) { color = ""; }
var _this = _super.call(this, null) || this;
_this.values = {
text: text,
color: color
};
return _this;
}
Object.defineProperty(ResourceInsertingArguments.prototype, "text", {
get: function () { return this.values.text; },
enumerable: false,
configurable: true
});
Object.defineProperty(ResourceInsertingArguments.prototype, "color", {
get: function () { return this.values.color; },
enumerable: false,
configurable: true
});
return ResourceInsertingArguments;
}(BaseArguments_1.BaseArguments));
exports.ResourceInsertingArguments = ResourceInsertingArguments;
/***/ }),
/* 117 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DeassignResourceCommand = void 0;
var tslib_1 = __webpack_require__(0);
var DeassignResourceHistoryItem_1 = __webpack_require__(34);
var ResourceCommandBase_1 = __webpack_require__(38);
var DeassignResourceCommand = (function (_super) {
(0, tslib_1.__extends)(DeassignResourceCommand, _super);
function DeassignResourceCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
DeassignResourceCommand.prototype.execute = function (assignmentId) {
return _super.prototype.execute.call(this, assignmentId);
};
DeassignResourceCommand.prototype.executeInternal = function (assignmentId) {
var assignment = this.control.viewModel.assignments.items.filter(function (r) { return r.internalId === assignmentId; })[0];
if (assignment && this.modelManipulator.dispatcher.fireResourceUnassigning(assignment)) {
this.history.addAndRedo(new DeassignResourceHistoryItem_1.DeassignResourceHistoryItem(this.modelManipulator, assignmentId));
return true;
}
return false;
};
DeassignResourceCommand.prototype.isEnabled = function () {
return _super.prototype.isEnabled.call(this) && this.control.settings.editing.allowTaskResourceUpdate;
};
return DeassignResourceCommand;
}(ResourceCommandBase_1.ResourceCommandBase));
exports.DeassignResourceCommand = DeassignResourceCommand;
/***/ }),
/* 118 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourceColorCommand = void 0;
var tslib_1 = __webpack_require__(0);
var ResourceColorHistoryItem_1 = __webpack_require__(119);
var ResourcePropertyCommandBase_1 = __webpack_require__(121);
var ResourceColorCommand = (function (_super) {
(0, tslib_1.__extends)(ResourceColorCommand, _super);
function ResourceColorCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
ResourceColorCommand.prototype.execute = function (id, value) {
return _super.prototype.execute.call(this, id, value);
};
ResourceColorCommand.prototype.executeInternal = function (id, value) {
var oldColor = this.control.viewModel.resources.getItemById(id).color;
if (oldColor === value)
return false;
this.history.addAndRedo(new ResourceColorHistoryItem_1.ResourceColorHistoryItem(this.modelManipulator, id, value));
return true;
};
return ResourceColorCommand;
}(ResourcePropertyCommandBase_1.ResourcePropertyCommandBase));
exports.ResourceColorCommand = ResourceColorCommand;
/***/ }),
/* 119 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourceColorHistoryItem = void 0;
var tslib_1 = __webpack_require__(0);
var ResourcePropertiesHistoryItemBase_1 = __webpack_require__(120);
var ResourceColorHistoryItem = (function (_super) {
(0, tslib_1.__extends)(ResourceColorHistoryItem, _super);
function ResourceColorHistoryItem() {
return _super !== null && _super.apply(this, arguments) || this;
}
ResourceColorHistoryItem.prototype.getPropertiesManipulator = function () {
return this.modelManipulator.resource.properties.color;
};
return ResourceColorHistoryItem;
}(ResourcePropertiesHistoryItemBase_1.ResourcePropertiesHistoryItemBase));
exports.ResourceColorHistoryItem = ResourceColorHistoryItem;
/***/ }),
/* 120 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourcePropertiesHistoryItemBase = void 0;
var tslib_1 = __webpack_require__(0);
var HistoryItem_1 = __webpack_require__(12);
var ResourcePropertiesHistoryItemBase = (function (_super) {
(0, tslib_1.__extends)(ResourcePropertiesHistoryItemBase, _super);
function ResourcePropertiesHistoryItemBase(modelManipulator, resourceId, newValue) {
var _this = _super.call(this, modelManipulator) || this;
_this.resourceId = resourceId;
_this.newValue = newValue;
return _this;
}
ResourcePropertiesHistoryItemBase.prototype.redo = function () {
this.oldState = this.getPropertiesManipulator().setValue(this.resourceId, this.newValue);
};
ResourcePropertiesHistoryItemBase.prototype.undo = function () {
this.getPropertiesManipulator().restoreValue(this.oldState);
};
ResourcePropertiesHistoryItemBase.prototype.getPropertiesManipulator = function () {
throw new Error("Not Implemented");
};
return ResourcePropertiesHistoryItemBase;
}(HistoryItem_1.HistoryItem));
exports.ResourcePropertiesHistoryItemBase = ResourcePropertiesHistoryItemBase;
/***/ }),
/* 121 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourcePropertyCommandBase = void 0;
var tslib_1 = __webpack_require__(0);
var CommandBase_1 = __webpack_require__(5);
var SimpleCommandState_1 = __webpack_require__(6);
var ResourcePropertyCommandBase = (function (_super) {
(0, tslib_1.__extends)(ResourcePropertyCommandBase, _super);
function ResourcePropertyCommandBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
ResourcePropertyCommandBase.prototype.getState = function () {
return new SimpleCommandState_1.SimpleCommandState(this.isEnabled());
};
ResourcePropertyCommandBase.prototype.isEnabled = function () {
return _super.prototype.isEnabled.call(this) && this.control.settings.editing.allowResourceUpdate;
};
return ResourcePropertyCommandBase;
}(CommandBase_1.CommandBase));
exports.ResourcePropertyCommandBase = ResourcePropertyCommandBase;
/***/ }),
/* 122 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RemoveResourceCommand = void 0;
var tslib_1 = __webpack_require__(0);
var ResourceRemovingArguments_1 = __webpack_require__(123);
var RemoveResourceHistoryItem_1 = __webpack_require__(124);
var DeassignResourceHistoryItem_1 = __webpack_require__(34);
var ResourceCommandBase_1 = __webpack_require__(38);
var RemoveResourceCommand = (function (_super) {
(0, tslib_1.__extends)(RemoveResourceCommand, _super);
function RemoveResourceCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
RemoveResourceCommand.prototype.execute = function (id) {
return _super.prototype.execute.call(this, id);
};
RemoveResourceCommand.prototype.executeInternal = function (id) {
var _this = this;
var resource = this.control.viewModel.resources.items.filter(function (r) { return r.internalId === id; })[0];
if (resource) {
var args = new ResourceRemovingArguments_1.ResourceRemovingArguments(resource);
this.modelManipulator.dispatcher.notifyResourceRemoving(args);
if (!args.cancel) {
var removeResourceHistoryItem_1 = new RemoveResourceHistoryItem_1.RemoveResourceHistoryItem(this.modelManipulator, id);
var assignments = this.control.viewModel.assignments.items.filter(function (a) { return a.resourceId === id; });
assignments.forEach(function (a) {
if (_this.modelManipulator.dispatcher.fireResourceUnassigning(a))
removeResourceHistoryItem_1.add(new DeassignResourceHistoryItem_1.DeassignResourceHistoryItem(_this.modelManipulator, a.internalId));
});
this.history.addAndRedo(removeResourceHistoryItem_1);
return true;
}
}
return false;
};
RemoveResourceCommand.prototype.isEnabled = function () {
return _super.prototype.isEnabled.call(this) && this.control.settings.editing.allowResourceDelete;
};
return RemoveResourceCommand;
}(ResourceCommandBase_1.ResourceCommandBase));
exports.RemoveResourceCommand = RemoveResourceCommand;
/***/ }),
/* 123 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourceRemovingArguments = void 0;
var tslib_1 = __webpack_require__(0);
var BaseArguments_1 = __webpack_require__(9);
var ResourceRemovingArguments = (function (_super) {
(0, tslib_1.__extends)(ResourceRemovingArguments, _super);
function ResourceRemovingArguments(resource) {
var _this = _super.call(this, resource.id) || this;
_this.values = resource;
return _this;
}
return ResourceRemovingArguments;
}(BaseArguments_1.BaseArguments));
exports.ResourceRemovingArguments = ResourceRemovingArguments;
/***/ }),
/* 124 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RemoveResourceHistoryItem = void 0;
var tslib_1 = __webpack_require__(0);
var CompositionHistoryItem_1 = __webpack_require__(45);
var RemoveResourceHistoryItem = (function (_super) {
(0, tslib_1.__extends)(RemoveResourceHistoryItem, _super);
function RemoveResourceHistoryItem(modelManipulator, resourceId) {
var _this = _super.call(this) || this;
_this.modelManipulator = modelManipulator;
_this.resourceId = resourceId;
return _this;
}
RemoveResourceHistoryItem.prototype.redo = function () {
_super.prototype.redo.call(this);
this.resource = this.modelManipulator.resource.remove(this.resourceId);
};
RemoveResourceHistoryItem.prototype.undo = function () {
var _this = this;
this.modelManipulator.resource.create(this.resource.text, this.resource.color, this.resourceId, function () {
if (_this.resource.color)
_this.modelManipulator.resource.properties.color.setValue(_this.resource.internalId, _this.resource.color);
_super.prototype.undo.call(_this);
});
};
RemoveResourceHistoryItem.prototype.undoItemsQuery = function () {
this.modelManipulator.resource.create(this.resource.text, this.resource.color, this.resourceId, function () { });
if (this.resource.color)
this.modelManipulator.resource.properties.color.setValue(this.resource.internalId, this.resource.color);
_super.prototype.undo.call(this);
};
return RemoveResourceHistoryItem;
}(CompositionHistoryItem_1.CompositionHistoryItem));
exports.RemoveResourceHistoryItem = RemoveResourceHistoryItem;
/***/ }),
/* 125 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ToggleResourceCommand = void 0;
var tslib_1 = __webpack_require__(0);
var CommandBase_1 = __webpack_require__(5);
var SimpleCommandState_1 = __webpack_require__(6);
var ToggleResourceCommand = (function (_super) {
(0, tslib_1.__extends)(ToggleResourceCommand, _super);
function ToggleResourceCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
ToggleResourceCommand.prototype.getState = function () {
return new SimpleCommandState_1.SimpleCommandState(true);
};
ToggleResourceCommand.prototype.execute = function () {
return _super.prototype.execute.call(this);
};
ToggleResourceCommand.prototype.executeInternal = function () {
this.control.toggleResources();
return true;
};
return ToggleResourceCommand;
}(CommandBase_1.CommandBase));
exports.ToggleResourceCommand = ToggleResourceCommand;
/***/ }),
/* 126 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CreateSubTaskCommand = void 0;
var tslib_1 = __webpack_require__(0);
var TaskInsertingArguments_1 = __webpack_require__(63);
var CreateTaskHistoryItem_1 = __webpack_require__(46);
var TaskCommandBase_1 = __webpack_require__(25);
var CreateSubTaskCommand = (function (_super) {
(0, tslib_1.__extends)(CreateSubTaskCommand, _super);
function CreateSubTaskCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
CreateSubTaskCommand.prototype.execute = function (parentId) {
return _super.prototype.execute.call(this, parentId);
};
CreateSubTaskCommand.prototype.executeInternal = function (parentId) {
parentId = parentId || this.control.currentSelectedTaskID;
var selectedItem = this.control.viewModel.findItem(parentId);
if (selectedItem.selected) {
var data = {
start: new Date(selectedItem.task.start.getTime()),
end: new Date(selectedItem.task.end.getTime()),
title: "New task",
progress: 0,
parentId: parentId
};
var args = new TaskInsertingArguments_1.TaskInsertingArguments(null, data);
this.modelManipulator.dispatcher.notifyTaskCreating(args);
if (!args.cancel) {
this.history.addAndRedo(new CreateTaskHistoryItem_1.CreateTaskHistoryItem(this.modelManipulator, args));
var parentItem = this.control.viewModel.findItem(data.parentId);
_super.prototype.updateParent.call(this, parentItem);
}
return !args.cancel;
}
return false;
};
CreateSubTaskCommand.prototype.isEnabled = function () {
var gantt = this.control;
var selectedItem = gantt.viewModel.findItem(gantt.currentSelectedTaskID);
return _super.prototype.isEnabled.call(this) && !!selectedItem && selectedItem.selected;
};
CreateSubTaskCommand.prototype.getState = function () {
var state = _super.prototype.getState.call(this);
var gantt = this.control;
state.visible = state.visible && gantt.settings.editing.allowTaskInsert;
return state;
};
return CreateSubTaskCommand;
}(TaskCommandBase_1.TaskCommandBase));
exports.CreateSubTaskCommand = CreateSubTaskCommand;
/***/ }),
/* 127 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CreateTaskCommand = void 0;
var tslib_1 = __webpack_require__(0);
var TaskInsertingArguments_1 = __webpack_require__(63);
var CreateTaskHistoryItem_1 = __webpack_require__(46);
var TaskCommandBase_1 = __webpack_require__(25);
var CreateTaskCommand = (function (_super) {
(0, tslib_1.__extends)(CreateTaskCommand, _super);
function CreateTaskCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
CreateTaskCommand.prototype.execute = function (data) {
return _super.prototype.execute.call(this, data);
};
CreateTaskCommand.prototype.executeInternal = function (data) {
var _a, _b;
data !== null && data !== void 0 ? data : (data = {});
if (!data.parentId) {
var item = this.control.viewModel.findItem(this.control.currentSelectedTaskID);
var selectedTask = item && item.task;
if (selectedTask)
data.parentId = selectedTask.parentId;
}
var referenceItem = this.control.viewModel.findItem(data.parentId) || this.control.viewModel.items[0];
var referenceTask = referenceItem && referenceItem.task;
if (!data.start)
data.start = referenceTask ? new Date(referenceTask.start.getTime()) : new Date(this.control.range.start.getTime());
if (!data.end)
data.end = referenceTask ? new Date(referenceTask.end.getTime()) : new Date(this.control.range.end.getTime());
(_a = data.title) !== null && _a !== void 0 ? _a : (data.title = "New task");
(_b = data.progress) !== null && _b !== void 0 ? _b : (data.progress = 0);
var args = new TaskInsertingArguments_1.TaskInsertingArguments(null, data);
this.modelManipulator.dispatcher.notifyTaskCreating(args);
if (!args.cancel) {
this.history.addAndRedo(new CreateTaskHistoryItem_1.CreateTaskHistoryItem(this.modelManipulator, args));
var parentItem = this.control.viewModel.findItem(data.parentId);
_super.prototype.updateParent.call(this, parentItem);
}
return !args.cancel;
};
CreateTaskCommand.prototype.getState = function () {
var state = _super.prototype.getState.call(this);
state.visible = state.visible && this.control.settings.editing.allowTaskInsert;
return state;
};
return CreateTaskCommand;
}(TaskCommandBase_1.TaskCommandBase));
exports.CreateTaskCommand = CreateTaskCommand;
/***/ }),
/* 128 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RemoveTaskCommand = void 0;
var tslib_1 = __webpack_require__(0);
var DialogEnums_1 = __webpack_require__(32);
var ConfirmationDialogParameters_1 = __webpack_require__(43);
var TaskRemovingArguments_1 = __webpack_require__(129);
var RemoveDependencyHistoryItem_1 = __webpack_require__(31);
var DeassignResourceHistoryItem_1 = __webpack_require__(34);
var RemoveTaskHistoryItem_1 = __webpack_require__(130);
var TaskCommandBase_1 = __webpack_require__(25);
var RemoveTaskCommand = (function (_super) {
(0, tslib_1.__extends)(RemoveTaskCommand, _super);
function RemoveTaskCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
RemoveTaskCommand.prototype.execute = function (id, confirmRequired, isApiCall, isUpdateParentTaskRequired, historyItem) {
var _this = this;
if (confirmRequired === void 0) { confirmRequired = true; }
if (isApiCall === void 0) { isApiCall = false; }
if (isUpdateParentTaskRequired === void 0) { isUpdateParentTaskRequired = true; }
this.isApiCall = isApiCall;
this.isUpdateParentTaskRequired = isUpdateParentTaskRequired;
if (confirmRequired) {
this.control.commandManager.showConfirmationDialog.execute(new ConfirmationDialogParameters_1.ConfirmationDialogParameters(DialogEnums_1.ConfirmationType.TaskDelete, function () { _this.executeInternal(id, historyItem); }));
return false;
}
return _super.prototype.execute.call(this, id, historyItem);
};
RemoveTaskCommand.prototype.executeInternal = function (id, historyItem) {
var _this = this;
id = id || this.control.currentSelectedTaskID;
var item = this.control.viewModel.findItem(id);
var task = item ? item.task : this.control.viewModel.tasks.getItemById(id);
var args = new TaskRemovingArguments_1.TaskRemovingArguments(task);
this.modelManipulator.dispatcher.notifyTaskRemoving(args);
if (args.cancel)
return false;
this.control.history.beginTransaction();
this.control.viewModel.beginUpdate();
var removeTaskHistoryItem = historyItem || new RemoveTaskHistoryItem_1.RemoveTaskHistoryItem(this.modelManipulator);
removeTaskHistoryItem.addTask(id);
var childTasks = this.control.viewModel.tasks.items.filter(function (t) { return t.parentId === id; });
childTasks.forEach(function (t) { return new RemoveTaskCommand(_this.control).execute(t.internalId, false, true, false, removeTaskHistoryItem); });
var dependencies = this.control.viewModel.dependencies.items.filter(function (d) { return d.predecessorId === id || d.successorId === id; });
if (dependencies.length)
if (this.control.settings.editing.allowDependencyDelete) {
dependencies = dependencies.filter(function (d) { return childTasks.filter(function (c) { return c.internalId === d.predecessorId || c.internalId === d.successorId; }).length === 0; });
dependencies.forEach(function (d) { return removeTaskHistoryItem.add(new RemoveDependencyHistoryItem_1.RemoveDependencyHistoryItem(_this.modelManipulator, d.internalId)); });
}
else
return false;
var assignments = this.control.viewModel.assignments.items.filter(function (a) { return a.taskId === id; });
assignments.forEach(function (a) {
if (_this.modelManipulator.dispatcher.fireResourceUnassigning(a))
removeTaskHistoryItem.add(new DeassignResourceHistoryItem_1.DeassignResourceHistoryItem(_this.modelManipulator, a.internalId));
});
if (!historyItem)
this.history.addAndRedo(removeTaskHistoryItem);
var parent = this.control.viewModel.findItem(task.parentId);
if (this.isUpdateParentTaskRequired)
_super.prototype.updateParent.call(this, parent);
this.control.history.endTransaction();
this.control.viewModel.endUpdate();
return true;
};
RemoveTaskCommand.prototype.isEnabled = function () {
var gantt = this.control;
var selectedItem = gantt.viewModel.findItem(gantt.currentSelectedTaskID);
var result = _super.prototype.isEnabled.call(this) && (!!selectedItem && selectedItem.selected || this.isApiCall);
return result;
};
RemoveTaskCommand.prototype.getState = function () {
var state = _super.prototype.getState.call(this);
var gantt = this.control;
state.visible = state.visible && gantt.settings.editing.allowTaskDelete;
return state;
};
return RemoveTaskCommand;
}(TaskCommandBase_1.TaskCommandBase));
exports.RemoveTaskCommand = RemoveTaskCommand;
/***/ }),
/* 129 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskRemovingArguments = void 0;
var tslib_1 = __webpack_require__(0);
var BaseArguments_1 = __webpack_require__(9);
var TaskRemovingArguments = (function (_super) {
(0, tslib_1.__extends)(TaskRemovingArguments, _super);
function TaskRemovingArguments(task) {
var _this = _super.call(this, task.id) || this;
_this.values = task;
return _this;
}
return TaskRemovingArguments;
}(BaseArguments_1.BaseArguments));
exports.TaskRemovingArguments = TaskRemovingArguments;
/***/ }),
/* 130 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RemoveTaskHistoryItem = void 0;
var tslib_1 = __webpack_require__(0);
var CompositionHistoryItem_1 = __webpack_require__(45);
var RemoveDependencyHistoryItem_1 = __webpack_require__(31);
var RemoveTaskHistoryItem = (function (_super) {
(0, tslib_1.__extends)(RemoveTaskHistoryItem, _super);
function RemoveTaskHistoryItem(modelManipulator) {
var _this = _super.call(this) || this;
_this.taskIds = [];
_this.tasks = [];
_this.pendingCallbacks = 0;
_this.modelManipulator = modelManipulator;
return _this;
}
RemoveTaskHistoryItem.prototype.redo = function () {
var _this = this;
_super.prototype.redo.call(this);
this.taskIds.forEach(function (id) {
_this.tasks.push(_this.modelManipulator.task.remove(id));
});
};
RemoveTaskHistoryItem.prototype.undo = function () {
var _this = this;
var viewModel = this.modelManipulator.task.viewModel;
viewModel.lockChangesProcessing = this.tasks.length > 0;
if (this.tasks.length) {
var task_1 = this.tasks.shift();
this.pendingCallbacks++;
this.modelManipulator.task.create(task_1, task_1.internalId, function () {
_this.modelManipulator.task.properties.progress.setValue(task_1.internalId, task_1.progress);
if (task_1.color)
_this.modelManipulator.task.properties.color.setValue(task_1.internalId, task_1.color);
_this.tasks.length ? _this.undo() : _super.prototype.undo.call(_this);
_this.pendingCallbacks--;
viewModel.lockChangesProcessing = _this.pendingCallbacks > 0;
});
}
};
RemoveTaskHistoryItem.prototype.undoItemsQuery = function () {
while (this.tasks.length) {
var task = this.tasks.shift();
this.modelManipulator.task.create(task, task.internalId, function () { });
this.modelManipulator.task.properties.progress.setValue(task.internalId, task.progress);
if (task.color)
this.modelManipulator.task.properties.color.setValue(task.internalId, task.color);
}
this.modelManipulator.task.viewModel.lockChangesProcessing = false;
this.pendingCallbacks = 0;
_super.prototype.undo.call(this);
};
RemoveTaskHistoryItem.prototype.addTask = function (taskId) {
this.taskIds.push(taskId);
};
RemoveTaskHistoryItem.prototype.add = function (historyItem) {
if (historyItem instanceof RemoveDependencyHistoryItem_1.RemoveDependencyHistoryItem) {
var item_1 = historyItem;
if (!this.historyItems.filter(function (i) { return i instanceof RemoveDependencyHistoryItem_1.RemoveDependencyHistoryItem && i.dependencyId == item_1.dependencyId; }).length)
this.historyItems.push(item_1);
}
else
_super.prototype.add.call(this, historyItem);
};
return RemoveTaskHistoryItem;
}(CompositionHistoryItem_1.CompositionHistoryItem));
exports.RemoveTaskHistoryItem = RemoveTaskHistoryItem;
/***/ }),
/* 131 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskAddContextItemCommand = void 0;
var tslib_1 = __webpack_require__(0);
var TaskCommandBase_1 = __webpack_require__(25);
var TaskAddContextItemCommand = (function (_super) {
(0, tslib_1.__extends)(TaskAddContextItemCommand, _super);
function TaskAddContextItemCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskAddContextItemCommand.prototype.getState = function () {
var state = _super.prototype.getState.call(this);
state.visible = state.visible && this.control.settings.editing.allowTaskInsert;
return state;
};
TaskAddContextItemCommand.prototype.execute = function () {
return false;
};
return TaskAddContextItemCommand;
}(TaskCommandBase_1.TaskCommandBase));
exports.TaskAddContextItemCommand = TaskAddContextItemCommand;
/***/ }),
/* 132 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskColorCommand = void 0;
var tslib_1 = __webpack_require__(0);
var TaskColorHistoryItem_1 = __webpack_require__(64);
var TaskPropertyCommandBase_1 = __webpack_require__(26);
var TaskColorCommand = (function (_super) {
(0, tslib_1.__extends)(TaskColorCommand, _super);
function TaskColorCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskColorCommand.prototype.execute = function (id, value) {
return _super.prototype.execute.call(this, id, value);
};
TaskColorCommand.prototype.executeInternal = function (id, value) {
var _this = this;
return this.modelManipulator.dispatcher.raiseTaskColorUpdating(this.getTask(id), value, function (newValue) { _this.history.addAndRedo(new TaskColorHistoryItem_1.TaskColorHistoryItem(_this.modelManipulator, id, newValue)); });
};
return TaskColorCommand;
}(TaskPropertyCommandBase_1.TaskPropertyCommandBase));
exports.TaskColorCommand = TaskColorCommand;
/***/ }),
/* 133 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskDescriptionCommand = void 0;
var tslib_1 = __webpack_require__(0);
var TaskDescriptionHistoryItem_1 = __webpack_require__(134);
var TaskPropertyCommandBase_1 = __webpack_require__(26);
var TaskDescriptionCommand = (function (_super) {
(0, tslib_1.__extends)(TaskDescriptionCommand, _super);
function TaskDescriptionCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskDescriptionCommand.prototype.execute = function (id, value) {
return _super.prototype.execute.call(this, id, value);
};
TaskDescriptionCommand.prototype.executeInternal = function (id, value) {
var _this = this;
return this.modelManipulator.dispatcher.raiseTaskDescriptionUpdating(this.getTask(id), value, function (newDescription) { _this.history.addAndRedo(new TaskDescriptionHistoryItem_1.TaskDescriptionHistoryItem(_this.modelManipulator, id, newDescription)); });
};
return TaskDescriptionCommand;
}(TaskPropertyCommandBase_1.TaskPropertyCommandBase));
exports.TaskDescriptionCommand = TaskDescriptionCommand;
/***/ }),
/* 134 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskDescriptionHistoryItem = void 0;
var tslib_1 = __webpack_require__(0);
var TaskPropertiesHistoryItemBase_1 = __webpack_require__(15);
var TaskDescriptionHistoryItem = (function (_super) {
(0, tslib_1.__extends)(TaskDescriptionHistoryItem, _super);
function TaskDescriptionHistoryItem() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskDescriptionHistoryItem.prototype.getPropertiesManipulator = function () {
return this.modelManipulator.task.properties.description;
};
return TaskDescriptionHistoryItem;
}(TaskPropertiesHistoryItemBase_1.TaskPropertiesHistoryItemBase));
exports.TaskDescriptionHistoryItem = TaskDescriptionHistoryItem;
/***/ }),
/* 135 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskEndCommand = void 0;
var tslib_1 = __webpack_require__(0);
var TaskEndHistoryItem_1 = __webpack_require__(35);
var TaskPropertyCommandValidation_1 = __webpack_require__(47);
var TaskEndCommand = (function (_super) {
(0, tslib_1.__extends)(TaskEndCommand, _super);
function TaskEndCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskEndCommand.prototype.execute = function (id, value) {
var success = this.modelManipulator.dispatcher.raiseTaskEndUpdating(this.getTask(id), value, function (newStart) { value = newStart; });
return success && _super.prototype.execute.call(this, id, value);
};
TaskEndCommand.prototype.executeInternal = function (id, value) {
return _super.prototype.executeInternal.call(this, id, value);
};
TaskEndCommand.prototype.executeCore = function (id, value) {
var oldEnd = this.control.viewModel.tasks.getItemById(id).end;
if (oldEnd.getTime() === value.getTime())
return false;
this.control.history.beginTransaction();
this.history.addAndRedo(new TaskEndHistoryItem_1.TaskEndHistoryItem(this.modelManipulator, id, value));
if (this.control.isValidateDependenciesRequired())
this.control.validationController.moveEndDependTasks(id, oldEnd);
this.validationController.updateParentsIfRequired(id);
this.control.history.endTransaction();
var maxEndTask = this.control.viewModel.tasks.items.reduce(function (prev, curr) {
if (!curr.isValid())
return prev;
return prev.end.getTime() > curr.end.getTime() ? prev : curr;
});
if (maxEndTask.end > this.control.dataRange.end) {
this.control.dataRange.end = maxEndTask.end;
this.control.resetAndUpdate();
}
return true;
};
TaskEndCommand.prototype.validate = function (id, value) {
return this.control.validationController.checkEndDependencies(id, value);
};
return TaskEndCommand;
}(TaskPropertyCommandValidation_1.TaskPropertyCommandValidation));
exports.TaskEndCommand = TaskEndCommand;
/***/ }),
/* 136 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConstraintViolationDialogParameters = void 0;
var tslib_1 = __webpack_require__(0);
var DialogParametersBase_1 = __webpack_require__(33);
var ConstraintViolationDialogParameters = (function (_super) {
(0, tslib_1.__extends)(ConstraintViolationDialogParameters, _super);
function ConstraintViolationDialogParameters(validationError, callback) {
var _this = _super.call(this) || this;
_this.validationError = validationError;
_this.callback = callback;
return _this;
}
ConstraintViolationDialogParameters.prototype.clone = function () {
var result = new ConstraintViolationDialogParameters(this.validationError, this.callback);
result.option = this.option;
return result;
};
return ConstraintViolationDialogParameters;
}(DialogParametersBase_1.DialogParametersBase));
exports.ConstraintViolationDialogParameters = ConstraintViolationDialogParameters;
/***/ }),
/* 137 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskMoveCommand = void 0;
var tslib_1 = __webpack_require__(0);
var TaskMoveHistoryItem_1 = __webpack_require__(65);
var DateRange_1 = __webpack_require__(14);
var TaskPropertyCommandValidation_1 = __webpack_require__(47);
var TaskMoveCommand = (function (_super) {
(0, tslib_1.__extends)(TaskMoveCommand, _super);
function TaskMoveCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskMoveCommand.prototype.execute = function (id, start, end) {
var success = this.modelManipulator.dispatcher.raiseTaskStartAndEndUpdating(this.getTask(id), start, end, function (newStart, newEnd) {
start = newStart;
end = newEnd;
});
return success && _super.prototype.execute.call(this, id, start, end);
};
TaskMoveCommand.prototype.executeInternal = function (id, start, end) {
return _super.prototype.executeInternal.call(this, id, start, end);
};
TaskMoveCommand.prototype.executeCore = function (id, start, end) {
var task = this.control.viewModel.tasks.getItemById(id);
var oldDateRange = new DateRange_1.DateRange(new Date(task.start.getTime()), new Date(task.end.getTime()));
this.control.history.beginTransaction();
this.history.addAndRedo(new TaskMoveHistoryItem_1.TaskMoveHistoryItem(this.modelManipulator, id, new DateRange_1.DateRange(start, end)));
this.validationController.correctParentsOnChildMoving(id, start.getTime() - oldDateRange.start.getTime());
this.validationController.updateParentsIfRequired(id);
if (this.control.isValidateDependenciesRequired()) {
this.control.validationController.moveStartDependTasks(id, oldDateRange.start);
this.control.validationController.moveEndDependTasks(id, oldDateRange.end);
}
this.control.history.endTransaction();
var maxEndTask = this.control.viewModel.tasks.items.reduce(function (prev, curr) {
if (!curr.isValid())
return prev;
return prev.end.getTime() > curr.end.getTime() ? prev : curr;
});
if (maxEndTask.end > this.control.dataRange.end) {
this.control.dataRange.end = maxEndTask.end;
this.control.resetAndUpdate();
}
var minStartTask = this.control.viewModel.tasks.items.reduce(function (prev, curr) {
if (!curr.isValid())
return prev;
if (!prev.isValid())
return curr;
return prev.start.getTime() < curr.start.getTime() ? prev : curr;
});
if (minStartTask.start < this.control.dataRange.start) {
this.control.dataRange.start = minStartTask.start;
this.control.resetAndUpdate();
}
return true;
};
TaskMoveCommand.prototype.validate = function (id, start, end) {
var startErrors = this.control.validationController.checkStartDependencies(id, start);
var endErrors = this.control.validationController.checkEndDependencies(id, end);
return (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], startErrors, true), endErrors, true);
};
return TaskMoveCommand;
}(TaskPropertyCommandValidation_1.TaskPropertyCommandValidation));
exports.TaskMoveCommand = TaskMoveCommand;
/***/ }),
/* 138 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskProgressCommand = void 0;
var tslib_1 = __webpack_require__(0);
var TaskProgressHistoryItem_1 = __webpack_require__(36);
var TaskPropertyCommandBase_1 = __webpack_require__(26);
var TaskProgressCommand = (function (_super) {
(0, tslib_1.__extends)(TaskProgressCommand, _super);
function TaskProgressCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskProgressCommand.prototype.execute = function (id, value) {
return _super.prototype.execute.call(this, id, value);
};
TaskProgressCommand.prototype.executeInternal = function (id, value) {
var _this = this;
return this.modelManipulator.dispatcher.raiseTaskProgressUpdating(this.getTask(id), value, function (newValue) {
_this.control.history.beginTransaction();
_this.history.addAndRedo(new TaskProgressHistoryItem_1.TaskProgressHistoryItem(_this.modelManipulator, id, newValue));
_this.validationController.updateParentsIfRequired(id);
_this.control.history.endTransaction();
});
};
return TaskProgressCommand;
}(TaskPropertyCommandBase_1.TaskPropertyCommandBase));
exports.TaskProgressCommand = TaskProgressCommand;
/***/ }),
/* 139 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskStartCommand = void 0;
var tslib_1 = __webpack_require__(0);
var TaskStartHistoryItem_1 = __webpack_require__(37);
var TaskPropertyCommandValidation_1 = __webpack_require__(47);
var TaskStartCommand = (function (_super) {
(0, tslib_1.__extends)(TaskStartCommand, _super);
function TaskStartCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskStartCommand.prototype.execute = function (id, value) {
var success = this.modelManipulator.dispatcher.raiseTaskStartUpdating(this.getTask(id), value, function (newStart) { value = newStart; });
return success && _super.prototype.execute.call(this, id, value);
};
TaskStartCommand.prototype.executeInternal = function (id, value) {
return _super.prototype.executeInternal.call(this, id, value);
};
TaskStartCommand.prototype.executeCore = function (id, value) {
var oldStart = this.control.viewModel.tasks.getItemById(id).start;
if (oldStart.getTime() === value.getTime())
return false;
this.control.history.beginTransaction();
this.history.addAndRedo(new TaskStartHistoryItem_1.TaskStartHistoryItem(this.modelManipulator, id, value));
if (this.control.isValidateDependenciesRequired())
this.control.validationController.moveStartDependTasks(id, oldStart);
this.validationController.updateParentsIfRequired(id);
this.control.history.endTransaction();
var minStartTask = this.control.viewModel.tasks.items.reduce(function (prev, curr) {
if (!curr.isValid())
return prev;
if (!prev.isValid())
return curr;
return prev.start.getTime() < curr.start.getTime() ? prev : curr;
});
if (minStartTask.start < this.control.dataRange.start) {
this.control.dataRange.start = minStartTask.start;
this.control.resetAndUpdate();
}
return true;
};
TaskStartCommand.prototype.validate = function (id, value) {
return this.control.validationController.checkStartDependencies(id, value);
};
return TaskStartCommand;
}(TaskPropertyCommandValidation_1.TaskPropertyCommandValidation));
exports.TaskStartCommand = TaskStartCommand;
/***/ }),
/* 140 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskTitleCommand = void 0;
var tslib_1 = __webpack_require__(0);
var TaskTitleHistoryItem_1 = __webpack_require__(44);
var TaskPropertyCommandBase_1 = __webpack_require__(26);
var TaskTitleCommand = (function (_super) {
(0, tslib_1.__extends)(TaskTitleCommand, _super);
function TaskTitleCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskTitleCommand.prototype.execute = function (id, value) {
return _super.prototype.execute.call(this, id, value);
};
TaskTitleCommand.prototype.executeInternal = function (id, value) {
var _this = this;
return this.modelManipulator.dispatcher.raiseTaskTitleUpdating(this.getTask(id), value, function (newTitle) { _this.history.addAndRedo(new TaskTitleHistoryItem_1.TaskTitleHistoryItem(_this.modelManipulator, id, newTitle)); });
};
return TaskTitleCommand;
}(TaskPropertyCommandBase_1.TaskPropertyCommandBase));
exports.TaskTitleCommand = TaskTitleCommand;
/***/ }),
/* 141 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UpdateTaskCommand = void 0;
var tslib_1 = __webpack_require__(0);
var common_1 = __webpack_require__(1);
var TaskColorHistoryItem_1 = __webpack_require__(64);
var TaskEndHistoryItem_1 = __webpack_require__(35);
var TaskProgressHistoryItem_1 = __webpack_require__(36);
var TaskStartHistoryItem_1 = __webpack_require__(37);
var TaskTitleHistoryItem_1 = __webpack_require__(44);
var TaskCommandBase_1 = __webpack_require__(25);
var UpdateTaskCommand = (function (_super) {
(0, tslib_1.__extends)(UpdateTaskCommand, _super);
function UpdateTaskCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
UpdateTaskCommand.prototype.execute = function (id, newValues) {
return _super.prototype.execute.call(this, id, newValues);
};
UpdateTaskCommand.prototype.executeInternal = function (id, newValues) {
var task = this.control.viewModel.tasks.getItemById(id);
if (!task)
return false;
var success = this.control.modelManipulator.dispatcher.raiseTaskMultipleUpdating(task, newValues, function (changedNewValues) {
newValues.title = changedNewValues.title;
newValues.progress = changedNewValues.progress;
newValues.start = changedNewValues.start;
newValues.end = changedNewValues.end;
newValues.color = changedNewValues.color;
});
if (success) {
this.history.beginTransaction();
var needRecalculateParents = false;
if ((0, common_1.isDefined)(newValues.title) && newValues.title !== task.title)
this.history.addAndRedo(new TaskTitleHistoryItem_1.TaskTitleHistoryItem(this.modelManipulator, id, newValues.title));
if ((0, common_1.isDefined)(newValues.progress) && newValues.progress !== task.progress) {
this.history.addAndRedo(new TaskProgressHistoryItem_1.TaskProgressHistoryItem(this.modelManipulator, id, newValues.progress));
needRecalculateParents = true;
}
if ((0, common_1.isDefined)(newValues.start) && (0, common_1.isDefined)(newValues.end) && newValues.end.getTime() < newValues.start.getTime())
newValues.end = newValues.start;
if ((0, common_1.isDefined)(newValues.start) && newValues.start !== task.start) {
this.history.addAndRedo(new TaskStartHistoryItem_1.TaskStartHistoryItem(this.modelManipulator, id, newValues.start));
needRecalculateParents = true;
if (this.control.isValidateDependenciesRequired())
this.control.validationController.moveStartDependTasks(id, task.start);
}
if ((0, common_1.isDefined)(newValues.end) && newValues.end !== task.end) {
this.history.addAndRedo(new TaskEndHistoryItem_1.TaskEndHistoryItem(this.modelManipulator, id, newValues.end));
needRecalculateParents = true;
if (this.control.isValidateDependenciesRequired())
this.control.validationController.moveEndDependTasks(id, task.end);
}
if ((0, common_1.isDefined)(newValues.color) && newValues.color !== task.color)
this.history.addAndRedo(new TaskColorHistoryItem_1.TaskColorHistoryItem(this.modelManipulator, id, newValues.color));
if (needRecalculateParents)
this.validationController.updateParentsIfRequired(id);
else
this.control.updateOwnerInAutoParentMode();
this.history.endTransaction();
}
return success;
};
UpdateTaskCommand.prototype.isEnabled = function () {
return _super.prototype.isEnabled.call(this) && this.control.settings.editing.allowTaskUpdate;
};
return UpdateTaskCommand;
}(TaskCommandBase_1.TaskCommandBase));
exports.UpdateTaskCommand = UpdateTaskCommand;
/***/ }),
/* 142 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZoomInCommand = void 0;
var tslib_1 = __webpack_require__(0);
var CommandBase_1 = __webpack_require__(5);
var SimpleCommandState_1 = __webpack_require__(6);
var ZoomInCommand = (function (_super) {
(0, tslib_1.__extends)(ZoomInCommand, _super);
function ZoomInCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
ZoomInCommand.prototype.getState = function () {
return new SimpleCommandState_1.SimpleCommandState(true);
};
ZoomInCommand.prototype.execute = function () {
return _super.prototype.execute.call(this);
};
ZoomInCommand.prototype.executeInternal = function () {
this.control.zoomIn();
return true;
};
return ZoomInCommand;
}(CommandBase_1.CommandBase));
exports.ZoomInCommand = ZoomInCommand;
/***/ }),
/* 143 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZoomOutCommand = void 0;
var tslib_1 = __webpack_require__(0);
var CommandBase_1 = __webpack_require__(5);
var SimpleCommandState_1 = __webpack_require__(6);
var ZoomOutCommand = (function (_super) {
(0, tslib_1.__extends)(ZoomOutCommand, _super);
function ZoomOutCommand() {
return _super !== null && _super.apply(this, arguments) || this;
}
ZoomOutCommand.prototype.getState = function () {
return new SimpleCommandState_1.SimpleCommandState(true);
};
ZoomOutCommand.prototype.execute = function () {
return _super.prototype.execute.call(this);
};
ZoomOutCommand.prototype.executeInternal = function () {
this.control.zoomOut();
return true;
};
return ZoomOutCommand;
}(CommandBase_1.CommandBase));
exports.ZoomOutCommand = ZoomOutCommand;
/***/ }),
/* 144 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventManager = void 0;
var MouseHandler_1 = __webpack_require__(145);
var key_1 = __webpack_require__(155);
var browser_1 = __webpack_require__(8);
var TouchHandler_1 = __webpack_require__(157);
var EventManager = (function () {
function EventManager(settings) {
this.settings = settings;
this.mouseHandler = new MouseHandler_1.MouseHandler(settings);
this.touchHandler = new TouchHandler_1.TouchHandler(settings);
}
Object.defineProperty(EventManager.prototype, "isFocus", {
get: function () {
return this.settings.isFocus();
},
enumerable: false,
configurable: true
});
Object.defineProperty(EventManager.prototype, "history", {
get: function () {
return this.settings.getHistory();
},
enumerable: false,
configurable: true
});
EventManager.prototype.deleteSelectedDependency = function () {
this.settings.getTaskEditController().deleteSelectedDependency();
};
EventManager.prototype.onMouseDown = function (evt) {
this.mouseHandler.onMouseDown(evt);
};
EventManager.prototype.onMouseMove = function (evt) {
this.mouseHandler.onMouseMove(evt);
};
EventManager.prototype.onMouseUp = function (evt) {
this.mouseHandler.onMouseUp(evt);
};
EventManager.prototype.onMouseDblClick = function (evt) {
this.mouseHandler.onMouseDoubleClick(evt);
};
EventManager.prototype.onMouseWheel = function (evt) {
this.mouseHandler.onMouseWheel(evt);
};
EventManager.prototype.onTouchStart = function (evt) {
this.touchHandler.onTouchStart(evt);
};
EventManager.prototype.onTouchEnd = function (evt) {
this.touchHandler.onTouchEnd(evt);
};
EventManager.prototype.onTouchMove = function (evt) {
this.touchHandler.onTouchMove(evt);
};
EventManager.prototype.onDoubleTap = function (evt) {
this.touchHandler.onDoubleTap(evt);
};
EventManager.prototype.onKeyDown = function (evt) {
if (this.isFocus) {
var code = this.getShortcutCode(evt);
if (code == (key_1.ModifierKey.Ctrl | key_1.KeyCode.Key_z))
this.history.undo();
if (code == (key_1.ModifierKey.Ctrl | key_1.KeyCode.Key_y))
this.history.redo();
if (code == key_1.KeyCode.Delete)
this.deleteSelectedDependency();
}
};
EventManager.prototype.getShortcutCode = function (evt) {
var keyCode = key_1.KeyUtils.getEventKeyCode(evt);
var modifiers = 0;
if (evt.altKey)
modifiers |= key_1.ModifierKey.Alt;
if (evt.ctrlKey)
modifiers |= key_1.ModifierKey.Ctrl;
if (evt.shiftKey)
modifiers |= key_1.ModifierKey.Shift;
if (evt.metaKey && browser_1.Browser.MacOSPlatform)
modifiers |= key_1.ModifierKey.Meta;
return modifiers | keyCode;
};
return EventManager;
}());
exports.EventManager = EventManager;
/***/ }),
/* 145 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MouseHandler = void 0;
var tslib_1 = __webpack_require__(0);
var HandlerBase_1 = __webpack_require__(69);
var MouseHandlerDefaultState_1 = __webpack_require__(147);
var evt_1 = __webpack_require__(10);
var MouseHandlerMoveTaskState_1 = __webpack_require__(152);
var MouseHandlerProgressTaskState_1 = __webpack_require__(153);
var MouseHandlerTimestampTaskState_1 = __webpack_require__(154);
var MouseHandlerDependencyState_1 = __webpack_require__(74);
var Enums_1 = __webpack_require__(2);
var MouseHandler = (function (_super) {
(0, tslib_1.__extends)(MouseHandler, _super);
function MouseHandler() {
return _super !== null && _super.apply(this, arguments) || this;
}
MouseHandler.prototype.onMouseDoubleClick = function (evt) {
this.state.onMouseDoubleClick(evt);
};
MouseHandler.prototype.onMouseDown = function (evt) {
var source = this.getEventSource(evt_1.EvtUtils.getEventSource(evt));
switch (source) {
case Enums_1.MouseEventSource.TaskEdit_Frame:
this.switchState(new MouseHandlerMoveTaskState_1.MouseHandlerMoveTaskState(this));
break;
case Enums_1.MouseEventSource.TaskEdit_Progress:
this.switchState(new MouseHandlerProgressTaskState_1.MouseHandlerProgressTaskState(this));
break;
case Enums_1.MouseEventSource.TaskEdit_Start:
case Enums_1.MouseEventSource.TaskEdit_End:
this.switchState(new MouseHandlerTimestampTaskState_1.MouseHandlerTimestampTaskState(this));
break;
case Enums_1.MouseEventSource.TaskEdit_DependencyStart:
case Enums_1.MouseEventSource.TaskEdit_DependencyFinish:
this.switchState(new MouseHandlerDependencyState_1.MouseHandlerDependencyState(this));
break;
}
this.state.onMouseDown(evt);
};
MouseHandler.prototype.onMouseUp = function (evt) {
this.state.onMouseUp(evt);
};
MouseHandler.prototype.onMouseMove = function (evt) {
this.state.onMouseMove(evt);
};
MouseHandler.prototype.onMouseWheel = function (evt) {
this.state.onMouseWheel(evt);
};
MouseHandler.prototype.switchToDefaultState = function () {
this.state = new MouseHandlerDefaultState_1.MouseHandlerDefaultState(this);
};
return MouseHandler;
}(HandlerBase_1.HandlerBase));
exports.MouseHandler = MouseHandler;
/***/ }),
/* 146 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskEditTooltip = void 0;
var dom_1 = __webpack_require__(3);
var TaskEditTooltip = (function () {
function TaskEditTooltip(parentElement, tooltipSettings, cultureInfo) {
this.parentElement = parentElement;
this.cultureInfo = cultureInfo;
this.tooltipSettings = tooltipSettings;
}
Object.defineProperty(TaskEditTooltip.prototype, "baseElement", {
get: function () {
if (!this._baseElement)
this.createTooltipContainer();
return this._baseElement;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskEditTooltip.prototype, "headerHeight", {
get: function () {
return this.tooltipSettings.getHeaderHeight;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskEditTooltip.prototype, "taskTooltipContentTemplate", {
get: function () {
return this.tooltipSettings.getTaskTooltipContentTemplate;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskEditTooltip.prototype, "taskProgressTooltipContentTemplate", {
get: function () {
return this.tooltipSettings.getTaskProgressTooltipContentTemplate;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskEditTooltip.prototype, "taskTimeTooltipContentTemplate", {
get: function () {
return this.tooltipSettings.getTaskTimeTooltipContentTemplate;
},
enumerable: false,
configurable: true
});
TaskEditTooltip.prototype.destroyTemplate = function (container) {
this.tooltipSettings.destroyTemplate(container);
};
TaskEditTooltip.prototype.formatDate = function (date) {
return this.tooltipSettings.formatDate(date);
};
TaskEditTooltip.prototype.createTooltipContainer = function () {
this._baseElement = document.createElement("DIV");
this._baseElement.className = TaskEditTooltip.CLASSNAMES.TASK_EDIT_PROGRESS_STATUS;
this.parentElement.appendChild(this._baseElement);
};
TaskEditTooltip.prototype.setDefaultTooltip = function (task) {
this.defaultTooltip = document.createElement("DIV");
this.defaultTooltip.className = TaskEditTooltip.CLASSNAMES.TASK_EDIT_TOOLTIP_DEFAULT;
var titleWrapper = document.createElement("DIV");
titleWrapper.className = TaskEditTooltip.CLASSNAMES.TASK_EDIT_TASK_TITLE;
var title = document.createElement("SPAN");
titleWrapper.appendChild(title);
this.defaultTooltip.appendChild(titleWrapper);
title.innerText = task.title;
this.defaultTooltip.appendChild(this.getTimeContent(task.start, task.end));
if (!isNaN(task.progress)) {
var progressElement = document.createElement("DIV");
progressElement.className = TaskEditTooltip.CLASSNAMES.TASK_EDIT_PROGRESS_STATUS_TIME;
var progressTitle = document.createElement("SPAN");
var progressValue = document.createElement("SPAN");
progressElement.appendChild(progressTitle);
progressElement.appendChild(progressValue);
this.defaultTooltip.appendChild(progressElement);
progressTitle.innerText = (this.cultureInfo.progress ? this.cultureInfo.progress : "Progress") + ": ";
progressValue.innerText = task.progress + "%";
}
this.baseElement.appendChild(this.defaultTooltip);
};
TaskEditTooltip.prototype.setDefaultProgressTooltip = function (progress) {
this.defaultTooltip = document.createElement("DIV");
this.defaultTooltip.className = TaskEditTooltip.CLASSNAMES.TASK_EDIT_TOOLTIP_DEFAULT;
this.defaultTooltip.innerText = progress + "%";
this.baseElement.appendChild(this.defaultTooltip);
};
TaskEditTooltip.prototype.setDefaultTimeTooltip = function (start, end) {
this.defaultTooltip = document.createElement("DIV");
this.defaultTooltip.className = TaskEditTooltip.CLASSNAMES.TASK_EDIT_TOOLTIP_DEFAULT;
this.defaultTooltip.appendChild(this.getTimeContent(start, end));
this.baseElement.appendChild(this.defaultTooltip);
};
TaskEditTooltip.prototype.showInfo = function (task, posX, delay) {
var _this = this;
if (delay === void 0) { delay = 0; }
var tooltipTemplateFunction = this.taskTooltipContentTemplate;
this.destroyTemplate(this.baseElement);
if (tooltipTemplateFunction)
tooltipTemplateFunction(this.baseElement, task, function () { _this.showTooltip(posX, false, delay); });
else {
this.setDefaultTooltip(task);
this.showTooltip(posX, false, delay);
}
};
TaskEditTooltip.prototype.showProgress = function (progress, posX) {
var _this = this;
var tooltipTemplateFunction = this.taskProgressTooltipContentTemplate;
this.destroyTemplate(this.baseElement);
if (tooltipTemplateFunction)
tooltipTemplateFunction(this.baseElement, { progress: progress }, function () { _this.showTooltip(posX); });
else {
this.setDefaultProgressTooltip(progress);
this.show(posX);
}
};
TaskEditTooltip.prototype.showTime = function (start, end, posX) {
var _this = this;
var tooltipTemplateFunction = this.taskTimeTooltipContentTemplate;
this.destroyTemplate(this.baseElement);
if (tooltipTemplateFunction)
tooltipTemplateFunction(this.baseElement, { start: start, end: end }, function () { _this.showTooltip(posX); });
else {
this.setDefaultTimeTooltip(start, end);
this.show(posX);
}
};
TaskEditTooltip.prototype.showTooltip = function (posX, autoHide, delay) {
var _this = this;
var _a;
if (autoHide === void 0) { autoHide = true; }
if (delay === void 0) { delay = 0; }
if ((_a = this.baseElement) === null || _a === void 0 ? void 0 : _a.innerHTML) {
var showInfoFunc = function () {
_this.show(posX, autoHide);
};
if (delay)
this.timerId = setTimeout(showInfoFunc, delay);
else
showInfoFunc();
}
};
TaskEditTooltip.prototype.show = function (posX, autoHide) {
var _this = this;
var _a, _b, _c, _d;
if (autoHide === void 0) { autoHide = true; }
var arrowHeight = 5;
var heightOffset = 15;
(_a = this.defaultTooltip) === null || _a === void 0 ? void 0 : _a.classList.remove(TaskEditTooltip.CLASSNAMES.TASK_EDIT_TOOLTIP_ARROW_AFTER);
(_b = this.defaultTooltip) === null || _b === void 0 ? void 0 : _b.classList.remove(TaskEditTooltip.CLASSNAMES.TASK_EDIT_TOOLTIP_ARROW_BEFORE);
this.baseElement.style.display = "block";
var absolutePositionY = dom_1.DomUtils.getAbsolutePositionY(this.parentElement);
var absoluteX = dom_1.DomUtils.getAbsolutePositionX(this.parentElement);
var leftPosition = posX - absoluteX - 2 * arrowHeight;
var absoluteDistance = absolutePositionY - this.headerHeight - dom_1.DomUtils.getDocumentScrollTop() - heightOffset;
var isShowingDown = this.baseElement.clientHeight > absoluteDistance || this.baseElement.clientHeight > this.parentElement.offsetTop;
var topPosition = -this.baseElement.clientHeight - arrowHeight;
if (isShowingDown) {
topPosition = this.parentElement.clientHeight + arrowHeight;
(_c = this.defaultTooltip) === null || _c === void 0 ? void 0 : _c.classList.add(TaskEditTooltip.CLASSNAMES.TASK_EDIT_TOOLTIP_ARROW_AFTER);
}
else
(_d = this.defaultTooltip) === null || _d === void 0 ? void 0 : _d.classList.add(TaskEditTooltip.CLASSNAMES.TASK_EDIT_TOOLTIP_ARROW_BEFORE);
this.baseElement.style.left = leftPosition + "px";
this.baseElement.style.top = topPosition + "px";
if (autoHide) {
if (this.timerId)
clearTimeout(this.timerId);
this.timerId = setTimeout(function () {
_this.hide();
}, 1500);
}
};
TaskEditTooltip.prototype.hide = function () {
this.baseElement.style.display = "none";
this.destroyTemplate(this.baseElement);
clearTimeout(this.timerId);
};
TaskEditTooltip.prototype.getTimeContent = function (start, end) {
var timeElement = document.createElement("TABLE");
timeElement.className = TaskEditTooltip.CLASSNAMES.TASK_EDIT_PROGRESS_STATUS_TIME;
var body = document.createElement("TBODY");
timeElement.appendChild(body);
var startEl = document.createElement("TR");
var startTitle = document.createElement("TD");
var startValue = document.createElement("TD");
var endEl = document.createElement("TR");
var endTitle = document.createElement("TD");
var endValue = document.createElement("TD");
startEl.appendChild(startTitle);
startEl.appendChild(startValue);
endEl.appendChild(endTitle);
endEl.appendChild(endValue);
body.appendChild(startEl);
body.appendChild(endEl);
startTitle.innerText = (this.cultureInfo.start ? this.cultureInfo.start : "Start") + ": ";
startValue.innerText = this.formatDate(start);
endTitle.innerText = (this.cultureInfo.end ? this.cultureInfo.end : "End") + ": ";
endValue.innerText = this.formatDate(end);
return timeElement;
};
TaskEditTooltip.CLASSNAMES = {
TASK_EDIT_PROGRESS_STATUS: "dx-gantt-task-edit-tooltip",
TASK_EDIT_TOOLTIP_DEFAULT: "dx-gantt-task-edit-tooltip-default",
TASK_EDIT_TASK_TITLE: "dx-gantt-task-title",
TASK_EDIT_PROGRESS_STATUS_TIME: "dx-gantt-status-time",
TASK_EDIT_TOOLTIP_ARROW_BEFORE: "dx-gantt-task-edit-tooltip-before",
TASK_EDIT_TOOLTIP_ARROW_AFTER: "dx-gantt-task-edit-tooltip-after"
};
return TaskEditTooltip;
}());
exports.TaskEditTooltip = TaskEditTooltip;
/***/ }),
/* 147 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MouseHandlerDefaultState = void 0;
var tslib_1 = __webpack_require__(0);
var dom_1 = __webpack_require__(3);
var evt_1 = __webpack_require__(10);
var MouseHandlerStateBase_1 = __webpack_require__(48);
var GridLayoutCalculator_1 = __webpack_require__(16);
var point_1 = __webpack_require__(4);
var GanttMovingHelper_1 = __webpack_require__(151);
var MouseHandlerDefaultState = (function (_super) {
(0, tslib_1.__extends)(MouseHandlerDefaultState, _super);
function MouseHandlerDefaultState(handler) {
var _this = _super.call(this, handler) || this;
_this.isInScrolling = false;
return _this;
}
Object.defineProperty(MouseHandlerDefaultState.prototype, "ganttMovingHelper", {
get: function () {
var _a;
(_a = this._ganttMovingHelper) !== null && _a !== void 0 ? _a : (this._ganttMovingHelper = new GanttMovingHelper_1.GanttMovingHelper(this.renderHelper.taskAreaContainer));
return this._ganttMovingHelper;
},
enumerable: false,
configurable: true
});
MouseHandlerDefaultState.prototype.onMouseDown = function (evt) {
evt.preventDefault();
var source = evt_1.EvtUtils.getEventSource(evt);
if (dom_1.DomUtils.hasClassName(source, GridLayoutCalculator_1.GridLayoutCalculator.CLASSNAMES.CONNECTOR_HORIZONTAL) ||
dom_1.DomUtils.hasClassName(source, GridLayoutCalculator_1.GridLayoutCalculator.CLASSNAMES.CONNECTOR_VERTICAL)) {
var id = source.getAttribute("dependency-id");
if (this.taskEditController.dependencyId != id) {
this.selectDependency(id);
if (evt instanceof PointerEvent) {
var info = {
event: evt,
type: "dependency",
key: id,
position: new point_1.Point(evt_1.EvtUtils.getEventX(evt), evt_1.EvtUtils.getEventY(evt))
};
this.showPopupMenu(info);
}
}
}
else {
if (evt_1.EvtUtils.isLeftButtonPressed(evt))
this.ganttMovingHelper.startMoving(evt);
if (this.taskEditController.dependencyId != null)
this.selectDependency(null);
}
};
MouseHandlerDefaultState.prototype.onMouseUp = function (evt) {
this.ganttMovingHelper.onMouseUp(evt);
};
MouseHandlerDefaultState.prototype.onMouseMove = function (evt) {
if (this.ganttMovingHelper.movingInfo) {
this.taskEditController.hide();
this.ganttMovingHelper.onMouseMove(evt);
evt.preventDefault();
}
};
MouseHandlerDefaultState.prototype.onMouseWheel = function (evt) {
var _this = this;
if (evt.ctrlKey) {
evt.preventDefault();
evt.stopPropagation();
if (!this.isInScrolling) {
this.isInScrolling = true;
setTimeout(function () { _this.isInScrolling = false; }, 50);
var increase = evt_1.EvtUtils.getWheelDelta(evt) > 0;
var leftPos = evt_1.EvtUtils.getEventX(evt) - dom_1.DomUtils.getAbsolutePositionX(this.renderHelper.taskAreaContainer.getElement());
if (increase)
this.zoomIn(leftPos);
else
this.zoomOut(leftPos);
}
}
};
return MouseHandlerDefaultState;
}(MouseHandlerStateBase_1.MouseHandlerStateBase));
exports.MouseHandlerDefaultState = MouseHandlerDefaultState;
/***/ }),
/* 148 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = __webpack_require__(58);
var offsets_1 = __webpack_require__(149);
var Margins = (function (_super) {
tslib_1.__extends(Margins, _super);
function Margins() {
return _super !== null && _super.apply(this, arguments) || this;
}
Margins.empty = function () {
return new Margins(0, 0, 0, 0);
};
Margins.prototype.clone = function () {
return new Margins(this.left, this.right, this.top, this.bottom);
};
return Margins;
}(offsets_1.Offsets));
exports.Margins = Margins;
/***/ }),
/* 149 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Offsets = (function () {
function Offsets(left, right, top, bottom) {
this.left = left;
this.right = right;
this.top = top;
this.bottom = bottom;
}
Offsets.empty = function () {
return new Offsets(0, 0, 0, 0);
};
Object.defineProperty(Offsets.prototype, "horizontal", {
get: function () {
return this.left + this.right;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Offsets.prototype, "vertical", {
get: function () {
return this.top + this.bottom;
},
enumerable: true,
configurable: true
});
Offsets.fromNumber = function (offset) {
return new Offsets(offset, offset, offset, offset);
};
Offsets.fromOffsets = function (offsets) {
return new Offsets(offsets.left, offsets.right, offsets.top, offsets.bottom);
};
Offsets.fromSide = function (horizontal, vertical) {
return new Offsets(horizontal, horizontal, vertical, vertical);
};
Offsets.prototype.normalize = function () {
this.left = Math.max(0, this.left);
this.right = Math.max(0, this.right);
this.top = Math.max(0, this.top);
this.bottom = Math.max(0, this.bottom);
return this;
};
Offsets.prototype.toString = function () {
return JSON.stringify(this);
};
Offsets.prototype.isEmpty = function () {
return this.left === 0 && this.right === 0 && this.top === 0 && this.bottom === 0;
};
Offsets.prototype.offset = function (offset) {
this.left += offset.left;
this.right += offset.right;
this.top += offset.top;
this.bottom += offset.bottom;
return this;
};
Offsets.prototype.multiply = function (multLeft, multRight, multTop, multBottom) {
switch (arguments.length) {
case 1: {
this.left *= multLeft;
this.right *= multLeft;
this.top *= multLeft;
this.bottom *= multLeft;
return this;
}
case 2: {
this.left *= multLeft;
this.right *= multLeft;
this.top *= multRight;
this.bottom *= multRight;
return this;
}
case 4: {
this.left *= multLeft;
this.right *= multRight;
this.top *= multTop;
this.bottom *= multBottom;
return this;
}
}
return this;
};
Offsets.prototype.clone = function () {
return new Offsets(this.left, this.right, this.top, this.bottom);
};
Offsets.prototype.copyFrom = function (obj) {
this.left = obj.left;
this.right = obj.right;
this.top = obj.top;
this.bottom = obj.bottom;
};
Offsets.prototype.equals = function (obj) {
return this.top === obj.top &&
this.bottom === obj.bottom &&
this.right === obj.right &&
this.left === obj.left;
};
Offsets.prototype.applyConverter = function (converter) {
this.left = converter(this.left);
this.right = converter(this.right);
this.top = converter(this.top);
this.bottom = converter(this.bottom);
return this;
};
return Offsets;
}());
exports.Offsets = Offsets;
/***/ }),
/* 150 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScaleCalculator = exports.ScaleItemInfo = void 0;
var point_1 = __webpack_require__(4);
var size_1 = __webpack_require__(11);
var DateUtils_1 = __webpack_require__(21);
var Enums_1 = __webpack_require__(2);
var ScaleItemInfo = (function () {
function ScaleItemInfo(start, end, position, size) {
this.start = start;
this.end = end;
this.position = position;
this.size = size;
}
return ScaleItemInfo;
}());
exports.ScaleItemInfo = ScaleItemInfo;
var ScaleCalculator = (function () {
function ScaleCalculator() {
this.firstDayOfWeek = 0;
}
ScaleCalculator.prototype.setSettings = function (range, viewType, tickSize, firstDayOfWeek) {
if (firstDayOfWeek === void 0) { firstDayOfWeek = 0; }
this.range = range;
this.viewType = viewType;
this.tickSize = tickSize;
this.firstDayOfWeek = firstDayOfWeek;
this.reset();
};
ScaleCalculator.prototype.setViewType = function (viewType) {
this.viewType = viewType;
this.reset();
};
ScaleCalculator.prototype.reset = function () {
delete this._bottomScaleItems;
delete this._topScaleItems;
delete this._scaleWidth;
};
ScaleCalculator.prototype.getScaleIndexByPos = function (pos, scaleType) {
scaleType !== null && scaleType !== void 0 ? scaleType : (scaleType = this.viewType);
var items = scaleType === this.viewType ? this.bottomScaleItems : this.topScaleItems;
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (pos >= item.position.x && pos <= item.position.x + item.size.width)
return i;
}
return -1;
};
ScaleCalculator.prototype.getScaleBorderPosition = function (index, scaleType) {
var item = this.getScaleItems(scaleType)[index];
if (item)
return item.position.x + item.size.width;
};
ScaleCalculator.prototype.getScaleItems = function (scaleType) {
if (scaleType === this.viewType)
return this.bottomScaleItems;
if (scaleType === DateUtils_1.DateUtils.ViewTypeToScaleMap[this.viewType])
return this.topScaleItems;
return null;
};
ScaleCalculator.prototype.getScaleItem = function (index, scaleType) {
return this.getScaleItems(scaleType)[index];
};
ScaleCalculator.prototype.getScaleItemAdjustedStart = function (index, scaleType) {
var item = this.getScaleItems(scaleType)[index];
if (index > 0)
return item.start;
var isTopScale = scaleType !== this.viewType;
var date = isTopScale ? DateUtils_1.DateUtils.adjustStartDateByViewType(this.range.start, this.viewType, this.firstDayOfWeek) : this.getAdjustedBottomScaleItemStart(item.start, scaleType, this.firstDayOfWeek);
if (isTopScale && scaleType === Enums_1.ViewType.Months) {
var ref = this.range.start;
date = new Date(ref.getFullYear(), ref.getMonth(), 1);
}
if (isTopScale && scaleType === Enums_1.ViewType.FiveYears) {
var year = Math.trunc(date.getFullYear() / 5) * 5;
date = new Date(year, date.getMonth(), date.getDate());
}
return date;
};
Object.defineProperty(ScaleCalculator.prototype, "topScaleItems", {
get: function () {
var _a;
(_a = this._topScaleItems) !== null && _a !== void 0 ? _a : (this._topScaleItems = this.calculateTopScale(DateUtils_1.DateUtils.ViewTypeToScaleMap[this.viewType]));
return this._topScaleItems;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleCalculator.prototype, "bottomScaleItems", {
get: function () {
var _a;
(_a = this._bottomScaleItems) !== null && _a !== void 0 ? _a : (this._bottomScaleItems = this.calculateBottomScale(this.viewType));
return this._bottomScaleItems;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleCalculator.prototype, "scaleWidth", {
get: function () {
var _a;
(_a = this._scaleWidth) !== null && _a !== void 0 ? _a : (this._scaleWidth = this.calculateScaleWidth());
return this._scaleWidth;
},
enumerable: false,
configurable: true
});
ScaleCalculator.prototype.getFirstScaleIndexForRender = function (startPos) {
var result = this.getScaleIndexByPos(startPos);
result = Math.max(result - 10, 0);
return result;
};
ScaleCalculator.prototype.getLastScaleIndexForRender = function (endPos) {
var result = this.getScaleIndexByPos(endPos);
if (result === -1)
result = this.bottomScaleItems.length - 1;
else
result = Math.min(result + 10, this.bottomScaleItems.length - 1);
return result;
};
ScaleCalculator.prototype.calculateBottomScale = function (scaleType) {
var items = new Array();
var defWidth = this.tickSize.width;
var currentDate = this.range.start;
var x = 0;
while (currentDate.getTime() < this.range.end.getTime()) {
var nextDate = this.getNextScaleDate(currentDate, scaleType);
var isStart = currentDate.getTime() === this.range.start.getTime();
var isEnd = nextDate.getTime() >= this.range.end.getTime();
var width = isStart || isEnd ? this.getRangeTickCount(currentDate, nextDate) * defWidth : defWidth;
items.push(new ScaleItemInfo(currentDate, nextDate, new point_1.Point(x, undefined), new size_1.Size(width, 0)));
currentDate = nextDate;
x += width;
}
return items;
};
ScaleCalculator.prototype.calculateTopScale = function (scaleType) {
var items = new Array();
var currentDate = this.range.start;
var x = 0;
while (currentDate.getTime() < this.range.end.getTime()) {
var nextDate = this.getNextScaleDate(currentDate, scaleType);
var width = this.getPosInScale(nextDate) - this.getPosInScale(currentDate);
items.push(new ScaleItemInfo(currentDate, nextDate, new point_1.Point(x, undefined), new size_1.Size(width, 0)));
currentDate = nextDate;
x += width;
}
return items;
};
ScaleCalculator.prototype.getDateInScale = function (pos) {
for (var i = 0; i < this.bottomScaleItems.length; i++) {
var item = this.bottomScaleItems[i];
var width = item.size.width;
var left = item.position.x;
if (pos >= left && pos <= left + width) {
var startTime = item.start.getTime();
var endTime = item.end.getTime();
var timeOffset = (pos - left) / width * (endTime - startTime);
return new Date(item.start.getTime() + timeOffset);
}
}
return new Date(this.range.end);
};
ScaleCalculator.prototype.getPosInScale = function (date) {
var time = date.getTime();
for (var i = 0; i < this.bottomScaleItems.length; i++) {
var item = this.bottomScaleItems[i];
var startTime = item.start.getTime();
var endTime = item.end.getTime();
var width = item.size.width;
if (time >= startTime && time <= endTime)
return (time - startTime) / (endTime - startTime) * width + item.position.x;
}
return 0;
};
ScaleCalculator.prototype.getNextScaleDate = function (start, scaleType) {
var date;
switch (scaleType) {
case Enums_1.ViewType.TenMinutes:
date = this.getNextDateInTenMinutesScale(start);
break;
case Enums_1.ViewType.Hours:
date = this.getNextDateInHoursScale(start);
break;
case Enums_1.ViewType.SixHours:
date = this.getNextDateInSixHoursScale(start);
break;
case Enums_1.ViewType.Days:
date = this.getNextDateInDaysScale(start);
break;
case Enums_1.ViewType.Weeks:
date = this.getNextDateInWeeksScale(start, this.firstDayOfWeek);
break;
case Enums_1.ViewType.Months:
date = this.getNextDateInMonthsScale(start);
break;
case Enums_1.ViewType.Quarter:
date = this.getNextDateInQuartersScale(start);
break;
case Enums_1.ViewType.Years:
date = this.getNextDateInYearsScale(start);
break;
case Enums_1.ViewType.FiveYears:
date = this.getNextDateInFiveYearsScale(start);
break;
}
if (date.getTime() > this.range.end.getTime())
date = this.range.end;
return date;
};
ScaleCalculator.prototype.getNextTimeBySpan = function (value, span) {
var k = Math.trunc(value / span);
return (k + 1) * span;
};
ScaleCalculator.prototype.getNextDateInTenMinutesScale = function (date) {
var minutes = this.getNextTimeBySpan(date.getMinutes(), 10);
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), minutes);
};
ScaleCalculator.prototype.getNextDateInHoursScale = function (date) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours() + 1);
};
ScaleCalculator.prototype.getNextDateInSixHoursScale = function (date) {
var hours = this.getNextTimeBySpan(date.getHours(), 6);
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), hours);
};
ScaleCalculator.prototype.getNextDateInDaysScale = function (date) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
};
ScaleCalculator.prototype.getNextDateInWeeksScale = function (date, firstDayOfWeek) {
if (firstDayOfWeek === void 0) { firstDayOfWeek = 0; }
return new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + firstDayOfWeek + 7);
};
ScaleCalculator.prototype.getNextDateInMonthsScale = function (date) {
return new Date(date.getFullYear(), date.getMonth() + 1, 1);
};
ScaleCalculator.prototype.getNextDateInQuartersScale = function (date) {
var months = this.getNextTimeBySpan(date.getMonth(), 3);
return new Date(date.getFullYear(), months, 1);
};
ScaleCalculator.prototype.getNextDateInYearsScale = function (date) {
return new Date(date.getFullYear() + 1, 0, 1);
};
ScaleCalculator.prototype.getNextDateInFiveYearsScale = function (date) {
var years = this.getNextTimeBySpan(date.getFullYear(), 5);
return new Date(years, 0, 1);
};
ScaleCalculator.prototype.getAdjustedBottomScaleItemStart = function (date, viewType, firstDayOfWeek) {
if (firstDayOfWeek === void 0) { firstDayOfWeek = 0; }
switch (viewType) {
case Enums_1.ViewType.TenMinutes:
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), Math.floor(date.getMinutes() / 10) * 10);
case Enums_1.ViewType.SixHours:
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), Math.floor(date.getHours() / 6) * 6);
case Enums_1.ViewType.Hours:
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours());
case Enums_1.ViewType.Days:
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
case Enums_1.ViewType.Weeks:
return new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + firstDayOfWeek);
case Enums_1.ViewType.Months:
return new Date(date.getFullYear(), date.getMonth(), 1);
case Enums_1.ViewType.Quarter:
return new Date(date.getFullYear(), Math.floor(date.getMonth() / 3) * 3, 1);
case Enums_1.ViewType.Years:
return new Date(date.getFullYear(), 0, 1);
default:
return new Date();
}
};
ScaleCalculator.prototype.calculateScaleWidth = function () {
return this.bottomScaleItems.reduce(function (sum, item) { return sum += item.size.width; }, 0);
};
ScaleCalculator.prototype.getScaleItemColSpan = function (scaleType) {
if (scaleType.valueOf() === this.viewType.valueOf())
return 1;
if (this.viewType === Enums_1.ViewType.TenMinutes)
return 6;
if (this.viewType === Enums_1.ViewType.Hours)
return 24;
if (this.viewType === Enums_1.ViewType.SixHours)
return 4;
if (this.viewType === Enums_1.ViewType.Days)
return 7;
if (this.viewType === Enums_1.ViewType.Weeks)
return 4.29;
if (this.viewType === Enums_1.ViewType.Months)
return 12;
if (this.viewType === Enums_1.ViewType.Quarter)
return 4;
if (this.viewType === Enums_1.ViewType.Years)
return 5;
return 1;
};
ScaleCalculator.prototype.getRangeTickCount = function (start, end) {
return DateUtils_1.DateUtils.getRangeTickCount(start, end, this.viewType);
};
return ScaleCalculator;
}());
exports.ScaleCalculator = ScaleCalculator;
/***/ }),
/* 151 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GanttMovingHelper = void 0;
var browser_1 = __webpack_require__(8);
var evt_1 = __webpack_require__(10);
var GanttMovingHelper = (function () {
function GanttMovingHelper(taskAreaContainer) {
this.taskAreaContainer = taskAreaContainer;
this.movingInfo = null;
}
GanttMovingHelper.prototype.startMoving = function (e) {
this.movingInfo = this.calcMovingInfo(e);
this.updateGanttAreaCursor(true);
};
GanttMovingHelper.prototype.cancelMoving = function () {
this.movingInfo = null;
};
GanttMovingHelper.prototype.onMouseMove = function (e) {
this.move(e);
};
GanttMovingHelper.prototype.onMouseUp = function (e) {
this.cancelMoving();
this.updateGanttAreaCursor(false);
};
GanttMovingHelper.prototype.move = function (e) {
this.updateScrollPosition(e);
};
GanttMovingHelper.prototype.updateScrollPosition = function (e) {
var newEventX = Math.round(evt_1.EvtUtils.getEventX(e));
var newEventY = Math.round(evt_1.EvtUtils.getEventY(e));
var deltaX = newEventX - this.movingInfo.eventX;
var deltaY = newEventY - this.movingInfo.eventY;
var dirX = deltaX < 0 ? -1 : 1;
var dirY = deltaY < 0 ? -1 : 1;
var maxDeltaX = dirX < 0 ? this.movingInfo.maxRightDelta : this.movingInfo.maxLeftDelta;
var maxDeltaY = dirY < 0 ? this.movingInfo.maxBottomDelta : this.movingInfo.maxTopDelta;
if (Math.abs(deltaX) > maxDeltaX)
deltaX = maxDeltaX * dirX;
if (Math.abs(deltaY) > maxDeltaY)
deltaY = maxDeltaY * dirY;
var newScrollLeft = this.movingInfo.scrollLeft - deltaX;
var newScrollTop = this.movingInfo.scrollTop - deltaY;
var taskAreaContainer = this.taskAreaContainer;
if (taskAreaContainer.scrollLeft !== newScrollLeft)
taskAreaContainer.scrollLeft = newScrollLeft;
if (taskAreaContainer.scrollTop !== newScrollTop)
taskAreaContainer.scrollTop = newScrollTop;
};
GanttMovingHelper.prototype.calcMovingInfo = function (e) {
var taskAreaContainer = this.taskAreaContainer;
return {
eventX: evt_1.EvtUtils.getEventX(e),
eventY: evt_1.EvtUtils.getEventY(e),
scrollLeft: taskAreaContainer.scrollLeft,
scrollTop: taskAreaContainer.scrollTop,
maxLeftDelta: taskAreaContainer.scrollLeft,
maxRightDelta: taskAreaContainer.scrollWidth - taskAreaContainer.scrollLeft - taskAreaContainer.getElement().offsetWidth,
maxTopDelta: taskAreaContainer.scrollTop,
maxBottomDelta: taskAreaContainer.scrollHeight - taskAreaContainer.scrollTop - taskAreaContainer.getElement().offsetHeight
};
};
GanttMovingHelper.prototype.updateGanttAreaCursor = function (drag) {
var moveCursor = browser_1.Browser.IE ? "move" : "grabbing";
this.taskAreaContainer.getElement().style.cursor = drag ? moveCursor : "default";
};
return GanttMovingHelper;
}());
exports.GanttMovingHelper = GanttMovingHelper;
/***/ }),
/* 152 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MouseHandlerMoveTaskState = void 0;
var tslib_1 = __webpack_require__(0);
var MouseHandlerDragTaskBaseState_1 = __webpack_require__(49);
var MouseHandlerMoveTaskState = (function (_super) {
(0, tslib_1.__extends)(MouseHandlerMoveTaskState, _super);
function MouseHandlerMoveTaskState() {
return _super !== null && _super.apply(this, arguments) || this;
}
MouseHandlerMoveTaskState.prototype.onMouseUpInternal = function (_evt) {
this.taskEditController.confirmMove();
};
MouseHandlerMoveTaskState.prototype.onMouseMoveInternal = function (position) {
if (!this.taskEditController.processMove(position.x - this.currentPosition.x))
this.handler.switchToDefaultState();
};
return MouseHandlerMoveTaskState;
}(MouseHandlerDragTaskBaseState_1.MouseHandlerDragBaseState));
exports.MouseHandlerMoveTaskState = MouseHandlerMoveTaskState;
/***/ }),
/* 153 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MouseHandlerProgressTaskState = void 0;
var tslib_1 = __webpack_require__(0);
var MouseHandlerDragTaskBaseState_1 = __webpack_require__(49);
var MouseHandlerProgressTaskState = (function (_super) {
(0, tslib_1.__extends)(MouseHandlerProgressTaskState, _super);
function MouseHandlerProgressTaskState() {
return _super !== null && _super.apply(this, arguments) || this;
}
MouseHandlerProgressTaskState.prototype.onMouseUpInternal = function (_evt) {
this.taskEditController.confirmProgress();
};
MouseHandlerProgressTaskState.prototype.onMouseMoveInternal = function (position) {
var relativePosition = this.getRelativePos(position);
this.taskEditController.processProgress(relativePosition);
};
return MouseHandlerProgressTaskState;
}(MouseHandlerDragTaskBaseState_1.MouseHandlerDragBaseState));
exports.MouseHandlerProgressTaskState = MouseHandlerProgressTaskState;
/***/ }),
/* 154 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MouseHandlerTimestampTaskState = void 0;
var tslib_1 = __webpack_require__(0);
var evt_1 = __webpack_require__(10);
var Enums_1 = __webpack_require__(2);
var MouseHandlerDragTaskBaseState_1 = __webpack_require__(49);
var MouseHandlerTimestampTaskState = (function (_super) {
(0, tslib_1.__extends)(MouseHandlerTimestampTaskState, _super);
function MouseHandlerTimestampTaskState() {
return _super !== null && _super.apply(this, arguments) || this;
}
MouseHandlerTimestampTaskState.prototype.onMouseDown = function (evt) {
_super.prototype.onMouseDown.call(this, evt);
this.source = this.handler.getEventSource(evt_1.EvtUtils.getEventSource(evt));
};
MouseHandlerTimestampTaskState.prototype.onMouseUpInternal = function (_evt) {
if (this.source == Enums_1.MouseEventSource.TaskEdit_Start)
this.taskEditController.confirmStart();
else
this.taskEditController.confirmEnd();
};
MouseHandlerTimestampTaskState.prototype.onMouseMoveInternal = function (position) {
var relativePosition = this.getRelativePos(position);
if (this.source == Enums_1.MouseEventSource.TaskEdit_Start)
this.taskEditController.processStart(relativePosition);
if (this.source == Enums_1.MouseEventSource.TaskEdit_End)
this.taskEditController.processEnd(relativePosition);
};
return MouseHandlerTimestampTaskState;
}(MouseHandlerDragTaskBaseState_1.MouseHandlerDragBaseState));
exports.MouseHandlerTimestampTaskState = MouseHandlerTimestampTaskState;
/***/ }),
/* 155 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var browser_1 = __webpack_require__(8);
var encode_1 = __webpack_require__(156);
var string_1 = __webpack_require__(42);
var KeyUtils = (function () {
function KeyUtils() {
}
KeyUtils.getKeyModifiers = function (evt) {
var result = 0;
if (evt.altKey)
result |= ModifierKey.Alt;
if (evt.ctrlKey)
result |= ModifierKey.Ctrl;
if (evt.shiftKey)
result |= ModifierKey.Shift;
return result;
};
KeyUtils.getShortcutCode = function (keyCode, isCtrlKey, isShiftKey, isAltKey, isMetaKey) {
var value = keyCode;
value |= isCtrlKey ? ModifierKey.Ctrl : 0;
value |= isShiftKey ? ModifierKey.Shift : 0;
value |= isAltKey ? ModifierKey.Alt : 0;
value |= isMetaKey ? ModifierKey.Meta : 0;
return value;
};
KeyUtils.getShortcutCodeByEvent = function (evt) {
return KeyUtils.getShortcutCode(KeyUtils.getEventKeyCode(evt), evt.ctrlKey, evt.shiftKey, evt.altKey, browser_1.Browser.MacOSPlatform ? evt.metaKey : false);
};
KeyUtils.getEventKeyCode = function (evt) {
return browser_1.Browser.NetscapeFamily || browser_1.Browser.Opera ? evt.which : evt.keyCode;
};
KeyUtils.parseShortcutString = function (shortcutString) {
if (!shortcutString)
return 0;
var isCtrlKey = false;
var isShiftKey = false;
var isAltKey = false;
var isMetaKey = false;
var keyCode = null;
var shcKeys = shortcutString.toString().split('+');
if (shcKeys.length > 0) {
for (var i = 0; i < shcKeys.length; i++) {
var key = string_1.StringUtils.trim(shcKeys[i].toUpperCase());
switch (key) {
case 'CONTROL':
case 'CONTROLKEY':
case 'CTRL':
isCtrlKey = true;
break;
case 'SHIFT':
case 'SHIFTKEY':
isShiftKey = true;
break;
case 'ALT':
isAltKey = true;
break;
case 'CMD':
isMetaKey = true;
break;
case 'F1':
keyCode = KeyCode.F1;
break;
case 'F2':
keyCode = KeyCode.F2;
break;
case 'F3':
keyCode = KeyCode.F3;
break;
case 'F4':
keyCode = KeyCode.F4;
break;
case 'F5':
keyCode = KeyCode.F5;
break;
case 'F6':
keyCode = KeyCode.F6;
break;
case 'F7':
keyCode = KeyCode.F7;
break;
case 'F8':
keyCode = KeyCode.F8;
break;
case 'F9':
keyCode = KeyCode.F9;
break;
case 'F10':
keyCode = KeyCode.F10;
break;
case 'F11':
keyCode = KeyCode.F11;
break;
case 'F12':
keyCode = KeyCode.F12;
break;
case 'RETURN':
case 'ENTER':
keyCode = KeyCode.Enter;
break;
case 'HOME':
keyCode = KeyCode.Home;
break;
case 'END':
keyCode = KeyCode.End;
break;
case 'LEFT':
keyCode = KeyCode.Left;
break;
case 'RIGHT':
keyCode = KeyCode.Right;
break;
case 'UP':
keyCode = KeyCode.Up;
break;
case 'DOWN':
keyCode = KeyCode.Down;
break;
case 'PAGEUP':
keyCode = KeyCode.PageUp;
break;
case 'PAGEDOWN':
keyCode = KeyCode.PageDown;
break;
case 'SPACE':
keyCode = KeyCode.Space;
break;
case 'TAB':
keyCode = KeyCode.Tab;
break;
case 'BACKSPACE':
case 'BACK':
keyCode = KeyCode.Backspace;
break;
case 'CONTEXT':
keyCode = KeyCode.ContextMenu;
break;
case 'ESCAPE':
case 'ESC':
keyCode = KeyCode.Esc;
break;
case 'DELETE':
case 'DEL':
keyCode = KeyCode.Delete;
break;
case 'INSERT':
case 'INS':
keyCode = KeyCode.Insert;
break;
case 'PLUS':
keyCode = '+'.charCodeAt(0);
break;
default:
keyCode = key.charCodeAt(0);
break;
}
}
}
else
alert(encode_1.EncodeUtils.decodeViaTextArea('Invalid shortcut'));
return KeyUtils.getShortcutCode(keyCode, isCtrlKey, isShiftKey, isAltKey, isMetaKey);
};
return KeyUtils;
}());
exports.KeyUtils = KeyUtils;
var ModifierKey;
(function (ModifierKey) {
ModifierKey[ModifierKey["None"] = 0] = "None";
ModifierKey[ModifierKey["Ctrl"] = 65536] = "Ctrl";
ModifierKey[ModifierKey["Shift"] = 262144] = "Shift";
ModifierKey[ModifierKey["Alt"] = 1048576] = "Alt";
ModifierKey[ModifierKey["Meta"] = 16777216] = "Meta";
})(ModifierKey = exports.ModifierKey || (exports.ModifierKey = {}));
var KeyCode;
(function (KeyCode) {
KeyCode[KeyCode["Backspace"] = 8] = "Backspace";
KeyCode[KeyCode["Tab"] = 9] = "Tab";
KeyCode[KeyCode["Enter"] = 13] = "Enter";
KeyCode[KeyCode["Pause"] = 19] = "Pause";
KeyCode[KeyCode["CapsLock"] = 20] = "CapsLock";
KeyCode[KeyCode["Esc"] = 27] = "Esc";
KeyCode[KeyCode["Space"] = 32] = "Space";
KeyCode[KeyCode["PageUp"] = 33] = "PageUp";
KeyCode[KeyCode["PageDown"] = 34] = "PageDown";
KeyCode[KeyCode["End"] = 35] = "End";
KeyCode[KeyCode["Home"] = 36] = "Home";
KeyCode[KeyCode["Left"] = 37] = "Left";
KeyCode[KeyCode["Up"] = 38] = "Up";
KeyCode[KeyCode["Right"] = 39] = "Right";
KeyCode[KeyCode["Down"] = 40] = "Down";
KeyCode[KeyCode["Insert"] = 45] = "Insert";
KeyCode[KeyCode["Delete"] = 46] = "Delete";
KeyCode[KeyCode["Key_0"] = 48] = "Key_0";
KeyCode[KeyCode["Key_1"] = 49] = "Key_1";
KeyCode[KeyCode["Key_2"] = 50] = "Key_2";
KeyCode[KeyCode["Key_3"] = 51] = "Key_3";
KeyCode[KeyCode["Key_4"] = 52] = "Key_4";
KeyCode[KeyCode["Key_5"] = 53] = "Key_5";
KeyCode[KeyCode["Key_6"] = 54] = "Key_6";
KeyCode[KeyCode["Key_7"] = 55] = "Key_7";
KeyCode[KeyCode["Key_8"] = 56] = "Key_8";
KeyCode[KeyCode["Key_9"] = 57] = "Key_9";
KeyCode[KeyCode["Key_a"] = 65] = "Key_a";
KeyCode[KeyCode["Key_b"] = 66] = "Key_b";
KeyCode[KeyCode["Key_c"] = 67] = "Key_c";
KeyCode[KeyCode["Key_d"] = 68] = "Key_d";
KeyCode[KeyCode["Key_e"] = 69] = "Key_e";
KeyCode[KeyCode["Key_f"] = 70] = "Key_f";
KeyCode[KeyCode["Key_g"] = 71] = "Key_g";
KeyCode[KeyCode["Key_h"] = 72] = "Key_h";
KeyCode[KeyCode["Key_i"] = 73] = "Key_i";
KeyCode[KeyCode["Key_j"] = 74] = "Key_j";
KeyCode[KeyCode["Key_k"] = 75] = "Key_k";
KeyCode[KeyCode["Key_l"] = 76] = "Key_l";
KeyCode[KeyCode["Key_m"] = 77] = "Key_m";
KeyCode[KeyCode["Key_n"] = 78] = "Key_n";
KeyCode[KeyCode["Key_o"] = 79] = "Key_o";
KeyCode[KeyCode["Key_p"] = 80] = "Key_p";
KeyCode[KeyCode["Key_q"] = 81] = "Key_q";
KeyCode[KeyCode["Key_r"] = 82] = "Key_r";
KeyCode[KeyCode["Key_s"] = 83] = "Key_s";
KeyCode[KeyCode["Key_t"] = 84] = "Key_t";
KeyCode[KeyCode["Key_u"] = 85] = "Key_u";
KeyCode[KeyCode["Key_v"] = 86] = "Key_v";
KeyCode[KeyCode["Key_w"] = 87] = "Key_w";
KeyCode[KeyCode["Key_x"] = 88] = "Key_x";
KeyCode[KeyCode["Key_y"] = 89] = "Key_y";
KeyCode[KeyCode["Key_z"] = 90] = "Key_z";
KeyCode[KeyCode["Windows"] = 91] = "Windows";
KeyCode[KeyCode["ContextMenu"] = 93] = "ContextMenu";
KeyCode[KeyCode["Numpad_0"] = 96] = "Numpad_0";
KeyCode[KeyCode["Numpad_1"] = 97] = "Numpad_1";
KeyCode[KeyCode["Numpad_2"] = 98] = "Numpad_2";
KeyCode[KeyCode["Numpad_3"] = 99] = "Numpad_3";
KeyCode[KeyCode["Numpad_4"] = 100] = "Numpad_4";
KeyCode[KeyCode["Numpad_5"] = 101] = "Numpad_5";
KeyCode[KeyCode["Numpad_6"] = 102] = "Numpad_6";
KeyCode[KeyCode["Numpad_7"] = 103] = "Numpad_7";
KeyCode[KeyCode["Numpad_8"] = 104] = "Numpad_8";
KeyCode[KeyCode["Numpad_9"] = 105] = "Numpad_9";
KeyCode[KeyCode["Multiply"] = 106] = "Multiply";
KeyCode[KeyCode["Add"] = 107] = "Add";
KeyCode[KeyCode["Subtract"] = 109] = "Subtract";
KeyCode[KeyCode["Decimal"] = 110] = "Decimal";
KeyCode[KeyCode["Divide"] = 111] = "Divide";
KeyCode[KeyCode["F1"] = 112] = "F1";
KeyCode[KeyCode["F2"] = 113] = "F2";
KeyCode[KeyCode["F3"] = 114] = "F3";
KeyCode[KeyCode["F4"] = 115] = "F4";
KeyCode[KeyCode["F5"] = 116] = "F5";
KeyCode[KeyCode["F6"] = 117] = "F6";
KeyCode[KeyCode["F7"] = 118] = "F7";
KeyCode[KeyCode["F8"] = 119] = "F8";
KeyCode[KeyCode["F9"] = 120] = "F9";
KeyCode[KeyCode["F10"] = 121] = "F10";
KeyCode[KeyCode["F11"] = 122] = "F11";
KeyCode[KeyCode["F12"] = 123] = "F12";
KeyCode[KeyCode["NumLock"] = 144] = "NumLock";
KeyCode[KeyCode["ScrollLock"] = 145] = "ScrollLock";
KeyCode[KeyCode["Semicolon"] = 186] = "Semicolon";
KeyCode[KeyCode["Equals"] = 187] = "Equals";
KeyCode[KeyCode["Comma"] = 188] = "Comma";
KeyCode[KeyCode["Dash"] = 189] = "Dash";
KeyCode[KeyCode["Period"] = 190] = "Period";
KeyCode[KeyCode["ForwardSlash"] = 191] = "ForwardSlash";
KeyCode[KeyCode["GraveAccent"] = 192] = "GraveAccent";
KeyCode[KeyCode["OpenBracket"] = 219] = "OpenBracket";
KeyCode[KeyCode["BackSlash"] = 220] = "BackSlash";
KeyCode[KeyCode["CloseBracket"] = 221] = "CloseBracket";
KeyCode[KeyCode["SingleQuote"] = 222] = "SingleQuote";
})(KeyCode = exports.KeyCode || (exports.KeyCode = {}));
/***/ }),
/* 156 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var EncodeUtils = (function () {
function EncodeUtils() {
}
EncodeUtils.encodeHtml = function (text) {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
};
EncodeUtils.decodeHtml = function (text) {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
};
EncodeUtils.prepareTextForRequest = function (text) {
return text
.replace(/%/g, '%25')
.replace(/&/g, '%26amp;')
.replace(/\+/g, '%2B')
.replace(/</g, '%26lt;')
.replace(/>/g, '%26gt;')
.replace(/"/g, '%26quot;');
};
EncodeUtils.prepareTextForCallBackRequest = function (text) {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
};
EncodeUtils.decodeViaTextArea = function (html) {
var textArea = document.createElement('TEXTAREA');
textArea.innerHTML = html;
return textArea.value;
};
return EncodeUtils;
}());
exports.EncodeUtils = EncodeUtils;
/***/ }),
/* 157 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TouchHandler = void 0;
var tslib_1 = __webpack_require__(0);
var HandlerBase_1 = __webpack_require__(69);
var evt_1 = __webpack_require__(10);
var TouchHandlerMoveTaskState_1 = __webpack_require__(158);
var TouchHandlerDefaultState_1 = __webpack_require__(159);
var TouchHandlerProgressTaskState_1 = __webpack_require__(160);
var TouchHandlerTimestampTaskState_1 = __webpack_require__(161);
var TouchHandlerDependencyState_1 = __webpack_require__(162);
var TouchHandlerZoomState_1 = __webpack_require__(163);
var Enums_1 = __webpack_require__(2);
var TouchHandler = (function (_super) {
(0, tslib_1.__extends)(TouchHandler, _super);
function TouchHandler() {
return _super !== null && _super.apply(this, arguments) || this;
}
TouchHandler.prototype.onTouchStart = function (evt) {
if (evt.touches.length > 1)
evt.preventDefault();
var source = this.getEventSource(evt_1.EvtUtils.getEventSource(evt));
switch (source) {
case Enums_1.MouseEventSource.TaskEdit_Frame:
this.switchState(new TouchHandlerMoveTaskState_1.TouchHandlerMoveTaskState(this));
break;
case Enums_1.MouseEventSource.TaskEdit_Progress:
this.switchState(new TouchHandlerProgressTaskState_1.TouchHandlerProgressTaskState(this));
break;
case Enums_1.MouseEventSource.TaskEdit_Start:
case Enums_1.MouseEventSource.TaskEdit_End:
this.switchState(new TouchHandlerTimestampTaskState_1.TouchHandlerTimestampTaskState(this));
break;
case Enums_1.MouseEventSource.TaskEdit_DependencyStart:
case Enums_1.MouseEventSource.TaskEdit_DependencyFinish:
this.switchState(new TouchHandlerDependencyState_1.TouchHandlerDependencyState(this));
break;
}
this.state.onTouchStart(evt);
};
TouchHandler.prototype.onDoubleTap = function (evt) {
this.state.onDoubleTap(evt);
};
TouchHandler.prototype.onTouchEnd = function (evt) {
this.state.onTouchEnd(evt);
};
TouchHandler.prototype.onTouchMove = function (evt) {
if (evt.touches.length > 1)
if (!(this.state instanceof TouchHandlerZoomState_1.TouchHandlerZoomState))
this.switchState(new TouchHandlerZoomState_1.TouchHandlerZoomState(this));
this.state.onTouchMove(evt);
};
TouchHandler.prototype.switchToDefaultState = function () {
this.state = new TouchHandlerDefaultState_1.TouchHandlerDefaultState(this);
};
return TouchHandler;
}(HandlerBase_1.HandlerBase));
exports.TouchHandler = TouchHandler;
/***/ }),
/* 158 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TouchHandlerMoveTaskState = void 0;
var tslib_1 = __webpack_require__(0);
var TouchHandlerDragBaseState_1 = __webpack_require__(50);
var TouchHandlerMoveTaskState = (function (_super) {
(0, tslib_1.__extends)(TouchHandlerMoveTaskState, _super);
function TouchHandlerMoveTaskState() {
return _super !== null && _super.apply(this, arguments) || this;
}
TouchHandlerMoveTaskState.prototype.onTouchEndInternal = function (_evt) {
this.taskEditController.confirmMove();
};
TouchHandlerMoveTaskState.prototype.onTouchMoveInternal = function (position) {
if (!this.taskEditController.processMove(position.x - this.currentPosition.x))
this.handler.switchToDefaultState();
};
return TouchHandlerMoveTaskState;
}(TouchHandlerDragBaseState_1.TouchHandlerDragBaseState));
exports.TouchHandlerMoveTaskState = TouchHandlerMoveTaskState;
/***/ }),
/* 159 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TouchHandlerDefaultState = void 0;
var tslib_1 = __webpack_require__(0);
var point_1 = __webpack_require__(4);
var dom_1 = __webpack_require__(3);
var evt_1 = __webpack_require__(10);
var touch_1 = __webpack_require__(27);
var GridLayoutCalculator_1 = __webpack_require__(16);
var HandlerStateBase_1 = __webpack_require__(39);
var TouchHandlerDefaultState = (function (_super) {
(0, tslib_1.__extends)(TouchHandlerDefaultState, _super);
function TouchHandlerDefaultState() {
return _super !== null && _super.apply(this, arguments) || this;
}
TouchHandlerDefaultState.prototype.onTouchStart = function (evt) {
var _this = this;
this.preventSelect = false;
clearTimeout(this.popupTimer);
if (evt.touches.length === 1) {
var source = evt_1.EvtUtils.getEventSource(evt);
var info_1 = {
event: evt,
position: new point_1.Point(evt_1.EvtUtils.getEventX(evt), evt_1.EvtUtils.getEventY(evt))
};
if (dom_1.DomUtils.hasClassName(source, GridLayoutCalculator_1.GridLayoutCalculator.CLASSNAMES.CONNECTOR_HORIZONTAL) ||
dom_1.DomUtils.hasClassName(source, GridLayoutCalculator_1.GridLayoutCalculator.CLASSNAMES.CONNECTOR_VERTICAL)) {
this.preventSelect = true;
var id = source.getAttribute("dependency-id");
if (this.taskEditController.dependencyId != id)
this.selectDependency(id);
info_1["type"] = "dependency";
info_1["key"] = id;
this.showPopupMenu(info_1);
}
else
this.popupTimer = setTimeout(function () {
var index = _this.getTaskIndex(evt);
_this.changeTaskSelection(index);
var item = _this.viewModel.items[index];
info_1["type"] = "task";
info_1["key"] = item && item.task.id;
_this.showPopupMenu(info_1);
}, 500);
}
};
TouchHandlerDefaultState.prototype.onDoubleTap = function (_evt) { };
TouchHandlerDefaultState.prototype.onTouchEnd = function (evt) {
clearTimeout(this.popupTimer);
if (!this.preventSelect)
this.changeTaskSelection(this.getTaskIndex(evt));
};
TouchHandlerDefaultState.prototype.onTouchMove = function (_evt) {
clearTimeout(this.popupTimer);
this.preventSelect = true;
};
TouchHandlerDefaultState.prototype.getTaskIndex = function (evt) {
var y = touch_1.TouchUtils.getEventY(evt);
var taskAreaY = dom_1.DomUtils.getAbsolutePositionY(this.renderHelper.taskArea);
var relativeY = y - taskAreaY;
return Math.floor(relativeY / this.tickSize.height);
};
TouchHandlerDefaultState.prototype.changeTaskSelection = function (index) {
var clickedTask = this.viewModel.items[index];
if (clickedTask)
this.changeGanttTaskSelection(clickedTask.task.id, true);
};
return TouchHandlerDefaultState;
}(HandlerStateBase_1.HandlerStateBase));
exports.TouchHandlerDefaultState = TouchHandlerDefaultState;
/***/ }),
/* 160 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TouchHandlerProgressTaskState = void 0;
var tslib_1 = __webpack_require__(0);
var TouchHandlerDragBaseState_1 = __webpack_require__(50);
var TouchHandlerProgressTaskState = (function (_super) {
(0, tslib_1.__extends)(TouchHandlerProgressTaskState, _super);
function TouchHandlerProgressTaskState() {
return _super !== null && _super.apply(this, arguments) || this;
}
TouchHandlerProgressTaskState.prototype.onTouchEndInternal = function (_evt) {
this.taskEditController.confirmProgress();
};
TouchHandlerProgressTaskState.prototype.onTouchMoveInternal = function (position) {
var relativePosition = this.getRelativePos(position);
this.taskEditController.processProgress(relativePosition);
};
return TouchHandlerProgressTaskState;
}(TouchHandlerDragBaseState_1.TouchHandlerDragBaseState));
exports.TouchHandlerProgressTaskState = TouchHandlerProgressTaskState;
/***/ }),
/* 161 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TouchHandlerTimestampTaskState = void 0;
var tslib_1 = __webpack_require__(0);
var TouchHandlerDragBaseState_1 = __webpack_require__(50);
var evt_1 = __webpack_require__(10);
var Enums_1 = __webpack_require__(2);
var TouchHandlerTimestampTaskState = (function (_super) {
(0, tslib_1.__extends)(TouchHandlerTimestampTaskState, _super);
function TouchHandlerTimestampTaskState() {
return _super !== null && _super.apply(this, arguments) || this;
}
TouchHandlerTimestampTaskState.prototype.onTouchStart = function (evt) {
_super.prototype.onTouchStart.call(this, evt);
this.source = this.handler.getEventSource(evt_1.EvtUtils.getEventSource(evt));
};
TouchHandlerTimestampTaskState.prototype.onTouchEndInternal = function (_evt) {
if (this.source == Enums_1.MouseEventSource.TaskEdit_Start)
this.taskEditController.confirmStart();
else
this.taskEditController.confirmEnd();
};
TouchHandlerTimestampTaskState.prototype.onTouchMoveInternal = function (position) {
var relativePosition = this.getRelativePos(position);
if (this.source == Enums_1.MouseEventSource.TaskEdit_Start)
this.taskEditController.processStart(relativePosition);
if (this.source == Enums_1.MouseEventSource.TaskEdit_End)
this.taskEditController.processEnd(relativePosition);
};
return TouchHandlerTimestampTaskState;
}(TouchHandlerDragBaseState_1.TouchHandlerDragBaseState));
exports.TouchHandlerTimestampTaskState = TouchHandlerTimestampTaskState;
/***/ }),
/* 162 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TouchHandlerDependencyState = void 0;
var tslib_1 = __webpack_require__(0);
var TouchHandlerStateBase_1 = __webpack_require__(75);
var dom_1 = __webpack_require__(3);
var evt_1 = __webpack_require__(10);
var point_1 = __webpack_require__(4);
var MouseHandlerDependencyState_1 = __webpack_require__(74);
var touch_1 = __webpack_require__(27);
var Enums_1 = __webpack_require__(2);
var TouchHandlerDependencyState = (function (_super) {
(0, tslib_1.__extends)(TouchHandlerDependencyState, _super);
function TouchHandlerDependencyState() {
return _super !== null && _super.apply(this, arguments) || this;
}
TouchHandlerDependencyState.prototype.onTouchStart = function (evt) {
evt.preventDefault();
var sourceElement = evt_1.EvtUtils.getEventSource(evt);
this.source = this.handler.getEventSource(sourceElement);
var pos = this.getRelativePos(new point_1.Point(dom_1.DomUtils.getAbsolutePositionX(sourceElement) + sourceElement.clientWidth / 2, dom_1.DomUtils.getAbsolutePositionY(sourceElement) + sourceElement.clientHeight / 2));
this.taskEditController.startDependency(pos);
};
TouchHandlerDependencyState.prototype.onTouchEnd = function (evt) {
var relativePosStart = this.getRelativePos(new point_1.Point(dom_1.DomUtils.getAbsolutePositionX(this.taskEditController.dependencySuccessorStart) + this.taskEditController.dependencySuccessorStart.clientWidth / 2, dom_1.DomUtils.getAbsolutePositionY(this.taskEditController.dependencySuccessorStart) + this.taskEditController.dependencySuccessorStart.clientHeight / 2));
var relativePosEnd = this.getRelativePos(new point_1.Point(dom_1.DomUtils.getAbsolutePositionX(this.taskEditController.dependencySuccessorFinish) + this.taskEditController.dependencySuccessorFinish.clientWidth / 2, dom_1.DomUtils.getAbsolutePositionY(this.taskEditController.dependencySuccessorFinish) + this.taskEditController.dependencySuccessorFinish.clientHeight / 2));
var relativeTouchPos = this.getRelativePos(new point_1.Point(touch_1.TouchUtils.getEventX(evt), touch_1.TouchUtils.getEventY(evt)));
var target = this.isTouchNearby(relativeTouchPos, relativePosStart) ? Enums_1.MouseEventSource.Successor_DependencyStart :
this.isTouchNearby(relativeTouchPos, relativePosEnd) ? Enums_1.MouseEventSource.Successor_DependencyFinish : null;
var type = target === Enums_1.MouseEventSource.Successor_DependencyStart || target == Enums_1.MouseEventSource.Successor_DependencyFinish ?
MouseHandlerDependencyState_1.dependencyMap[this.source][target] : null;
this.taskEditController.endDependency(type);
this.handler.switchToDefaultState();
};
TouchHandlerDependencyState.prototype.onTouchMove = function (evt) {
evt.preventDefault();
var relativePos = this.getRelativePos(new point_1.Point(touch_1.TouchUtils.getEventX(evt), touch_1.TouchUtils.getEventY(evt)));
var hoverTaskIndex = Math.floor(relativePos.y / this.tickSize.height);
this.taskEditController.processDependency(relativePos);
if (this.viewModel.tasks.items[hoverTaskIndex])
this.taskEditController.showDependencySuccessor(hoverTaskIndex);
};
TouchHandlerDependencyState.prototype.isTouchNearby = function (touchPos, elementPos) {
if (Math.abs(elementPos.x - touchPos.x) <= 10 && Math.abs(elementPos.y - touchPos.y) <= 10)
return true;
return false;
};
return TouchHandlerDependencyState;
}(TouchHandlerStateBase_1.TouchHandlerStateBase));
exports.TouchHandlerDependencyState = TouchHandlerDependencyState;
/***/ }),
/* 163 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TouchHandlerZoomState = void 0;
var tslib_1 = __webpack_require__(0);
var HandlerStateBase_1 = __webpack_require__(39);
var point_1 = __webpack_require__(4);
var dom_1 = __webpack_require__(3);
var PINCH_CHANGE_DISTANCE = 3;
var TouchHandlerZoomState = (function (_super) {
(0, tslib_1.__extends)(TouchHandlerZoomState, _super);
function TouchHandlerZoomState() {
return _super !== null && _super.apply(this, arguments) || this;
}
TouchHandlerZoomState.prototype.onTouchStart = function (_evt) { };
TouchHandlerZoomState.prototype.onDoubleTap = function (_evt) { };
TouchHandlerZoomState.prototype.onTouchEnd = function (_evt) {
this.prevDistance = null;
this.handler.switchToDefaultState();
};
TouchHandlerZoomState.prototype.onTouchMove = function (evt) {
evt.stopPropagation();
evt.preventDefault();
if (evt.touches.length > 1) {
var distance = this.getTouchDistance(evt);
if (this.prevDistance) {
var diff = this.prevDistance - distance;
if (Math.abs(diff) > PINCH_CHANGE_DISTANCE) {
var offsetX = this.getMiddleAbsPoint(evt).x;
if (diff > 0)
this.zoomOut(offsetX);
else
this.zoomIn(offsetX);
this.prevDistance = distance;
}
}
else
this.prevDistance = distance;
}
};
TouchHandlerZoomState.prototype.getTouchDistance = function (evt) {
var pt0 = new point_1.Point(evt.touches[0].clientX, evt.touches[0].clientY);
var pt1 = new point_1.Point(evt.touches[1].clientX, evt.touches[1].clientY);
return this.getDistance(pt0, pt1);
};
TouchHandlerZoomState.prototype.getDistance = function (a, b) {
return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
};
TouchHandlerZoomState.prototype.getMiddleAbsPoint = function (evt) {
var _this = this;
return this.getMiddlePointByEvent(evt, function (touch) {
return new point_1.Point(touch.pageX - dom_1.DomUtils.getAbsolutePositionX(_this.renderHelper.taskAreaContainer.getElement()), touch.pageY - dom_1.DomUtils.getAbsolutePositionY(_this.renderHelper.taskAreaContainer.getElement()));
});
};
TouchHandlerZoomState.prototype.getMiddlePointByEvent = function (evt, getPoint) {
if (evt.touches.length > 1)
return new point_1.Point((getPoint(evt.touches[0]).x + getPoint(evt.touches[1]).x) / 2, (getPoint(evt.touches[0]).y + getPoint(evt.touches[1]).y) / 2);
};
return TouchHandlerZoomState;
}(HandlerStateBase_1.HandlerStateBase));
exports.TouchHandlerZoomState = TouchHandlerZoomState;
/***/ }),
/* 164 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FullScreenHelperSettings = void 0;
var common_1 = __webpack_require__(1);
var FullScreenHelperSettings = (function () {
function FullScreenHelperSettings() {
}
FullScreenHelperSettings.parse = function (settings) {
var result = new FullScreenHelperSettings();
if (settings) {
if ((0, common_1.isDefined)(settings.getMainElement))
result.getMainElement = settings.getMainElement;
if ((0, common_1.isDefined)(settings.adjustControl))
result.adjustControl = settings.adjustControl;
}
return result;
};
return FullScreenHelperSettings;
}());
exports.FullScreenHelperSettings = FullScreenHelperSettings;
/***/ }),
/* 165 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FullScreenModeHelper = void 0;
var browser_1 = __webpack_require__(8);
var attr_1 = __webpack_require__(166);
var dom_1 = __webpack_require__(3);
var FullScreenModeHelper = (function () {
function FullScreenModeHelper(settings) {
this._isInFullScreenMode = false;
this.fullScreenTempVars = {};
this.settings = settings;
}
Object.defineProperty(FullScreenModeHelper.prototype, "isInFullScreenMode", {
get: function () { return this._isInFullScreenMode; },
enumerable: false,
configurable: true
});
FullScreenModeHelper.prototype.getMainElement = function () {
return this.settings.getMainElement();
};
FullScreenModeHelper.prototype.adjustControl = function () {
this.settings.adjustControl();
};
FullScreenModeHelper.prototype.toggle = function () {
this._isInFullScreenMode = !this._isInFullScreenMode;
if (this._isInFullScreenMode)
this.setFullScreenMode();
else
this.setNormalMode();
return true;
};
FullScreenModeHelper.prototype.setFullScreenMode = function () {
this.prepareFullScreenMode();
this.adjustControlInFullScreenMode();
};
FullScreenModeHelper.prototype.prepareFullScreenMode = function () {
var mainElement = this.getMainElement();
attr_1.AttrUtils.changeElementStyleAttribute(mainElement, "border-top-width", "0px");
attr_1.AttrUtils.changeElementStyleAttribute(mainElement, "border-left-width", "0px");
attr_1.AttrUtils.changeElementStyleAttribute(mainElement, "border-right-width", "0px");
attr_1.AttrUtils.changeElementStyleAttribute(mainElement, "border-bottom-width", "0px");
this.fullScreenTempVars.scrollTop = dom_1.DomUtils.getDocumentScrollTop();
this.fullScreenTempVars.scrollLeft = dom_1.DomUtils.getDocumentScrollLeft();
attr_1.AttrUtils.changeElementStyleAttribute(mainElement, "background-color", "white");
attr_1.AttrUtils.changeElementStyleAttribute(mainElement, "position", "fixed");
attr_1.AttrUtils.changeElementStyleAttribute(mainElement, "top", "0px");
attr_1.AttrUtils.changeElementStyleAttribute(mainElement, "left", "0px");
attr_1.AttrUtils.changeElementStyleAttribute(mainElement, "z-index", "1010");
attr_1.AttrUtils.changeElementStyleAttribute(document.documentElement, "position", "static");
attr_1.AttrUtils.changeElementStyleAttribute(document.documentElement, "overflow", "hidden");
this.fullScreenTempVars.bodyMargin = document.body.style.margin;
document.body.style.margin = "0";
this.fullScreenTempVars.width = mainElement.style.width;
this.fullScreenTempVars.height = mainElement.style.height || mainElement.clientHeight;
if (window.self !== window.top)
this.requestFullScreen(document.body);
};
FullScreenModeHelper.prototype.setNormalMode = function () {
this.cancelFullScreen(document);
var mainElement = this.getMainElement();
attr_1.AttrUtils.restoreElementStyleAttribute(mainElement, "left");
attr_1.AttrUtils.restoreElementStyleAttribute(mainElement, "top");
attr_1.AttrUtils.restoreElementStyleAttribute(mainElement, "background-color");
attr_1.AttrUtils.restoreElementStyleAttribute(document.documentElement, "overflow");
attr_1.AttrUtils.restoreElementStyleAttribute(document.documentElement, "position");
attr_1.AttrUtils.restoreElementStyleAttribute(mainElement, "z-index");
document.body.style.margin = this.fullScreenTempVars.bodyMargin;
attr_1.AttrUtils.restoreElementStyleAttribute(mainElement, "position");
attr_1.AttrUtils.restoreElementStyleAttribute(mainElement, "border-top-width");
attr_1.AttrUtils.restoreElementStyleAttribute(mainElement, "border-left-width");
attr_1.AttrUtils.restoreElementStyleAttribute(mainElement, "border-right-width");
attr_1.AttrUtils.restoreElementStyleAttribute(mainElement, "border-bottom-width");
this.setHeight(this.fullScreenTempVars.height);
this.setWidth(this.fullScreenTempVars.width);
document.documentElement.scrollTop = this.fullScreenTempVars.scrollTop;
document.documentElement.scrollLeft = this.fullScreenTempVars.scrollLeft;
this.adjustControl();
};
FullScreenModeHelper.prototype.adjustControlInFullScreenMode = function () {
var documentWidth = document.documentElement.clientWidth == 0 ? document.body.clientWidth : document.documentElement.clientWidth;
var documentHeight = document.documentElement.clientHeight == 0 ? document.body.clientHeight : document.documentElement.clientHeight;
this.setWidth(documentWidth);
this.setHeight(documentHeight);
this.adjustControl();
};
FullScreenModeHelper.prototype.requestFullScreen = function (element) {
if (element.requestFullscreen)
element.requestFullscreen();
else if (element.mozRequestFullScreen)
element.mozRequestFullScreen();
else if (element.webkitRequestFullscreen)
element.webkitRequestFullscreen();
else if (element.msRequestFullscreen)
element.msRequestFullscreen();
};
FullScreenModeHelper.prototype.cancelFullScreen = function (document) {
if (browser_1.Browser.Firefox && !this.getFullScreenElement(document))
return;
if (document.webkitExitFullscreen)
document.webkitExitFullscreen();
else if (document.mozCancelFullScreen)
document.mozCancelFullScreen();
else if (document.msExitFullscreen)
document.msExitFullscreen();
else if (document.exitFullscreen)
document.exitFullscreen();
};
FullScreenModeHelper.prototype.getFullScreenElement = function (document) {
return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
};
FullScreenModeHelper.prototype.setWidth = function (width) {
var mainElement = this.getMainElement();
mainElement.style.width = this.isNumber(width) ? width + "px" : width;
};
FullScreenModeHelper.prototype.setHeight = function (height) {
var mainElement = this.getMainElement();
mainElement.style.height = this.isNumber(height) ? height + "px" : height;
};
FullScreenModeHelper.prototype.isNumber = function (str) {
return !isNaN(parseFloat(str)) && isFinite(str);
};
return FullScreenModeHelper;
}());
exports.FullScreenModeHelper = FullScreenModeHelper;
/***/ }),
/* 166 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var browser_1 = __webpack_require__(8);
var AttrUtils = (function () {
function AttrUtils() {
}
AttrUtils.setElementAttribute = function (obj, attrName, value) {
if (obj.setAttribute) {
if (browser_1.Browser.IE && browser_1.Browser.MajorVersion >= 11 && attrName.toLowerCase() === 'src')
obj.setAttribute(attrName, '');
obj.setAttribute(attrName, value);
}
};
AttrUtils.setStyleAttribute = function (obj, attrName, value) {
if (obj.setProperty)
obj.setProperty(attrName, value, '');
};
AttrUtils.getElementAttribute = function (obj, attrName) {
return obj.getAttribute(attrName);
};
AttrUtils.getStyleAttribute = function (obj, attrName) {
if (obj.getPropertyValue) {
if (browser_1.Browser.Firefox) {
try {
return obj.getPropertyValue(attrName);
}
catch (e) {
return obj[attrName];
}
}
return obj.getPropertyValue(attrName);
}
return null;
};
AttrUtils.removeElementAttribute = function (obj, attrName) {
if (obj.removeAttribute)
obj.removeAttribute(attrName);
};
AttrUtils.removeStyleAttribute = function (obj, attrName) {
if (obj.removeProperty)
obj.removeProperty(attrName);
};
AttrUtils.changeElementStyleAttribute = function (obj, attrName, newValue) {
AttrUtils.saveStyleAttributeInElement(obj, attrName);
AttrUtils.setStyleAttribute(obj.style, attrName, newValue);
};
AttrUtils.restoreElementStyleAttribute = function (obj, attrName) {
var savedAttrName = "saved" + attrName;
var style = obj.style;
if (AttrUtils.isExistsAttributeInElement(obj, savedAttrName)) {
var oldValue = AttrUtils.getElementAttribute(obj, savedAttrName);
if (oldValue === AttrUtils.emptyObject || oldValue === null)
AttrUtils.removeStyleAttribute(style, attrName);
else
AttrUtils.setStyleAttribute(style, attrName, oldValue);
AttrUtils.removeElementAttribute(obj, savedAttrName);
return true;
}
return false;
};
AttrUtils.saveStyleAttributeInElement = function (obj, attrName) {
var savedAttrName = "saved" + attrName;
var style = obj.style;
if (!AttrUtils.isExistsAttributeInElement(obj, savedAttrName)) {
var oldValue = AttrUtils.getStyleAttribute(style, attrName);
AttrUtils.setElementAttribute(obj, savedAttrName, AttrUtils.isAttributeExists(oldValue) ? oldValue : AttrUtils.emptyObject);
}
};
AttrUtils.isExistsAttributeInElement = function (obj, attrName) {
var value = AttrUtils.getElementAttribute(obj, attrName);
return AttrUtils.isAttributeExists(value);
};
AttrUtils.isAttributeExists = function (attrValue) {
return attrValue !== null && attrValue !== '';
};
AttrUtils.emptyObject = 'DxEmptyValue';
return AttrUtils;
}());
exports.AttrUtils = AttrUtils;
/***/ }),
/* 167 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GanttExportCalculator = void 0;
var point_1 = __webpack_require__(4);
var dom_1 = __webpack_require__(3);
var Enums_1 = __webpack_require__(2);
var GridLayoutCalculator_1 = __webpack_require__(16);
var DependencyLineInfo_1 = __webpack_require__(76);
var TaskResourcesInfo_1 = __webpack_require__(77);
var TaskInfo_1 = __webpack_require__(52);
var Color_1 = __webpack_require__(17);
var StyleDef_1 = __webpack_require__(28);
var Margin_1 = __webpack_require__(40);
var CellDef_1 = __webpack_require__(53);
var TaskAreaHelper_1 = __webpack_require__(168);
var Props_1 = __webpack_require__(54);
var Interfaces_1 = __webpack_require__(29);
var size_1 = __webpack_require__(11);
var Paginator_1 = __webpack_require__(169);
var ScalingHelper_1 = __webpack_require__(171);
var TimeMarkerInfo_1 = __webpack_require__(79);
var GanttExportCalculator = (function () {
function GanttExportCalculator(owner, props) {
var _a;
var _b;
this._owner = owner;
this._props = new Props_1.GanttPdfExportProps(props);
(_a = (_b = this._props).margins) !== null && _a !== void 0 ? _a : (_b.margins = new Margin_1.Margin(GanttExportCalculator._defaultPageMargin));
}
Object.defineProperty(GanttExportCalculator.prototype, "chartTableScaleTopMatrix", {
get: function () {
var _a;
(_a = this._chartTableScaleTopMatrix) !== null && _a !== void 0 ? _a : (this._chartTableScaleTopMatrix = this.calculateChartScaleMatrix(0));
return this._chartTableScaleTopMatrix;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "chartTableScaleBottomMatrix", {
get: function () {
var _a;
(_a = this._chartTableScaleBottomMatrix) !== null && _a !== void 0 ? _a : (this._chartTableScaleBottomMatrix = this.calculateChartScaleMatrix(1));
return this._chartTableScaleBottomMatrix;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "chartTableBodyMatrix", {
get: function () {
if (!this._chartTableBodyMatrix)
this.calculateChartTableBodyMatrix();
return this._chartTableBodyMatrix;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "treeListHeaderMatrix", {
get: function () {
if (!this._treeListHeaderMatrix)
this.calculateTreeListTableHeaderMatrix();
return this._treeListHeaderMatrix;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "treeListBodyMatrix", {
get: function () {
if (!this._treeListBodyMatrix)
this.calculateTreeListTableBodyMatrix();
return this._treeListBodyMatrix;
},
enumerable: false,
configurable: true
});
GanttExportCalculator.prototype.getPages = function (pdfDoc) {
var paginator = new Paginator_1.PdfGanttPaginator(pdfDoc, this.settings, this.createGlobalInfo());
return paginator.getPages();
};
Object.defineProperty(GanttExportCalculator.prototype, "settings", {
get: function () {
return this.settingsForPaging;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "layoutCalculator", {
get: function () {
return this._taskAreaHelper.layoutCalculator;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "taskAreaHelper", {
get: function () {
var _a;
(_a = this._taskAreaHelper) !== null && _a !== void 0 ? _a : (this._taskAreaHelper = new TaskAreaHelper_1.TaskAreaExportHelper(this._owner, this._props));
return this._taskAreaHelper;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "scalingHelper", {
get: function () {
var _a, _b;
(_a = this._scalingHelper) !== null && _a !== void 0 ? _a : (this._scalingHelper = new ScalingHelper_1.ScalingHelper((_b = this._props) === null || _b === void 0 ? void 0 : _b.pdfDoc));
return this._scalingHelper;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "visibleTaskIndices", {
get: function () {
return this.taskAreaHelper.visibleTaskIndices;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "baseCellWidth", {
get: function () {
return this.taskAreaHelper.baseCellSize.width;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "baseCellHeight", {
get: function () {
return this.taskAreaHelper.baseCellSize.height;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "chartScaleTableStyle", {
get: function () {
var _a;
(_a = this._chartScaleTableStyle) !== null && _a !== void 0 ? _a : (this._chartScaleTableStyle = this.getChartScaleTableStyle());
return this._chartScaleTableStyle;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "chartMainTableStyle", {
get: function () {
var _a;
(_a = this._chartMainTableStyle) !== null && _a !== void 0 ? _a : (this._chartMainTableStyle = this.getChartMainTableStyle());
return this._chartMainTableStyle;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "treeListTableStyle", {
get: function () {
if (!this._treeListTableStyle)
this.calculateTreeListTableStyle();
return this._treeListTableStyle;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "pageTopMargin", {
get: function () {
return this._props.margins.top;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "pageLeftMargin", {
get: function () {
return this._props.margins.left;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "pageRightMargin", {
get: function () {
return this._props.margins.right;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "pageBottomMargin", {
get: function () {
return this._props.margins.bottom;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "headerTableTop", {
get: function () {
var _a;
(_a = this._headerTableTop) !== null && _a !== void 0 ? _a : (this._headerTableTop = this.pageTopMargin);
return this._headerTableTop;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "mainTableTop", {
get: function () {
var _a;
(_a = this._mainTableTop) !== null && _a !== void 0 ? _a : (this._mainTableTop = this.getMainTableTop());
return this._mainTableTop;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "exportDataMode", {
get: function () {
return this._props.exportDataMode;
},
enumerable: false,
configurable: true
});
GanttExportCalculator.prototype.getMainTableTop = function () {
return this.headerTableTop + this.headerTableHeight - this.taskAreaHelper.offsetTop;
};
Object.defineProperty(GanttExportCalculator.prototype, "chartLeft", {
get: function () {
var _a;
(_a = this._chartLeft) !== null && _a !== void 0 ? _a : (this._chartLeft = this.getChartLeft());
return this._chartLeft;
},
enumerable: false,
configurable: true
});
GanttExportCalculator.prototype.getChartLeft = function () {
var _a;
var mode = ((_a = this._props) === null || _a === void 0 ? void 0 : _a.exportMode) || Props_1.ExportMode.all;
var visibleLeft = mode === Props_1.ExportMode.chart ? this.pageLeftMargin : this.treeListLeft + this.treeListWidth;
var left = visibleLeft - this.taskAreaHelper.offsetLeft;
return left;
};
Object.defineProperty(GanttExportCalculator.prototype, "treeListLeft", {
get: function () {
var _a;
(_a = this._treeListLeft) !== null && _a !== void 0 ? _a : (this._treeListLeft = this.pageLeftMargin);
return this._treeListLeft;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "headerTableHeight", {
get: function () {
return 2 * this.taskAreaHelper.headerRowHeight;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "mainTableHeight", {
get: function () {
var _a;
(_a = this._mainTableHeight) !== null && _a !== void 0 ? _a : (this._mainTableHeight = this.visibleTaskIndices.length * this.baseCellHeight);
return this._mainTableHeight;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "treeListWidth", {
get: function () {
var _a;
(_a = this._treeListWidth) !== null && _a !== void 0 ? _a : (this._treeListWidth = this.getTreeListTableWidth());
return this._treeListWidth;
},
enumerable: false,
configurable: true
});
GanttExportCalculator.prototype.getTreeListTableWidth = function () {
var _this = this;
var _a;
var headerWidths = this.treeListHeaderMatrix[0].map(function (c, i) { return _this.getTreeListColumnWidth(i); });
return (_a = headerWidths === null || headerWidths === void 0 ? void 0 : headerWidths.reduce(function (acc, v) { return acc += v; }, 0)) !== null && _a !== void 0 ? _a : 0;
};
Object.defineProperty(GanttExportCalculator.prototype, "chartWidth", {
get: function () {
var _this = this;
if (!this._chartWidth) {
var row = this.chartTableScaleBottomMatrix[0];
this._chartWidth = row.reduce(function (acc, v) {
return acc += v.styles.cellWidth.hasValue() ? v.styles.cellWidth.getValue() : _this.baseCellWidth;
}, 0);
}
return this._chartWidth;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "settingsForPaging", {
get: function () {
if (!this._settingsForPaging) {
this._settingsForPaging = new Props_1.GanttPdfExportProps(this._props);
this.prepareAutoFormat(this._settingsForPaging);
this.scalingHelper.scalePageMargins(this._settingsForPaging);
}
return this._settingsForPaging;
},
enumerable: false,
configurable: true
});
GanttExportCalculator.prototype.prepareAutoFormat = function (settings) {
if (settings.format === Props_1.GanttPdfExportProps.autoFormatKey) {
settings.format = null;
var landscape = settings.landscape;
var width = this.autoFormatWidth;
var height = this.autoFormatHeight;
var rotateLanscape = (landscape && height > width) || (!landscape && height < width);
if (rotateLanscape)
settings.landscape = !landscape;
settings.pageSize = new size_1.Size(width, height);
}
};
Object.defineProperty(GanttExportCalculator.prototype, "autoFormatWidth", {
get: function () {
var _a;
var mode = ((_a = this._props) === null || _a === void 0 ? void 0 : _a.exportMode) || Props_1.ExportMode.all;
var hasChart = mode !== Props_1.ExportMode.treeList;
var width = this.pageRightMargin;
if (hasChart)
width += this.chartLeft + this.chartWidth;
else
width += this.treeListLeft + this.treeListWidth;
return width + GanttExportCalculator._autoFormatWidthAddStock;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "autoFormatHeight", {
get: function () {
return this.mainTableTop + this.mainTableHeight + this.pageBottomMargin;
},
enumerable: false,
configurable: true
});
GanttExportCalculator.prototype.createGlobalInfo = function () {
var info = {
objects: this._canExportChart() ? this.getGanttObjectsInfo() : null,
tables: this.getTablesInfo()
};
this.scalingHelper.scaleSizes(info);
return info;
};
GanttExportCalculator.prototype.getTablesInfo = function () {
var info = {};
if (this._canExportTreelist()) {
info[Interfaces_1.PdfPageTableNames.treeListHeader] = this.createTreeListHeaderTableInfo();
info[Interfaces_1.PdfPageTableNames.treeListMain] = this.createTreeListMainTableInfo();
}
if (this._canExportChart()) {
info[Interfaces_1.PdfPageTableNames.chartMain] = this.createChartMainTableInfo();
info[Interfaces_1.PdfPageTableNames.chartScaleTop] = this._createChartScaleTopInfo();
info[Interfaces_1.PdfPageTableNames.chartScaleBottom] = this._createChartScaleBottomInfo();
}
return info;
};
Object.defineProperty(GanttExportCalculator.prototype, "exportMode", {
get: function () {
var _a, _b;
return (_b = (_a = this._props) === null || _a === void 0 ? void 0 : _a.exportMode) !== null && _b !== void 0 ? _b : Props_1.ExportMode.all;
},
enumerable: false,
configurable: true
});
GanttExportCalculator.prototype._canExportTreelist = function () {
return this.exportMode === Props_1.ExportMode.all || this.exportMode === Props_1.ExportMode.treeList;
};
GanttExportCalculator.prototype._canExportChart = function () {
return this.exportMode === Props_1.ExportMode.all || this.exportMode === Props_1.ExportMode.chart;
};
Object.defineProperty(GanttExportCalculator.prototype, "_predefinedFont", {
get: function () {
var _a, _b;
var font = (_b = (_a = this._props) === null || _a === void 0 ? void 0 : _a.pdfDoc) === null || _b === void 0 ? void 0 : _b.getFont();
return font === null || font === void 0 ? void 0 : font.fontName;
},
enumerable: false,
configurable: true
});
GanttExportCalculator.prototype._createChartScaleTopInfo = function () {
return {
name: Interfaces_1.PdfPageTableNames.chartScaleTop,
size: new size_1.Size(this.chartWidth, this.taskAreaHelper.headerRowHeight),
position: new point_1.Point(this.chartLeft, this.headerTableTop),
style: this.chartScaleTableStyle,
baseCellSize: new size_1.Size(this.baseCellWidth, this.taskAreaHelper.headerRowHeight),
cells: this.chartTableScaleTopMatrix
};
};
GanttExportCalculator.prototype._createChartScaleBottomInfo = function () {
var rowHeight = this.taskAreaHelper.headerRowHeight;
return {
name: Interfaces_1.PdfPageTableNames.chartScaleBottom,
size: new size_1.Size(this.chartWidth, rowHeight),
position: new point_1.Point(this.chartLeft, this.headerTableTop + rowHeight),
style: this.chartScaleTableStyle,
baseCellSize: new size_1.Size(this.baseCellWidth, rowHeight),
cells: this.chartTableScaleBottomMatrix
};
};
GanttExportCalculator.prototype.createChartMainTableInfo = function () {
var info = {
name: Interfaces_1.PdfPageTableNames.chartMain,
size: new size_1.Size(this.chartWidth, this.mainTableHeight),
position: new point_1.Point(this.chartLeft, this.mainTableTop),
style: this.chartMainTableStyle,
baseCellSize: new size_1.Size(this.baseCellWidth, this.baseCellHeight),
cells: this.chartTableBodyMatrix,
hideRowLines: !this._owner.settings.areHorizontalBordersEnabled
};
return info;
};
GanttExportCalculator.prototype.createTreeListHeaderTableInfo = function () {
var info = {
name: Interfaces_1.PdfPageTableNames.treeListHeader,
size: new size_1.Size(this.treeListWidth, this.headerTableHeight),
position: new point_1.Point(this.treeListLeft, this.headerTableTop),
style: this.treeListTableStyle,
baseCellSize: new size_1.Size(null, this.headerTableHeight),
cells: this.treeListHeaderMatrix
};
return info;
};
GanttExportCalculator.prototype.createTreeListMainTableInfo = function () {
var info = {
name: Interfaces_1.PdfPageTableNames.treeListMain,
size: new size_1.Size(this.treeListWidth, this.mainTableHeight),
position: new point_1.Point(this.treeListLeft, this.mainTableTop),
style: this.treeListTableStyle,
baseCellSize: new size_1.Size(null, this.baseCellHeight),
cells: this.treeListBodyMatrix,
hideRowLines: !this._owner.settings.areHorizontalBordersEnabled
};
return info;
};
GanttExportCalculator.prototype.calculateChartScaleMatrix = function (index) {
var helper = this.taskAreaHelper;
var ranges = helper.scaleRanges;
var row = new Array();
var start = ranges[index][0];
var end = ranges[index][1];
for (var j = start; j <= end; j++) {
var start_1 = this.layoutCalculator.getScaleItemStart(j, helper.scales[index]);
var cell = new CellDef_1.CellDef(this._owner.renderHelper.getScaleItemTextByStart(start_1, helper.scales[index]));
cell.styles.cellPadding.assign(0);
cell.styles.minCellHeight = this.taskAreaHelper.headerRowHeight;
var cellWidth = index === 0 ? helper.scaleTopWidths[j] : helper.scaleBottomWidths[j];
cell.styles.cellWidth.assign(cellWidth);
row.push(cell);
}
return [row];
};
GanttExportCalculator.prototype.calculateChartTableBodyMatrix = function () {
var _this = this;
this._chartTableBodyMatrix = new Array();
this.visibleTaskIndices.forEach(function (i) { return _this._chartTableBodyMatrix.push(_this.createChartTableBodyRow(i)); });
};
GanttExportCalculator.prototype.createChartTableBodyRow = function (index) {
var etalon = new CellDef_1.CellDef();
if (this.rowHasChildren(index))
etalon.styles.fillColor.assign(this.taskAreaHelper.parentRowBackColor);
return this.chartTableScaleBottomMatrix[0].map(function (c) {
var cell = new CellDef_1.CellDef(etalon);
cell.styles.cellWidth.assign(c.styles.cellWidth);
return cell;
});
};
GanttExportCalculator.prototype.rowHasSelection = function (index) {
return this._owner.rowHasSelection(index);
};
GanttExportCalculator.prototype.rowHasChildren = function (index) {
return this._owner.rowHasChildren(index);
};
GanttExportCalculator.prototype.calculateTreeListTableHeaderMatrix = function () {
this._treeListHeaderMatrix = new Array();
var owner = this._owner;
var colCount = owner.getTreeListColCount();
var row = new Array();
for (var j = 0; j < colCount; j++) {
var cell = new CellDef_1.CellDef(owner.getTreeListHeaderInfo(j));
cell.styles.minCellHeight = 2 * this.taskAreaHelper.headerRowHeight;
row.push(cell);
}
this._treeListHeaderMatrix.push(row);
};
GanttExportCalculator.prototype.calculateTreeListTableBodyMatrix = function () {
this._treeListBodyMatrix = new Array();
var visibleTaskIndices = this.visibleTaskIndices;
var colCount = this.treeListHeaderMatrix[0].length;
for (var i = 0; i < visibleTaskIndices.length; i++) {
var row = new Array();
for (var j = 0; j < colCount; j++) {
var cell = new CellDef_1.CellDef(this._owner.getTreeListCellInfo(visibleTaskIndices[i], j));
if (!cell.styles.cellWidth.hasValue())
cell.styles.cellWidth.assign(this.getTreeListColumnWidth(j));
if (this.rowHasChildren(visibleTaskIndices[i]))
cell.styles.fillColor.assign(this.taskAreaHelper.parentRowBackColor);
row.push(cell);
}
this._treeListBodyMatrix.push(row);
}
};
GanttExportCalculator.prototype.getTreeListColumnWidth = function (colIndex) {
var info = this.treeListHeaderMatrix[0][colIndex];
var style = info && info.styles;
var numWidth = style.cellWidth.getValue();
return numWidth || style.minCellWidth || 0;
};
GanttExportCalculator.prototype.getObjectsLeftOffset = function (isTask) {
if (isTask === void 0) { isTask = false; }
var offset = this.dataObjectLeftDelta;
if (!isTask)
offset += this.taskAreaHelper.customRangeLeftOffset;
return offset;
};
Object.defineProperty(GanttExportCalculator.prototype, "dataObjectLeftDelta", {
get: function () {
var _a;
(_a = this._dataObjectLeftDelta) !== null && _a !== void 0 ? _a : (this._dataObjectLeftDelta = this.getDataObjectLeftDelta());
return this._dataObjectLeftDelta;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "dataObjectTopDelta", {
get: function () {
var _a;
(_a = this._dataObjectTopDelta) !== null && _a !== void 0 ? _a : (this._dataObjectTopDelta = this.getDataObjectTopDelta());
return this._dataObjectTopDelta;
},
enumerable: false,
configurable: true
});
GanttExportCalculator.prototype.getChartScaleTableStyle = function () {
var style = new StyleDef_1.StyleDef(this.taskAreaHelper.scaleTableStyle);
if (this._predefinedFont)
style.font = this._predefinedFont;
return style;
};
GanttExportCalculator.prototype.getChartMainTableStyle = function () {
var style = new StyleDef_1.StyleDef(this.taskAreaHelper.chartMainTableStyle);
if (this._predefinedFont)
style.font = this._predefinedFont;
return style;
};
GanttExportCalculator.prototype.calculateTreeListTableStyle = function () {
this._treeListTableStyle = new StyleDef_1.StyleDef(this._owner.getTreeListTableStyle());
this._treeListTableStyle.fillColor.assign(this.chartMainTableStyle.fillColor);
this._treeListTableStyle.lineColor.assign(this.chartMainTableStyle.lineColor);
if (this._predefinedFont)
this._treeListTableStyle.font = this._predefinedFont;
};
GanttExportCalculator.prototype.getGanttObjectsInfo = function () {
return {
tasks: this.tasksInfo,
dependencies: this.dependenciesInfo,
resources: this.resourcesInfo,
timeMarkers: this.timeMarkersInfo
};
};
Object.defineProperty(GanttExportCalculator.prototype, "tasksInfo", {
get: function () {
var _a;
(_a = this._tasksInfo) !== null && _a !== void 0 ? _a : (this._tasksInfo = this.calculateTasksInfo());
return this._tasksInfo;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "dependenciesInfo", {
get: function () {
var _a;
(_a = this._dependenciesInfo) !== null && _a !== void 0 ? _a : (this._dependenciesInfo = this.calculateDependenciesInfo());
return this._dependenciesInfo;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "resourcesInfo", {
get: function () {
var _a;
(_a = this._resourcesInfo) !== null && _a !== void 0 ? _a : (this._resourcesInfo = this.calculateResourcesInfo());
return this._resourcesInfo;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttExportCalculator.prototype, "timeMarkersInfo", {
get: function () {
var _a;
(_a = this._timeMarkersInfo) !== null && _a !== void 0 ? _a : (this._timeMarkersInfo = this.calculateTimeMarkersInfoInfo());
return this._timeMarkersInfo;
},
enumerable: false,
configurable: true
});
GanttExportCalculator.prototype.getDataObjectLeftDelta = function () {
return this.chartLeft - this.taskAreaHelper.objectsLeftDelta;
};
GanttExportCalculator.prototype.getDataObjectTopDelta = function () {
return this.headerTableTop + this.headerTableHeight - this.taskAreaHelper.objectsTopDelta;
};
GanttExportCalculator.prototype.calculateTasksInfo = function () {
var _this = this;
var result = new Array();
this.visibleTaskIndices.forEach(function (i) { return result.push(_this.calculateTaskInfo(i)); });
return result;
};
GanttExportCalculator.prototype.calculateTaskInfo = function (index) {
var info = new TaskInfo_1.PdfTaskInfo();
var taskElementInfo = this.layoutCalculator.getTaskElementInfo(index);
info.taskColor = this.getTaskColor(index);
info.sidePoints = this.getTaskSidePoints(index);
info.isMilestone = taskElementInfo.className.indexOf(GridLayoutCalculator_1.GridLayoutCalculator.milestoneClassName) > 0;
if (!info.isMilestone) {
info.isSmallTask = taskElementInfo.className.indexOf(GridLayoutCalculator_1.GridLayoutCalculator.smallTaskClassName) > 0;
info.isParent = taskElementInfo.className.indexOf(GridLayoutCalculator_1.GridLayoutCalculator.parentTaskClassName) > 0;
this.appendTaskTitle(info, index);
this.appendTaskProgress(info, index);
}
return info;
};
GanttExportCalculator.prototype.appendTaskTitle = function (info, index) {
var textPosition = this._owner.settings.taskTitlePosition;
var isTextHidden = info.isSmallTask && textPosition !== Enums_1.TaskTitlePosition.Outside || textPosition === Enums_1.TaskTitlePosition.None;
if (!isTextHidden) {
info.text = this._owner.getTaskText(index);
info.textPosition = textPosition;
info.textStyle = this.getTaskTextStyle(index);
}
};
GanttExportCalculator.prototype.appendTaskProgress = function (info, index) {
var progressInfo = this.layoutCalculator.getTaskProgressElementInfo(index);
info.progressWidth = progressInfo.size.width;
info.progressColor = this.getTaskProgressColor(index);
info.progressColor.applyOpacityToBackground(info.taskColor);
};
GanttExportCalculator.prototype.getTaskSidePoints = function (index) {
var _this = this;
var points = this.layoutCalculator.getTaskSidePoints(index);
points.forEach(function (p) {
p.x += _this.getObjectsLeftOffset(true);
p.y += _this.dataObjectTopDelta;
});
return points;
};
GanttExportCalculator.prototype.getTaskColor = function (index) {
var color = this.taskAreaHelper.getTaskElementBackColor(index, GridLayoutCalculator_1.GridLayoutCalculator.taskClassName);
return new Color_1.Color(color);
};
GanttExportCalculator.prototype.getTaskProgressColor = function (index) {
return new Color_1.Color(this.taskAreaHelper.getTaskElementBackColor(index, GridLayoutCalculator_1.GridLayoutCalculator.taskProgressClassName));
};
GanttExportCalculator.prototype.getTaskTextStyle = function (index) {
var style = new StyleDef_1.StyleDef();
style.cellPadding.assign(0);
style.assign(this.taskAreaHelper.getTaskElementStyle(index, GridLayoutCalculator_1.GridLayoutCalculator.taskTitleClassName));
return style;
};
GanttExportCalculator.prototype.calculateDependenciesInfo = function () {
var _this = this;
var result = new Array();
var helper = this.taskAreaHelper;
var fillColor = new Color_1.Color(helper.dependencyColor);
helper.connectorLines.forEach(function (line) { return result.push(_this.createLineInfo(line, fillColor, helper.arrowWidth)); });
return result;
};
GanttExportCalculator.prototype.createLineInfo = function (line, fillColor, arrowWidth) {
var info = new DependencyLineInfo_1.PdfDependencyLineInfo();
info.fillColor = fillColor;
var isArrow = line.className.indexOf(GridLayoutCalculator_1.GridLayoutCalculator.arrowClassName) > -1;
if (isArrow) {
var position = this.layoutCalculator.getArrowPositionByClassName(line.className);
info.arrowInfo = { position: position, width: arrowWidth };
info.points = [this.getArrowTopCorner(line, position, arrowWidth)];
}
else
info.points = this.getLinePoints(line);
return info;
};
GanttExportCalculator.prototype.getArrowTopCorner = function (info, position, width) {
var x = info.position.x + this.getObjectsLeftOffset();
var y = info.position.y + this.dataObjectTopDelta;
switch (position) {
case Enums_1.Position.Left:
x += width;
break;
case Enums_1.Position.Top:
y += width;
}
return new point_1.Point(x, y);
};
GanttExportCalculator.prototype.getLinePoints = function (line) {
var x1 = line.position.x + this.getObjectsLeftOffset();
var y1 = line.position.y + this.dataObjectTopDelta;
var x2 = x1 + line.size.width;
var y2 = y1 + line.size.height;
return [new point_1.Point(x1, y1), new point_1.Point(x2, y2)];
};
GanttExportCalculator.prototype.calculateResourcesInfo = function () {
var _this = this;
var result = new Array();
this.taskAreaHelper.resourcesElements.forEach(function (rw) { return result = result.concat(_this.calculateResourcesInLine(rw)); });
return result;
};
GanttExportCalculator.prototype.calculateResourcesInLine = function (wrapper) {
var result = new Array();
if (wrapper) {
var left = dom_1.DomUtils.pxToInt(wrapper.style.left) + this.getObjectsLeftOffset();
var top_1 = dom_1.DomUtils.pxToInt(wrapper.style.top) + this.dataObjectTopDelta;
var resources = wrapper.getElementsByClassName(GridLayoutCalculator_1.GridLayoutCalculator.taskResourceClassName);
for (var i = 0; i < resources.length; i++) {
var resource = resources[i];
var style = getComputedStyle(resource);
left += this.getMargin(style).left;
result.push(new TaskResourcesInfo_1.PdfTaskResourcesInfo(resource.textContent, new StyleDef_1.StyleDef(style), left, top_1));
left += dom_1.DomUtils.pxToInt(style.width);
}
}
return result;
};
GanttExportCalculator.prototype.calculateTimeMarkersInfoInfo = function () {
var _this = this;
var result = new Array();
var stripLines = this.taskAreaHelper.stripLinesElements;
stripLines.forEach(function (s) { return result.push(_this.createTimeMarkerInfo(s, true)); });
var noWorkIntervals = this.taskAreaHelper.noWorkingIntervalsElements;
noWorkIntervals.forEach(function (s) { return result.push(_this.createTimeMarkerInfo(s, false)); });
return result;
};
GanttExportCalculator.prototype.createTimeMarkerInfo = function (element, isStripLine) {
var style = getComputedStyle(element);
var left = dom_1.DomUtils.pxToInt(style.left) + this.getObjectsLeftOffset();
var top = dom_1.DomUtils.pxToInt(style.top) + this.dataObjectTopDelta;
var width = dom_1.DomUtils.pxToInt(style.width);
var height = dom_1.DomUtils.pxToInt(style.height);
return new TimeMarkerInfo_1.PdfTimeMarkerInfo(new point_1.Point(left, top), new size_1.Size(width, height), new Color_1.Color(style.backgroundColor), new Color_1.Color(style.borderLeftColor), isStripLine);
};
GanttExportCalculator.prototype.getMargin = function (style) {
var margin = new Margin_1.Margin(0);
if (style) {
var marginCss = style.margin;
if (!marginCss) {
marginCss += style.marginTop || "0";
marginCss += " " + style.marginRight || false;
marginCss += " " + style.marginBottom || false;
marginCss += " " + style.marginLeft || false;
}
margin.assign(marginCss);
}
return margin;
};
GanttExportCalculator._defaultPageMargin = 10;
GanttExportCalculator._autoFormatWidthAddStock = 1;
return GanttExportCalculator;
}());
exports.GanttExportCalculator = GanttExportCalculator;
/***/ }),
/* 168 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskAreaExportHelper = void 0;
var dom_1 = __webpack_require__(3);
var DateRange_1 = __webpack_require__(14);
var GridLayoutCalculator_1 = __webpack_require__(16);
var DateUtils_1 = __webpack_require__(21);
var Props_1 = __webpack_require__(54);
var Color_1 = __webpack_require__(17);
var TaskAreaExportHelper = (function () {
function TaskAreaExportHelper(owner, props) {
this._owner = owner;
this._props = props;
}
Object.defineProperty(TaskAreaExportHelper.prototype, "customRangeLeftOffset", {
get: function () {
var _a;
(_a = this._customRangeLeftOffset) !== null && _a !== void 0 ? _a : (this._customRangeLeftOffset = Math.max(this.layoutCalculator.getWidthByDateRange(this.startDate, this.ownerStartDate), 0));
return this._customRangeLeftOffset;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "baseCellSize", {
get: function () { return this._owner.tickSize; },
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "objectsLeftDelta", {
get: function () {
return this.renderedScaleLeft;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "objectsTopDelta", {
get: function () {
var firstIndex = this.visibleTaskIndices[0];
return this.getCellTop(firstIndex) + this.getTaskCellOffsetTop(firstIndex);
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "offsetLeft", {
get: function () {
var _a;
(_a = this._offsetLeft) !== null && _a !== void 0 ? _a : (this._offsetLeft = Math.max(this.visibleLeft - this.renderedScaleLeft, 0));
return this._offsetLeft;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "offsetTop", {
get: function () {
var _a;
(_a = this._offsetTop) !== null && _a !== void 0 ? _a : (this._offsetTop = this.getOffsetTop());
return this._offsetTop;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "scales", {
get: function () {
var viewType = this.settings.viewType;
return [DateUtils_1.DateUtils.ViewTypeToScaleMap[viewType], viewType];
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "scaleRanges", {
get: function () {
var _a;
(_a = this._scaleRanges) !== null && _a !== void 0 ? _a : (this._scaleRanges = this.layoutCalculator.getScaleRangesInArea(this.scaleLeft, this.scaleRight));
return this._scaleRanges;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "scaleBottomStartIndex", {
get: function () {
return this.scaleRanges[1][0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "scaleBottomEndIndex", {
get: function () {
return this.scaleRanges[1][1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "scaleTopStartIndex", {
get: function () {
return this.scaleRanges[0][0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "scaleTopEndIndex", {
get: function () {
return this.scaleRanges[0][1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "scaleTopWidths", {
get: function () {
var _a;
(_a = this._scaleTopWidths) !== null && _a !== void 0 ? _a : (this._scaleTopWidths = this.getScaleTopWidths());
return this._scaleTopWidths;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "scaleBottomWidths", {
get: function () {
var _a;
(_a = this._scaleBottomWidths) !== null && _a !== void 0 ? _a : (this._scaleBottomWidths = this.getScaleBottomWidths());
return this._scaleBottomWidths;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "headerRowHeight", {
get: function () {
if (!this._headerRowHeight) {
var element = this.scaleElements[0].filter(function (el) { return !!el; })[0];
this._headerRowHeight = element === null || element === void 0 ? void 0 : element.offsetHeight;
}
return this._headerRowHeight;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "visibleTaskIndices", {
get: function () {
var _a;
(_a = this._visibleTaskIndices) !== null && _a !== void 0 ? _a : (this._visibleTaskIndices = this.getTaskIndices());
return this._visibleTaskIndices;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "scaleTableStyle", {
get: function () {
var _a;
(_a = this._scaleTableStyle) !== null && _a !== void 0 ? _a : (this._scaleTableStyle = this.getScaleTableStyle());
return this._scaleTableStyle;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "chartMainTableStyle", {
get: function () {
var _a;
(_a = this._chartMainTableStyle) !== null && _a !== void 0 ? _a : (this._chartMainTableStyle = this.getChartMainTableStyle());
return this._chartMainTableStyle;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "parentRowBackColor", {
get: function () {
var _a;
(_a = this._parentRowBackColor) !== null && _a !== void 0 ? _a : (this._parentRowBackColor = this.getParentBackColor());
return this._parentRowBackColor;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "arrowWidth", {
get: function () {
var _a;
(_a = this._arrowWidth) !== null && _a !== void 0 ? _a : (this._arrowWidth = this.getArrowWidth());
return this._arrowWidth;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "dependencyColor", {
get: function () {
var _a;
(_a = this._dependencyColor) !== null && _a !== void 0 ? _a : (this._dependencyColor = this.getDependencyColor());
return this._dependencyColor;
},
enumerable: false,
configurable: true
});
TaskAreaExportHelper.prototype.getTaskElementBackColor = function (taskIndex, className) {
var style = this.getTaskElementStyle(taskIndex, className);
return style === null || style === void 0 ? void 0 : style.backgroundColor;
};
TaskAreaExportHelper.prototype.getTaskElementStyle = function (taskIndex, className) {
var taskWrapper = this.getTaskWrapper(taskIndex);
return this.getElementStyle(taskWrapper.getElementsByClassName(className)[0]);
};
Object.defineProperty(TaskAreaExportHelper.prototype, "visibleLeft", {
get: function () {
var _a;
(_a = this._visibleLeft) !== null && _a !== void 0 ? _a : (this._visibleLeft = this.isVisibleMode ? this.container.scrollLeft : 0);
return this._visibleLeft;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "visibleTop", {
get: function () {
var _a;
(_a = this._visibleTop) !== null && _a !== void 0 ? _a : (this._visibleTop = this.isVisibleMode ? this.container.scrollTop : 0);
return this._visibleTop;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "visibleRight", {
get: function () {
var _a;
(_a = this._visibleRight) !== null && _a !== void 0 ? _a : (this._visibleRight = this.getVisibleRight());
return this._visibleRight;
},
enumerable: false,
configurable: true
});
TaskAreaExportHelper.prototype.getVisibleRight = function () {
var width = this.container.getElement().offsetWidth;
return this.visibleLeft + width;
};
Object.defineProperty(TaskAreaExportHelper.prototype, "visibleBottom", {
get: function () {
var _a;
(_a = this._visibleBottom) !== null && _a !== void 0 ? _a : (this._visibleBottom = this.getVisibleBottom());
return this._visibleBottom;
},
enumerable: false,
configurable: true
});
TaskAreaExportHelper.prototype.getVisibleBottom = function () {
if (!this.isVisibleMode)
return this.visibleTaskIndices.length * this.baseCellSize.height;
return this.visibleTop + this.container.getHeight();
};
Object.defineProperty(TaskAreaExportHelper.prototype, "scaleLeft", {
get: function () {
var _a;
(_a = this._scaleLeft) !== null && _a !== void 0 ? _a : (this._scaleLeft = this.isVisibleMode ? this.visibleLeft : this.getPosByDate(this.startDate));
return this._scaleLeft;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "scaleRight", {
get: function () {
var _a;
(_a = this._scaleRight) !== null && _a !== void 0 ? _a : (this._scaleRight = this.isVisibleMode ? this.visibleRight : this.getPosByDate(this.endDate) - 1);
return this._scaleRight;
},
enumerable: false,
configurable: true
});
TaskAreaExportHelper.prototype.getScaleTopWidths = function () {
var widths = this.getScaleWidths(this.scaleTopStartIndex, this.scaleTopEndIndex, this.scales[0]);
var calc = this.layoutCalculator;
var firstBottom = calc.getScaleItemInfo(this.scaleBottomStartIndex, this.scales[1]);
var firstTop = calc.getScaleItemInfo(this.scaleTopStartIndex, this.scales[0]);
var delta = Math.max(firstBottom.position.x - firstTop.position.x, 0);
widths[this.scaleTopStartIndex] -= delta;
var lastTop = calc.getScaleItemInfo(this.scaleTopEndIndex, this.scales[0]);
var lastBottom = calc.getScaleItemInfo(this.scaleBottomEndIndex, this.scales[1]);
delta = Math.max(lastTop.position.x + lastTop.size.width - lastBottom.position.x - lastBottom.size.width, 0);
widths[this.scaleTopEndIndex] -= delta;
return widths;
};
TaskAreaExportHelper.prototype.getScaleBottomWidths = function () {
return this.getScaleWidths(this.scaleBottomStartIndex, this.scaleBottomEndIndex, this.scales[1]);
};
TaskAreaExportHelper.prototype.getScaleWidths = function (start, end, scaleType) {
var widths = new Array();
for (var i = start; i <= end; i++)
widths[i] = this.layoutCalculator.getScaleItemInfo(i, scaleType).size.width;
return widths;
};
TaskAreaExportHelper.prototype.getOffsetTop = function () {
return this.isVisibleMode ? this.getTaskCellOffsetTop(this.visibleTaskIndices[0]) : 0;
};
Object.defineProperty(TaskAreaExportHelper.prototype, "renderedScaleLeft", {
get: function () {
return this.getCellLeft(this.scaleBottomStartIndex);
},
enumerable: false,
configurable: true
});
TaskAreaExportHelper.prototype.getTaskCellOffsetTop = function (taskIndex) {
var point = this.getCellTop(taskIndex);
return Math.max(this.visibleTop - point, 0);
};
TaskAreaExportHelper.prototype.getCellTop = function (index) {
var point = this.layoutCalculator.getGridBorderPosition(index - 1, false);
return point.y;
};
TaskAreaExportHelper.prototype.getCellLeft = function (index) {
var point = this.layoutCalculator.getScaleItemInfo(index, this.scales[1]).position;
return point.x;
};
TaskAreaExportHelper.prototype.getTaskIndices = function () {
var _a, _b;
if (this.dataMode === Props_1.DataExportMode.all || this.exportRange)
return this._owner.getAllVisibleTaskIndices((_a = this.exportRange) === null || _a === void 0 ? void 0 : _a.startIndex, (_b = this.exportRange) === null || _b === void 0 ? void 0 : _b.endIndex);
return this.getVisibleTaskIndices();
};
TaskAreaExportHelper.prototype.getVisibleTaskIndices = function () {
var _this = this;
var indices = [];
this.taskElements.forEach(function (t, i) {
if (t) {
var taskTop = dom_1.DomUtils.pxToInt(t.style.top);
var taskBottom = taskTop + t.offsetHeight;
var topInArea = taskTop >= _this.visibleTop && taskTop <= _this.visibleBottom;
var bottomInArea = taskBottom >= _this.visibleTop && taskBottom <= _this.visibleBottom;
if (topInArea || bottomInArea)
indices.push(i);
}
});
return indices;
};
Object.defineProperty(TaskAreaExportHelper.prototype, "scaleElements", {
get: function () {
return this._owner.renderHelper.scaleElements.slice();
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "scaleBorders", {
get: function () {
return this._owner.renderHelper.scaleBorders.slice();
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "hlRowElements", {
get: function () {
return this._owner.renderHelper.hlRowElements.filter(function (el) { return !!el; });
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "selectionElements", {
get: function () {
return this._owner.renderHelper.selectionElements.filter(function (el) { return !!el; });
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "taskElements", {
get: function () {
return this._owner.renderHelper.taskElements;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "connectorLines", {
get: function () {
var _this = this;
var _a;
(_a = this._connectorLines) !== null && _a !== void 0 ? _a : (this._connectorLines = this._owner.renderHelper.renderedConnectorLines.filter(function (l) { return _this.isLineVisible(l); }));
return this._connectorLines;
},
enumerable: false,
configurable: true
});
TaskAreaExportHelper.prototype.isLineVisible = function (line) {
if (this.dataMode === Props_1.DataExportMode.all)
return true;
var id = line.attr["dependency-id"];
return this.visibleDependencyKeys.indexOf(id) > -1;
};
Object.defineProperty(TaskAreaExportHelper.prototype, "visibleDependencyKeys", {
get: function () {
var _a;
(_a = this._visibleDependencyKeys) !== null && _a !== void 0 ? _a : (this._visibleDependencyKeys = this._owner.getVisibleDependencyKeysByTaskRange(this.visibleTaskIndices));
return this._visibleDependencyKeys;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "resourcesElements", {
get: function () {
var _this = this;
var _a;
(_a = this._resourcesElements) !== null && _a !== void 0 ? _a : (this._resourcesElements = this.visibleTaskIndices.map(function (tIndex) { return _this._owner.renderHelper.resourcesElements[tIndex]; }).filter(function (r) { return r && r.parentElement; }));
return this._resourcesElements;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "stripLinesElements", {
get: function () {
if (!this._stripLinesElements) {
var elements = this._owner.renderHelper.stripLinesMap.filter(function (s) { return !!s; }).map(function (s) { return s; });
this._stripLinesElements = elements.map(function (e) { return e; });
}
return this._stripLinesElements;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "noWorkingIntervalsElements", {
get: function () {
if (!this._noWorkingIntervalsElements) {
this._noWorkingIntervalsElements = [];
var hash = this._owner.renderHelper.noWorkingIntervalsToElementsMap;
for (var key in hash) {
if (!Object.prototype.hasOwnProperty.call(hash, key))
continue;
this._noWorkingIntervalsElements.push(hash[key]);
}
}
return this._noWorkingIntervalsElements;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "taskArea", {
get: function () {
return this._owner.renderHelper.taskArea;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "settings", {
get: function () { return this._owner.settings; },
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "dataMode", {
get: function () {
var _a;
return (_a = this._props) === null || _a === void 0 ? void 0 : _a.exportDataMode;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "exportRange", {
get: function () {
var _a;
return (_a = this._props) === null || _a === void 0 ? void 0 : _a.dateRange;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "isVisibleMode", {
get: function () {
return this.dataMode === Props_1.DataExportMode.visible && !this.exportRange;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "ownerStartDate", {
get: function () {
return this._owner.range.start;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "ownerEndDate", {
get: function () {
return this._owner.range.end;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "startDate", {
get: function () {
var _a, _b, _c, _d;
if (((_a = this.exportRange) === null || _a === void 0 ? void 0 : _a.startDate) && ((_b = this.exportRange) === null || _b === void 0 ? void 0 : _b.endDate)) {
var min = Math.min((_c = this.exportRange) === null || _c === void 0 ? void 0 : _c.startDate.getTime(), (_d = this.exportRange) === null || _d === void 0 ? void 0 : _d.endDate.getTime());
return new Date(min);
}
return this.ownerStartDate;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "endDate", {
get: function () {
var _a, _b, _c, _d;
if (((_a = this.exportRange) === null || _a === void 0 ? void 0 : _a.startDate) && ((_b = this.exportRange) === null || _b === void 0 ? void 0 : _b.endDate)) {
var max = Math.max((_c = this.exportRange) === null || _c === void 0 ? void 0 : _c.startDate.getTime(), (_d = this.exportRange) === null || _d === void 0 ? void 0 : _d.endDate.getTime());
return new Date(max);
}
return this.ownerEndDate;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "hasCustomRangeOutOfRender", {
get: function () {
return this.startDate.getTime() < this.ownerStartDate.getTime() || this.endDate.getTime() > this.ownerEndDate.getTime();
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "layoutCalculator", {
get: function () {
if (!this._layoutCalculator) {
var calc = this._owner.renderHelper.gridLayoutCalculator;
if (this.hasCustomRangeOutOfRender) {
this._layoutCalculator = new GridLayoutCalculator_1.GridLayoutCalculator();
this._layoutCalculator.setSettings(calc.visibleTaskAreaSize, calc.tickSize, calc.elementSizeValues, new DateRange_1.DateRange(this.startDate, this.endDate), calc.viewModel, calc.viewType, calc.scrollBarHeight, this._owner.settings.firstDayOfWeek);
}
else
this._layoutCalculator = calc;
}
return this._layoutCalculator;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaExportHelper.prototype, "container", {
get: function () {
return this._owner.renderHelper.taskAreaContainer;
},
enumerable: false,
configurable: true
});
TaskAreaExportHelper.prototype.getPosByDate = function (date) {
return this.layoutCalculator.getPosByDate(date);
};
TaskAreaExportHelper.prototype.getScaleTableStyle = function () {
var result = {};
var visibleScaleItem = this.scaleElements[0].filter(function (el) { return !!el; })[0];
var style = this.getElementStyle(visibleScaleItem);
result["backgroundColor"] = this.findElementBackColor(visibleScaleItem);
result["borderColor"] = this.getChartTableBorderColor();
result["verticalAlign"] = "middle";
result["textAlign"] = "center";
result["fontSize"] = style.fontSize;
result["fontFamily"] = style.fontFamily;
result["fontWeight"] = style.fontWeight;
result["fontStyle"] = style.fontStyle;
result["color"] = style.color;
return result;
};
TaskAreaExportHelper.prototype.getChartMainTableStyle = function () {
var result = {};
result["backgroundColor"] = this.findElementBackColor(this.taskArea);
result["borderColor"] = this.getChartTableBorderColor();
return result;
};
TaskAreaExportHelper.prototype.findElementBackColor = function (element) {
if (!element)
return null;
var parent = element;
var color = new Color_1.Color("transparent");
while (color.opacity === 0 && parent) {
var style = this.getElementStyle(parent);
color.assign(style.backgroundColor);
parent = parent.parentElement;
}
return color;
};
TaskAreaExportHelper.prototype.getChartTableBorderColor = function () {
var style = this.getElementStyle(this.scaleBorders[0].filter(function (el) { return !!el; })[0]);
return style === null || style === void 0 ? void 0 : style.borderColor;
};
TaskAreaExportHelper.prototype.getParentBackColor = function () {
var style = this.getElementStyle(this.hlRowElements[0]);
return style === null || style === void 0 ? void 0 : style.backgroundColor;
};
TaskAreaExportHelper.prototype.getArrowWidth = function () {
var style = this.getDependencyLineStyle(GridLayoutCalculator_1.GridLayoutCalculator.arrowClassName);
var borderWidth = style.borderWidth || style.borderLeftWidth || style.borderRightWidth || style.borderTopWidth || style.borderBottomWidth;
return style && dom_1.DomUtils.pxToInt(borderWidth);
};
TaskAreaExportHelper.prototype.getDependencyColor = function () {
var style = this.getDependencyLineStyle(GridLayoutCalculator_1.GridLayoutCalculator.CLASSNAMES.CONNECTOR_HORIZONTAL);
return style === null || style === void 0 ? void 0 : style.borderColor;
};
TaskAreaExportHelper.prototype.getDependencyLineStyle = function (className) {
return this.getElementStyle(this.taskArea.getElementsByClassName(className)[0]);
};
TaskAreaExportHelper.prototype.getElementStyle = function (element) {
return element && getComputedStyle(element);
};
TaskAreaExportHelper.prototype.getTaskWrapper = function (index) {
if (this.isTaskTemplateMode)
return this._owner.renderHelper.fakeTaskWrapper;
if (!this.taskElements[index])
this._owner.renderHelper.createDefaultTaskElement(index);
return this.taskElements[index];
};
Object.defineProperty(TaskAreaExportHelper.prototype, "isTaskTemplateMode", {
get: function () {
return !!this._owner.settings.taskContentTemplate;
},
enumerable: false,
configurable: true
});
return TaskAreaExportHelper;
}());
exports.TaskAreaExportHelper = TaskAreaExportHelper;
/***/ }),
/* 169 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PdfGanttPaginator = void 0;
var point_1 = __webpack_require__(4);
var size_1 = __webpack_require__(11);
var DependencyLineInfo_1 = __webpack_require__(76);
var TaskInfo_1 = __webpack_require__(52);
var TaskResourcesInfo_1 = __webpack_require__(77);
var TimeMarkerInfo_1 = __webpack_require__(79);
var Interfaces_1 = __webpack_require__(29);
var CellDef_1 = __webpack_require__(53);
var PageNavigation_1 = __webpack_require__(170);
var CellNavigationInfo = (function () {
function CellNavigationInfo(pageHorIndex, pageVerIndex, cellRowIndexOnPage, cellColIndexOnPage, cell) {
this.pageVerIndex = pageVerIndex;
this.pageHorIndex = pageHorIndex;
this.cellRowIndexOnPage = cellRowIndexOnPage;
this.cellColIndexOnPage = cellColIndexOnPage;
this.cell = cell;
}
return CellNavigationInfo;
}());
var VectorInfo = (function () {
function VectorInfo(pageIndex, globalCellIndex, pageOffset, cutSize) {
this.pageIndex = pageIndex;
this.globalCellIndex = globalCellIndex;
this.pageOffset = pageOffset;
this.cutSize = cutSize;
}
Object.defineProperty(VectorInfo.prototype, "isCutted", {
get: function () {
return this.cutSize > 0;
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorInfo.prototype, "cellIndexOnPage", {
get: function () {
return this.globalCellIndex - this.pageOffset;
},
enumerable: false,
configurable: true
});
return VectorInfo;
}());
var PdfGanttPaginator = (function () {
function PdfGanttPaginator(pdfDoc, props, globalInfo) {
this._pdfDoc = pdfDoc;
this._props = props;
this._globalInfo = globalInfo;
}
PdfGanttPaginator.prototype.getPages = function () {
delete this._pages;
this._paginateTables();
this._paginateObjects();
return this.pageMatrixToArray;
};
PdfGanttPaginator.prototype._paginateTables = function () {
this._paginateTable(Interfaces_1.PdfPageTableNames.treeListHeader);
this._paginateTable(Interfaces_1.PdfPageTableNames.treeListMain);
this._paginateTable(Interfaces_1.PdfPageTableNames.chartScaleBottom);
this._paginateTable(Interfaces_1.PdfPageTableNames.chartScaleTop);
this._paginateTable(Interfaces_1.PdfPageTableNames.chartMain);
};
PdfGanttPaginator.prototype._paginateObjects = function () {
this._paginateTasks();
this._paginateDependencies();
this._paginateResources();
this._paginateTimeMarkers();
};
Object.defineProperty(PdfGanttPaginator.prototype, "pageMatrixToArray", {
get: function () {
var _a;
var result = new Array();
(_a = this._pages) === null || _a === void 0 ? void 0 : _a.forEach(function (row) {
result = result.concat(row);
});
return result;
},
enumerable: false,
configurable: true
});
PdfGanttPaginator.prototype._paginateTasks = function () {
var _this = this;
var _a, _b;
(_b = (_a = this._globalInfo.objects) === null || _a === void 0 ? void 0 : _a.tasks) === null || _b === void 0 ? void 0 : _b.forEach(function (t) { return _this._paginateTask(t); });
};
PdfGanttPaginator.prototype._paginateDependencies = function () {
var _this = this;
var _a, _b;
(_b = (_a = this._globalInfo.objects) === null || _a === void 0 ? void 0 : _a.dependencies) === null || _b === void 0 ? void 0 : _b.forEach(function (d) {
if (d.arrowInfo)
_this._paginateArrow(d);
else
_this._paginateDependencyLine(d);
});
};
PdfGanttPaginator.prototype._paginateResources = function () {
var _this = this;
var _a, _b;
(_b = (_a = this._globalInfo.objects) === null || _a === void 0 ? void 0 : _a.resources) === null || _b === void 0 ? void 0 : _b.forEach(function (r) { return _this._paginateResource(r); });
};
PdfGanttPaginator.prototype._paginateTimeMarkers = function () {
var _this = this;
var _a, _b;
(_b = (_a = this._globalInfo.objects) === null || _a === void 0 ? void 0 : _a.timeMarkers) === null || _b === void 0 ? void 0 : _b.forEach(function (m) { return _this._paginateTimeMarker(m); });
};
PdfGanttPaginator.prototype._paginateTable = function (tableKey) {
var _a;
var table = (_a = this._globalInfo) === null || _a === void 0 ? void 0 : _a.tables[tableKey];
if (table) {
var start = this._getTableStart(table);
var matrix = this._preparePagesNavigationMatrixForTable(start, table);
var rowCount = matrix.length;
for (var i = 0; i < rowCount; i++) {
var colCount = matrix[i].length;
for (var j = 0; j < colCount; j++) {
var navInfo = matrix[i][j];
var page = this._getPage(navInfo.pageVerIndex, navInfo.pageHorIndex, true);
var tablePositionX = navInfo.pageHorIndex === start.hIndex ? start.pageX : this.pageLeft;
var tablePositionY = navInfo.pageVerIndex === start.vIndex ? start.pageY : this.pageTop;
this._setTablePositionOnPage(page, tableKey, tablePositionX, tablePositionY);
this._addCellToPage(page, tableKey, navInfo);
}
}
this._updateTableSizeOnPages(tableKey);
}
};
PdfGanttPaginator.prototype._paginateTask = function (task) {
var hOffsets = this._getTaskPagination(task);
var vOffsets = this._getTaskPagination(task, true);
for (var i = 0; i < vOffsets.length; i++)
for (var j = 0; j < hOffsets.length; j++) {
var newTask = new TaskInfo_1.PdfTaskInfo();
newTask.assign(task);
this._offsetPoints(newTask.sidePoints, hOffsets[j].offset, vOffsets[i].offset);
this._addTaskToPage(vOffsets[i].pageIndex, hOffsets[j].pageIndex, newTask);
}
};
PdfGanttPaginator.prototype._paginateArrow = function (dependency) {
var pointInfo = this._getPointPageInfo(dependency.points[0]);
var newDependency = new DependencyLineInfo_1.PdfDependencyLineInfo();
newDependency.assign(dependency);
this._offsetPoints(newDependency.points, pointInfo.offsetX, pointInfo.offsetY);
this._addDependencyToPage(pointInfo.pageVerIndex, pointInfo.pageHorIndex, newDependency);
};
PdfGanttPaginator.prototype._paginateDependencyLine = function (dependency) {
var hPagination = this._getDependencyLinePagination(dependency);
var vPagination = this._getDependencyLinePagination(dependency, true);
for (var i = 0; i < vPagination.length; i++)
for (var j = 0; j < hPagination.length; j++) {
var newDependency = new DependencyLineInfo_1.PdfDependencyLineInfo();
newDependency.assign(dependency);
this._offsetPoints(newDependency.points, hPagination[j].offset, vPagination[i].offset);
this._addDependencyToPage(vPagination[i].pageIndex, hPagination[j].pageIndex, newDependency);
}
};
PdfGanttPaginator.prototype._paginateResource = function (resource) {
var pointInfo = this._getPointPageInfo(new point_1.Point(resource.x, resource.y));
var newResource = new TaskResourcesInfo_1.PdfTaskResourcesInfo();
newResource.assign(resource);
newResource.x -= pointInfo.offsetX;
newResource.y -= pointInfo.offsetY;
this._addResourceToPage(pointInfo.pageVerIndex, pointInfo.pageHorIndex, newResource);
};
PdfGanttPaginator.prototype._paginateTimeMarker = function (timeMarker) {
var hPagination = this._getTimeMarkerPagination(timeMarker);
var vPagination = this._getTimeMarkerPagination(timeMarker, true);
for (var i = 0; i < vPagination.length; i++)
for (var j = 0; j < hPagination.length; j++) {
var newMarker = new TimeMarkerInfo_1.PdfTimeMarkerInfo();
newMarker.assign(timeMarker);
newMarker.start.x -= hPagination[j].offset;
newMarker.start.y -= vPagination[i].offset;
this._addTimeMarkerToPage(vPagination[i].pageIndex, hPagination[j].pageIndex, newMarker);
}
};
PdfGanttPaginator.prototype._getTableStart = function (table) {
var start = new PageNavigation_1.PageNavigation(this.pageBorders, 0, 0, 0, 0, this.correctedPageBottoms);
start.offset(table.position.x, table.position.y);
return start;
};
PdfGanttPaginator.prototype._getPage = function (rowIndex, colIndex, forceCreate) {
if (forceCreate)
this._extendPageMatrixIfRequired(rowIndex, colIndex);
return this._pages[rowIndex] && this._pages[rowIndex][colIndex];
};
PdfGanttPaginator.prototype._getTableOrCreate = function (page, tableKey) {
var _a;
var _b;
(_a = (_b = page.tables)[tableKey]) !== null && _a !== void 0 ? _a : (_b[tableKey] = this._createTable(tableKey));
return page.tables[tableKey];
};
PdfGanttPaginator.prototype._preparePagesNavigationMatrixForTable = function (start, table) {
var matrix = new Array();
var verticalVector = this._getTableNavigationVector(start, table, true);
var rowCount = verticalVector.length;
for (var i = 0; i < rowCount; i++) {
var row = new Array();
var vInfo = verticalVector[i];
var horizontalVector = this._getTableNavigationVector(start, table, false, vInfo.globalCellIndex);
var colCount = horizontalVector.length;
for (var j = 0; j < colCount; j++) {
var hInfo = horizontalVector[j];
var cancelTextCut = table.name === Interfaces_1.PdfPageTableNames.chartScaleTop;
var cell = this._prepareCuttedCell(table.cells[vInfo.globalCellIndex][hInfo.globalCellIndex], hInfo, vInfo, cancelTextCut);
var info = new CellNavigationInfo(hInfo.pageIndex, vInfo.pageIndex, vInfo.cellIndexOnPage, hInfo.cellIndexOnPage, cell);
row.push(info);
}
matrix.push(row);
}
return matrix;
};
PdfGanttPaginator.prototype._setTablePositionOnPage = function (page, tableKey, x, y) {
var table = this._getTableOrCreate(page, tableKey);
table.position = new point_1.Point(x, y);
};
PdfGanttPaginator.prototype._extendPageMatrixIfRequired = function (rowIndex, colIndex) {
var _a;
(_a = this._pages) !== null && _a !== void 0 ? _a : (this._pages = new Array());
for (var i = this._pages.length; i <= rowIndex; i++)
this._pages.push(new Array());
var row = this._pages[rowIndex];
for (var i = row.length; i <= colIndex; i++)
row.push(this._createPage());
};
PdfGanttPaginator.prototype._getTableAndExtendIfRequired = function (page, tableKey, rowIndex, colIndex) {
var table = this._getTableOrCreate(page, tableKey);
var cells = table.cells;
for (var i = cells.length; i <= rowIndex; i++)
cells.push(new Array());
var row = cells[rowIndex];
for (var i = row.length; i <= colIndex; i++)
row.push(new CellDef_1.CellDef());
return table;
};
PdfGanttPaginator.prototype._createPage = function () {
return {
objects: {
tasks: null,
dependencies: null,
resources: null,
timeMarkers: null
},
tables: {}
};
};
PdfGanttPaginator.prototype._createTable = function (tableKey) {
var _a;
var globalTableInfo = (_a = this._globalInfo) === null || _a === void 0 ? void 0 : _a.tables[tableKey];
return {
name: tableKey,
size: null,
position: null,
style: globalTableInfo.style,
baseCellSize: globalTableInfo.baseCellSize,
cells: new Array(),
hideRowLines: globalTableInfo.hideRowLines
};
};
PdfGanttPaginator.prototype._addCellToPage = function (page, tableKey, cellInfo) {
var rowIndex = cellInfo.cellRowIndexOnPage;
var colIndex = cellInfo.cellColIndexOnPage;
var table = this._getTableAndExtendIfRequired(page, tableKey, rowIndex, colIndex);
table.cells[rowIndex][colIndex].assign(cellInfo.cell);
};
PdfGanttPaginator.prototype._updateTableSizeOnPages = function (tableKey) {
var _a;
var colCount = (_a = this._pages[0]) === null || _a === void 0 ? void 0 : _a.length;
var rowCount = this._pages.length;
for (var i = 0; i < rowCount; i++)
for (var j = 0; j < colCount; j++)
this._updateTableSizeOnPage(this._pages[i][j], tableKey);
};
PdfGanttPaginator.prototype._updateTableSizeOnPage = function (page, tableKey) {
var _this = this;
var _a;
var table = page === null || page === void 0 ? void 0 : page.tables[tableKey];
if (table) {
var rowCount = table.cells.length;
var height = rowCount * table.baseCellSize.height || 0;
var width = ((_a = table.cells[0]) === null || _a === void 0 ? void 0 : _a.reduce(function (acc, v, i) { return acc += _this._getCellWidth(table, 0, i); }, 0)) || 0;
table.size = new size_1.Size(width, height);
}
};
PdfGanttPaginator.prototype._getTableNavigationVector = function (start, table, isVertical, rowIndex) {
var _a, _b;
if (isVertical === void 0) { isVertical = false; }
if (rowIndex === void 0) { rowIndex = 0; }
var vector = new Array();
var pageNav = PageNavigation_1.PageNavigation.createFrom(start);
var length = isVertical ? (_a = table.cells) === null || _a === void 0 ? void 0 : _a.length : (_b = table.cells[rowIndex]) === null || _b === void 0 ? void 0 : _b.length;
for (var i = 0; i < length; i++) {
var cellSize = isVertical ? table.baseCellSize.height : this._getCellWidth(table, rowIndex, i);
this._placeCell(vector, pageNav, i, cellSize, isVertical);
}
return vector;
};
PdfGanttPaginator.prototype._placeCell = function (vector, pageNav, cellGlobalIndex, size, isVertical) {
var _a, _b;
var startPageIndex = isVertical ? pageNav.vIndex : pageNav.hIndex;
var pageOffsetIndex = (_b = (_a = vector[vector.length - 1]) === null || _a === void 0 ? void 0 : _a.pageOffset) !== null && _b !== void 0 ? _b : cellGlobalIndex;
var unplacedSize = size;
var spaceToBorder = pageNav.getSpaceToBorder(isVertical);
pageNav.offsetOneD(size, isVertical);
var endPageIndex = isVertical ? pageNav.vIndex : pageNav.hIndex;
if (!isVertical)
for (var i = startPageIndex; i < endPageIndex; i++) {
var info_1 = new VectorInfo(i, cellGlobalIndex, pageOffsetIndex, spaceToBorder);
pageOffsetIndex = cellGlobalIndex;
vector.push(info_1);
unplacedSize -= spaceToBorder;
spaceToBorder = pageNav.getPageSize(isVertical);
}
if (endPageIndex !== startPageIndex)
pageOffsetIndex = cellGlobalIndex;
var isCutted = unplacedSize !== size;
var info = new VectorInfo(endPageIndex, cellGlobalIndex, pageOffsetIndex, isCutted ? unplacedSize : null);
vector.push(info);
};
PdfGanttPaginator.prototype._prepareCuttedCell = function (originCell, hInfo, vInfo, cancelTextCut) {
var cell = new CellDef_1.CellDef(originCell);
if (hInfo.isCutted) {
var width = hInfo.cutSize;
if (!cancelTextCut) {
var text = cell.content;
var style = originCell.styles;
var leftPadding = style && style.cellPadding.left || 0;
var rightPadding = style && style.cellPadding.right || 0;
var textWidth = width - leftPadding - rightPadding;
var parts = this._pdfDoc.splitTextToSize(text, textWidth);
originCell.content = text.replace(parts[0], "");
cell.content = parts[0];
}
cell.styles.cellWidth.assign(width);
}
if (vInfo.isCutted)
cell.styles.minCellHeight = vInfo.cutSize;
return cell;
};
PdfGanttPaginator.prototype._getCellWidth = function (table, rowIndex, colIndex) {
var _a;
var cell = table.cells[rowIndex][colIndex];
var style = cell.styles;
var numWidth = style.cellWidth.getValue();
var width = numWidth !== null && numWidth !== void 0 ? numWidth : style.minCellWidth;
return width !== null && width !== void 0 ? width : table.baseCellSize.width * ((_a = cell.colSpan) !== null && _a !== void 0 ? _a : 1);
};
PdfGanttPaginator.prototype._getTaskPagination = function (task, isVertical) {
var size = isVertical ? task.height : task.width;
var startPos = isVertical ? task.top : task.left;
return this._getLinePagination(startPos, size, isVertical);
};
PdfGanttPaginator.prototype._getDependencyLinePagination = function (dependency, isVertical) {
var lineStart = dependency.points[0];
var lineEnd = dependency.points[1];
var size = isVertical ? lineEnd.y - lineStart.y : lineEnd.x - lineStart.x;
var startPos = isVertical ? lineStart.y : lineStart.x;
return this._getLinePagination(startPos, size, isVertical);
};
PdfGanttPaginator.prototype._getTimeMarkerPagination = function (timeMarker, isVertical) {
var size = isVertical ? timeMarker.size.height : timeMarker.size.width;
var start = isVertical ? timeMarker.start.y : timeMarker.start.x;
return this._getLinePagination(start, size, isVertical);
};
PdfGanttPaginator.prototype._getLinePagination = function (globalStart, size, isVertical) {
var result = new Array();
var pageNav = this.pageNavigator.clone();
pageNav.offsetOneD(globalStart, isVertical);
var startPageIndex = isVertical ? pageNav.vIndex : pageNav.hIndex;
pageNav.offsetOneD(size, isVertical);
var endPageIndex = isVertical ? pageNav.vIndex : pageNav.hIndex;
for (var i = startPageIndex; i <= endPageIndex; i++)
result.push({
offset: pageNav.getPageGlobalOffset(i, isVertical),
pageIndex: i
});
return result;
};
PdfGanttPaginator.prototype._getPointPageInfo = function (p) {
var pageNav = this.pageNavigator.clone();
pageNav.offset(p.x, p.y);
return {
offsetX: pageNav.getPageGlobalOffset(pageNav.hIndex),
offsetY: pageNav.getPageGlobalOffset(pageNav.vIndex, true),
pageHorIndex: pageNav.hIndex,
pageVerIndex: pageNav.vIndex
};
};
Object.defineProperty(PdfGanttPaginator.prototype, "pageWidth", {
get: function () {
var _a;
return (_a = this._pdfDoc) === null || _a === void 0 ? void 0 : _a.getPageWidth();
},
enumerable: false,
configurable: true
});
Object.defineProperty(PdfGanttPaginator.prototype, "pageHeight", {
get: function () {
var _a;
return (_a = this._pdfDoc) === null || _a === void 0 ? void 0 : _a.getPageHeight();
},
enumerable: false,
configurable: true
});
Object.defineProperty(PdfGanttPaginator.prototype, "pageLeftMargin", {
get: function () {
var _a;
return (_a = this._props) === null || _a === void 0 ? void 0 : _a.margins.left;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PdfGanttPaginator.prototype, "pageTopMargin", {
get: function () {
var _a;
return (_a = this._props) === null || _a === void 0 ? void 0 : _a.margins.top;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PdfGanttPaginator.prototype, "pageRightMargin", {
get: function () {
var _a;
return (_a = this._props) === null || _a === void 0 ? void 0 : _a.margins.right;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PdfGanttPaginator.prototype, "pageBottomMargin", {
get: function () {
var _a;
return (_a = this._props) === null || _a === void 0 ? void 0 : _a.margins.bottom;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PdfGanttPaginator.prototype, "pageLeft", {
get: function () {
var _a;
(_a = this._pageLeft) !== null && _a !== void 0 ? _a : (this._pageLeft = this.pageLeftMargin);
return this._pageLeft;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PdfGanttPaginator.prototype, "pageRight", {
get: function () {
var _a;
(_a = this._pageRight) !== null && _a !== void 0 ? _a : (this._pageRight = this.pageWidth - this.pageRightMargin);
return this._pageRight;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PdfGanttPaginator.prototype, "pageTop", {
get: function () {
var _a;
(_a = this._pageTop) !== null && _a !== void 0 ? _a : (this._pageTop = this.pageTopMargin);
return this._pageTop;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PdfGanttPaginator.prototype, "pageBottom", {
get: function () {
var _a;
(_a = this._pageBottom) !== null && _a !== void 0 ? _a : (this._pageBottom = this.pageHeight - this.pageBottomMargin);
return this._pageBottom;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PdfGanttPaginator.prototype, "pageBorders", {
get: function () {
return {
left: this.pageLeft,
top: this.pageTop,
bottom: this.pageBottom,
right: this.pageRight
};
},
enumerable: false,
configurable: true
});
Object.defineProperty(PdfGanttPaginator.prototype, "correctedPageBottoms", {
get: function () {
var _a;
(_a = this._correctedPageBottoms) !== null && _a !== void 0 ? _a : (this._correctedPageBottoms = this._getCorrectedPagesBottom());
return this._correctedPageBottoms;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PdfGanttPaginator.prototype, "pageNavigator", {
get: function () {
var _a;
(_a = this._pageNavigator) !== null && _a !== void 0 ? _a : (this._pageNavigator = new PageNavigation_1.PageNavigation(this.pageBorders, 0, 0, 0, 0, this.correctedPageBottoms));
return this._pageNavigator;
},
enumerable: false,
configurable: true
});
PdfGanttPaginator.prototype._getCorrectedPagesBottom = function () {
var _a, _b, _c, _d;
var result = new Array();
var tables = (_a = this._globalInfo) === null || _a === void 0 ? void 0 : _a.tables;
var referenceTable = (_b = tables[Interfaces_1.PdfPageTableNames.treeListMain]) !== null && _b !== void 0 ? _b : tables[Interfaces_1.PdfPageTableNames.chartMain];
var nav = new PageNavigation_1.PageNavigation(this.pageBorders);
nav.pageY = referenceTable.position.y;
for (var i = 0; i < referenceTable.cells.length; i++) {
var cell = referenceTable.cells[i][0];
var height = (_d = (_c = cell.styles) === null || _c === void 0 ? void 0 : _c.minCellHeight) !== null && _d !== void 0 ? _d : referenceTable.baseCellSize.height;
var prevPageIndex = nav.vIndex;
var prevPageY = nav.pageY;
nav.offsetOneD(height, true);
if (prevPageIndex !== nav.vIndex) {
result.push(prevPageY);
nav.pageY = nav.getPageStart(true) + height;
}
}
return result;
};
PdfGanttPaginator.prototype._addTaskToPage = function (pageVIndex, pageHIndex, task) {
var _a;
var _b;
var page = this._getPage(pageVIndex, pageHIndex);
if (page) {
(_a = (_b = page.objects).tasks) !== null && _a !== void 0 ? _a : (_b.tasks = new Array());
page.objects.tasks.push(task);
}
};
PdfGanttPaginator.prototype._addDependencyToPage = function (pageVIndex, pageHIndex, dependency) {
var _a;
var _b;
var page = this._getPage(pageVIndex, pageHIndex);
if (page) {
(_a = (_b = page.objects).dependencies) !== null && _a !== void 0 ? _a : (_b.dependencies = new Array());
page.objects.dependencies.push(dependency);
}
};
PdfGanttPaginator.prototype._addResourceToPage = function (pageVIndex, pageHIndex, resource) {
var _a;
var _b;
var page = this._getPage(pageVIndex, pageHIndex);
if (page) {
(_a = (_b = page.objects).resources) !== null && _a !== void 0 ? _a : (_b.resources = new Array());
page.objects.resources.push(resource);
}
};
PdfGanttPaginator.prototype._addTimeMarkerToPage = function (pageVIndex, pageHIndex, timeMarker) {
var _a;
var _b;
var page = this._getPage(pageVIndex, pageHIndex);
if (page) {
(_a = (_b = page.objects).timeMarkers) !== null && _a !== void 0 ? _a : (_b.timeMarkers = new Array());
page.objects.timeMarkers.push(timeMarker);
}
};
PdfGanttPaginator.prototype._offsetPoints = function (points, offsetX, offsetY) {
points.forEach(function (p) {
p.x -= offsetX;
p.y -= offsetY;
});
};
return PdfGanttPaginator;
}());
exports.PdfGanttPaginator = PdfGanttPaginator;
/***/ }),
/* 170 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PageNavigation = void 0;
var PageNavigation = (function () {
function PageNavigation(borders, vIndex, hIndex, pageX, pageY, correctedBottoms) {
this._correctedBottoms = new Array();
this.vIndex = 0;
this.hIndex = 0;
this.pageX = 0;
this.pageY = 0;
this._top = borders === null || borders === void 0 ? void 0 : borders.top;
this._left = borders === null || borders === void 0 ? void 0 : borders.left;
this._bottom = borders === null || borders === void 0 ? void 0 : borders.bottom;
this._right = borders === null || borders === void 0 ? void 0 : borders.right;
this.vIndex = vIndex !== null && vIndex !== void 0 ? vIndex : this.vIndex;
this.hIndex = hIndex !== null && hIndex !== void 0 ? hIndex : this.hIndex;
this.pageX = pageX !== null && pageX !== void 0 ? pageX : this.pageX;
this.pageY = pageY !== null && pageY !== void 0 ? pageY : this.pageY;
if (correctedBottoms)
this._correctedBottoms = correctedBottoms;
}
PageNavigation.prototype.offset = function (offsetX, offsetY) {
if (offsetX)
this.offsetOneD(offsetX);
if (offsetY)
this.offsetOneD(offsetY, true);
};
PageNavigation.prototype.offsetOneD = function (delta, isVertical) {
var unplacedSize = delta;
var spaceToBorder = this.getSpaceToBorder(isVertical);
while (spaceToBorder < unplacedSize) {
if (isVertical) {
this.vIndex++;
this.pageY = this._top;
}
else {
this.hIndex++;
this.pageX = this._left;
}
unplacedSize -= spaceToBorder;
spaceToBorder = this.getSpaceToBorder(isVertical);
}
if (isVertical)
this.pageY += unplacedSize;
else
this.pageX += unplacedSize;
};
Object.defineProperty(PageNavigation.prototype, "defaultPageHeight", {
get: function () {
return this.getCurrentPageBottom() - this._top;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PageNavigation.prototype, "defaultPageWidth", {
get: function () {
return this._right - this._left;
},
enumerable: false,
configurable: true
});
PageNavigation.prototype.getPageEnd = function (isVertical) {
return isVertical ? this.getCurrentPageBottom() : this._right;
};
PageNavigation.prototype.getPageStart = function (isVertical) {
return isVertical ? this._top : this._left;
};
PageNavigation.prototype.getPageSize = function (isVertical, index) {
return isVertical ? this.getPageHeight(index) : this.defaultPageWidth;
};
PageNavigation.prototype.getSpaceToBorder = function (isVertical) {
return isVertical ? this.getCurrentPageBottom() - this.pageY : this._right - this.pageX;
};
PageNavigation.prototype.getPageGlobalOffset = function (index, isVertical) {
if (!isVertical)
return index * this.defaultPageWidth;
var offset = 0;
for (var i = 1; i <= index; i++)
offset += this.getPageHeight(i - 1);
return offset;
};
PageNavigation.prototype.assign = function (src) {
this._top = src._top;
this._left = src._left;
this._bottom = src._bottom;
this._right = src._right;
this._correctedBottoms = src._correctedBottoms;
this.vIndex = src.vIndex;
this.hIndex = src.hIndex;
this.pageX = src.pageX;
this.pageY = src.pageY;
};
PageNavigation.createFrom = function (src) {
var instance = new PageNavigation();
instance.assign(src);
return instance;
};
PageNavigation.prototype.clone = function () {
var instance = new PageNavigation();
instance.assign(this);
return instance;
};
PageNavigation.prototype.getCurrentPageBottom = function () {
return this.getPageBottom(this.vIndex);
};
PageNavigation.prototype.getPageBottom = function (index) {
var _a;
return (_a = this._correctedBottoms[index]) !== null && _a !== void 0 ? _a : this._bottom;
};
PageNavigation.prototype.getPageHeight = function (index) {
return this.getPageBottom(index) - this._top;
};
return PageNavigation;
}());
exports.PageNavigation = PageNavigation;
/***/ }),
/* 171 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScalingHelper = void 0;
var Interfaces_1 = __webpack_require__(29);
var ScalingHelper = (function () {
function ScalingHelper(doc) {
this._doc = doc;
}
Object.defineProperty(ScalingHelper.prototype, "_docScaleFactor", {
get: function () {
var _a, _b;
return (_b = (_a = this._doc) === null || _a === void 0 ? void 0 : _a.internal) === null || _b === void 0 ? void 0 : _b.scaleFactor;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScalingHelper.prototype, "_correctScaleNeeded", {
get: function () {
return this._docScaleFactor && Math.abs(this._docScaleFactor - ScalingHelper._defaultScaleFactor) > Number.EPSILON;
},
enumerable: false,
configurable: true
});
ScalingHelper.prototype.getScaledSize = function (size) {
var size_in_pt = size * ScalingHelper._defaultScaleFactor;
return size_in_pt / this._docScaleFactor;
};
ScalingHelper.prototype.scalePageMargins = function (settings) {
var _a, _b, _c, _d;
if (this._correctScaleNeeded) {
if ((_a = settings === null || settings === void 0 ? void 0 : settings.margins) === null || _a === void 0 ? void 0 : _a.left)
settings.margins.left = this.getScaledSize(settings.margins.left);
if ((_b = settings === null || settings === void 0 ? void 0 : settings.margins) === null || _b === void 0 ? void 0 : _b.right)
settings.margins.right = this.getScaledSize(settings.margins.right);
if ((_c = settings === null || settings === void 0 ? void 0 : settings.margins) === null || _c === void 0 ? void 0 : _c.top)
settings.margins.top = this.getScaledSize(settings.margins.top);
if ((_d = settings === null || settings === void 0 ? void 0 : settings.margins) === null || _d === void 0 ? void 0 : _d.bottom)
settings.margins.bottom = this.getScaledSize(settings.margins.bottom);
}
};
ScalingHelper.prototype.scaleSizes = function (info) {
if (this._correctScaleNeeded) {
this.scaleTables(info);
this.scaleObjects(info.objects);
}
};
ScalingHelper.prototype.scaleTables = function (info) {
if (info === null || info === void 0 ? void 0 : info.tables) {
this.scaleTable(info.tables[Interfaces_1.PdfPageTableNames.treeListHeader]);
this.scaleTable(info.tables[Interfaces_1.PdfPageTableNames.treeListMain]);
this.scaleTable(info.tables[Interfaces_1.PdfPageTableNames.chartMain]);
this.scaleTable(info.tables[Interfaces_1.PdfPageTableNames.chartScaleTop]);
this.scaleTable(info.tables[Interfaces_1.PdfPageTableNames.chartScaleBottom]);
}
};
ScalingHelper.prototype.scaleTable = function (table) {
var _a, _b, _c, _d, _e, _f;
if (!table)
return;
if ((_a = table.size) === null || _a === void 0 ? void 0 : _a.width)
table.size.width = this.getScaledSize(table.size.width);
if ((_b = table.size) === null || _b === void 0 ? void 0 : _b.height)
table.size.height = this.getScaledSize(table.size.height);
if ((_c = table.position) === null || _c === void 0 ? void 0 : _c.x)
table.position.x = this.getScaledSize(table.position.x);
if ((_d = table.position) === null || _d === void 0 ? void 0 : _d.y)
table.position.y = this.getScaledSize(table.position.y);
if ((_e = table.baseCellSize) === null || _e === void 0 ? void 0 : _e.width)
table.baseCellSize.width = this.getScaledSize(table.baseCellSize.width);
if ((_f = table.baseCellSize) === null || _f === void 0 ? void 0 : _f.height)
table.baseCellSize.height = this.getScaledSize(table.baseCellSize.height);
if (table.cells)
for (var i = 0; i < table.cells.length; i++) {
var row = table.cells[i];
for (var j = 0; j < row.length; j++) {
var cell = row[j];
this.scaleStyle(cell.styles);
}
}
};
ScalingHelper.prototype.scaleObjects = function (objects) {
this.scaleTasks(objects === null || objects === void 0 ? void 0 : objects.tasks);
this.scaleDependencies(objects === null || objects === void 0 ? void 0 : objects.dependencies);
this.scaleResources(objects === null || objects === void 0 ? void 0 : objects.resources);
this.scaleTimeMarkers(objects === null || objects === void 0 ? void 0 : objects.timeMarkers);
};
ScalingHelper.prototype.scaleTasks = function (tasks) {
var _this = this;
tasks === null || tasks === void 0 ? void 0 : tasks.forEach(function (t) {
_this.scalePoints(t.sidePoints);
t.progressWidth = _this.getScaledSize(t.progressWidth);
_this.scaleStyle(t.textStyle);
});
};
ScalingHelper.prototype.scaleDependencies = function (dependencies) {
var _this = this;
dependencies === null || dependencies === void 0 ? void 0 : dependencies.forEach(function (d) {
var _a;
_this.scalePoints(d.points);
if ((_a = d.arrowInfo) === null || _a === void 0 ? void 0 : _a.width)
d.arrowInfo.width = _this.getScaledSize(d.arrowInfo.width);
});
};
ScalingHelper.prototype.scaleResources = function (resources) {
var _this = this;
resources === null || resources === void 0 ? void 0 : resources.forEach(function (r) {
r.x = _this.getScaledSize(r.x);
r.y = _this.getScaledSize(r.y);
_this.scaleStyle(r.style);
});
};
ScalingHelper.prototype.scaleTimeMarkers = function (timeMarkers) {
var _this = this;
timeMarkers === null || timeMarkers === void 0 ? void 0 : timeMarkers.forEach(function (m) {
m.start.x = _this.getScaledSize(m.start.x);
m.start.y = _this.getScaledSize(m.start.y);
m.size.width = _this.getScaledSize(m.size.width);
m.size.height = _this.getScaledSize(m.size.height);
});
};
ScalingHelper.prototype.scaleStyle = function (style) {
var _a, _b, _c, _d;
if (style) {
var cellWidth = style.cellWidth;
if (cellWidth === null || cellWidth === void 0 ? void 0 : cellWidth.hasValue()) {
var scaled = this.getScaledSize(Number(cellWidth.getValue()));
cellWidth.assign(scaled);
}
if (style.minCellHeight)
style.minCellHeight = this.getScaledSize(style.minCellHeight);
if (style.minCellWidth)
style.minCellWidth = this.getScaledSize(style.minCellWidth);
if ((_a = style.cellPadding) === null || _a === void 0 ? void 0 : _a.left)
style.cellPadding.left = this.getScaledSize(style.cellPadding.left);
if ((_b = style.cellPadding) === null || _b === void 0 ? void 0 : _b.right)
style.cellPadding.right = this.getScaledSize(style.cellPadding.right);
if ((_c = style.cellPadding) === null || _c === void 0 ? void 0 : _c.top)
style.cellPadding.top = this.getScaledSize(style.cellPadding.top);
if ((_d = style.cellPadding) === null || _d === void 0 ? void 0 : _d.bottom)
style.cellPadding.bottom = this.getScaledSize(style.cellPadding.bottom);
}
};
ScalingHelper.prototype.scalePoints = function (points) {
var _this = this;
points === null || points === void 0 ? void 0 : points.forEach(function (p) {
p.x = _this.getScaledSize(p.x);
p.y = _this.getScaledSize(p.y);
});
};
ScalingHelper._defaultScaleFactor = 72 / 96;
return ScalingHelper;
}());
exports.ScalingHelper = ScalingHelper;
/***/ }),
/* 172 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HandlerSettings = void 0;
var common_1 = __webpack_require__(1);
var HandlerSettings = (function () {
function HandlerSettings() {
}
HandlerSettings.parse = function (settings) {
var result = new HandlerSettings();
if (settings) {
if ((0, common_1.isDefined)(settings.getRenderHelper))
result.getRenderHelper = settings.getRenderHelper;
if ((0, common_1.isDefined)(settings.getTaskEditController))
result.getTaskEditController = settings.getTaskEditController;
if ((0, common_1.isDefined)(settings.getHistory))
result.getHistory = settings.getHistory;
if ((0, common_1.isDefined)(settings.getTickSize))
result.getTickSize = settings.getTickSize;
if ((0, common_1.isDefined)(settings.isFocus))
result.isFocus = settings.isFocus;
if ((0, common_1.isDefined)(settings.getViewModel))
result.getViewModel = settings.getViewModel;
if ((0, common_1.isDefined)(settings.zoomIn))
result.zoomIn = settings.zoomIn;
if ((0, common_1.isDefined)(settings.zoomOut))
result.zoomOut = settings.zoomOut;
if ((0, common_1.isDefined)(settings.selectDependency))
result.selectDependency = settings.selectDependency;
if ((0, common_1.isDefined)(settings.showPopupMenu))
result.showPopupMenu = settings.showPopupMenu;
if ((0, common_1.isDefined)(settings.changeGanttTaskSelection))
result.changeGanttTaskSelection = settings.changeGanttTaskSelection;
}
return result;
};
return HandlerSettings;
}());
exports.HandlerSettings = HandlerSettings;
/***/ }),
/* 173 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.History = void 0;
var HistoryItemInfo_1 = __webpack_require__(174);
var CompositionHistoryItem_1 = __webpack_require__(45);
var History = (function () {
function History(listener) {
this.historyItems = [];
this.currentIndex = -1;
this.currentProcessingItemInfo = null;
this.transaction = null;
this.transactionLevel = -1;
this._listener = listener;
}
History.prototype.undo = function () {
if (this.canUndo()) {
this.activateItem(this.historyItems[this.currentIndex], true);
this.currentIndex--;
}
};
History.prototype.redo = function () {
if (this.canRedo()) {
this.currentIndex++;
this.activateItem(this.historyItems[this.currentIndex]);
}
};
History.prototype.beginTransaction = function () {
var _a;
this.transactionLevel++;
if (this.transactionLevel == 0)
this.transaction = new CompositionHistoryItem_1.CompositionHistoryItem();
(_a = this._listener) === null || _a === void 0 ? void 0 : _a.onTransactionStart();
};
History.prototype.endTransaction = function () {
var _a;
if (--this.transactionLevel >= 0)
return;
var transactionLength = this.transaction.historyItems.length;
if (transactionLength > 1)
this.addInternal(this.transaction);
else if (transactionLength == 1)
this.addInternal(this.transaction.historyItems.pop());
this.transaction = null;
(_a = this._listener) === null || _a === void 0 ? void 0 : _a.onTransactionEnd();
};
History.prototype.addAndRedo = function (historyItem) {
this.add(historyItem);
this.activateItem(historyItem);
};
History.prototype.add = function (historyItem) {
if (this.transactionLevel >= 0)
this.transaction.add(historyItem);
else
this.addInternal(historyItem);
};
History.prototype.canUndo = function () {
return this.currentIndex >= 0;
};
History.prototype.canRedo = function () {
return this.currentIndex < this.historyItems.length - 1;
};
History.prototype.addInternal = function (historyItem) {
if (this.currentIndex < this.historyItems.length - 1)
this.historyItems.splice(this.currentIndex + 1);
this.historyItems.push(historyItem);
this.currentIndex++;
this.deleteOldItems();
};
History.prototype.deleteOldItems = function () {
var exceedItemsCount = this.historyItems.length - History.MAX_HISTORY_ITEM_COUNT;
if (exceedItemsCount > 0 && this.currentIndex > exceedItemsCount) {
this.historyItems.splice(0, exceedItemsCount);
this.currentIndex -= exceedItemsCount;
}
};
History.prototype.clear = function () {
this.currentIndex = -1;
this.historyItems = [];
};
History.prototype.activateItem = function (historyItem, isUndo) {
if (isUndo === void 0) { isUndo = false; }
this.currentProcessingItemInfo = new HistoryItemInfo_1.HistoryItemInfo(historyItem, isUndo);
if (isUndo)
historyItem.undo();
else
historyItem.redo();
this.currentProcessingItemInfo = null;
};
History.prototype.getCurrentProcessingItemInfo = function () {
return this.currentProcessingItemInfo;
};
History.prototype.rollBackAndRemove = function (info) {
var item = info.item;
if (!this.checkAndRemoveItem(item))
return;
if (info.isUndo)
item.redo();
else if (item instanceof CompositionHistoryItem_1.CompositionHistoryItem)
item.undoItemsQuery();
else
item.undo();
};
History.prototype.checkAndRemoveItem = function (item) {
var index = this.historyItems.indexOf(item);
if (index > -1) {
this.historyItems.splice(index, 1);
this.currentIndex--;
}
else if (this.transaction) {
index = this.transaction.historyItems.indexOf(item);
if (index > -1)
this.transaction.historyItems.splice(index, 1);
}
return index > -1;
};
History.MAX_HISTORY_ITEM_COUNT = 100;
return History;
}());
exports.History = History;
/***/ }),
/* 174 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HistoryItemInfo = void 0;
var HistoryItemInfo = (function () {
function HistoryItemInfo(item, isUndo) {
if (isUndo === void 0) { isUndo = false; }
this.item = item;
this.isUndo = isUndo;
}
return HistoryItemInfo;
}());
exports.HistoryItemInfo = HistoryItemInfo;
/***/ }),
/* 175 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModelChangesDispatcher = void 0;
var ResourceManagerDialogShowingArguments_1 = __webpack_require__(176);
var TaskEditDialogShowingArguments_1 = __webpack_require__(177);
var ResourceUnassigningArguments_1 = __webpack_require__(178);
var TaskUpdatingArguments_1 = __webpack_require__(179);
var EventDispatcher_1 = __webpack_require__(180);
var ModelChangesDispatcher = (function () {
function ModelChangesDispatcher() {
this.onModelChanged = new EventDispatcher_1.EventDispatcher();
this.isLocked = false;
}
ModelChangesDispatcher.prototype.notifyTaskCreating = function (args) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyTaskCreating", args);
};
ModelChangesDispatcher.prototype.notifyTaskCreated = function (task, callback, errorCallback) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyTaskCreated", task, callback, errorCallback);
};
ModelChangesDispatcher.prototype.notifyTaskRemoving = function (args) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyTaskRemoving", args);
};
ModelChangesDispatcher.prototype.notifyTaskRemoved = function (taskID, errorCallback, task) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyTaskRemoved", taskID, errorCallback, task);
};
ModelChangesDispatcher.prototype.notifyTaskUpdating = function (args) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyTaskUpdating", args);
};
ModelChangesDispatcher.prototype.notifyTaskMoving = function (args) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyTaskMoving", args);
};
ModelChangesDispatcher.prototype.notifyTaskEditDialogShowing = function (args) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyTaskEditDialogShowing", args);
};
ModelChangesDispatcher.prototype.notifyResourceManagerDialogShowing = function (args) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyResourceManagerDialogShowing", args);
};
ModelChangesDispatcher.prototype.notifyTaskTitleChanged = function (taskID, newValue, errorCallback) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyTaskTitleChanged", taskID, newValue, errorCallback);
};
ModelChangesDispatcher.prototype.notifyTaskDescriptionChanged = function (taskID, newValue, errorCallback) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyTaskDescriptionChanged", taskID, newValue, errorCallback);
};
ModelChangesDispatcher.prototype.notifyTaskStartChanged = function (taskID, newValue, errorCallback) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyTaskStartChanged", taskID, newValue, errorCallback);
};
ModelChangesDispatcher.prototype.notifyTaskEndChanged = function (taskID, newValue, errorCallback) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyTaskEndChanged", taskID, newValue, errorCallback);
};
ModelChangesDispatcher.prototype.notifyTaskProgressChanged = function (taskID, newValue, errorCallback) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyTaskProgressChanged", taskID, newValue, errorCallback);
};
ModelChangesDispatcher.prototype.notifyTaskColorChanged = function (taskID, newValue, errorCallback) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyTaskColorChanged", taskID, newValue, errorCallback);
};
ModelChangesDispatcher.prototype.notifyParentTaskUpdated = function (task, errorCallback) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyParentTaskUpdated", task, errorCallback);
};
ModelChangesDispatcher.prototype.notifyDependencyInserting = function (args) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyDependencyInserting", args);
};
ModelChangesDispatcher.prototype.notifyDependencyInserted = function (dependency, callback, errorCallback) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyDependencyInserted", dependency, callback, errorCallback);
};
ModelChangesDispatcher.prototype.notifyDependencyRemoving = function (args) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyDependencyRemoving", args);
};
ModelChangesDispatcher.prototype.notifyDependencyRemoved = function (dependencyID, errorCallback, dependency) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyDependencyRemoved", dependencyID, errorCallback, dependency);
};
ModelChangesDispatcher.prototype.notifyResourceCreating = function (args) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyResourceCreating", args);
};
ModelChangesDispatcher.prototype.notifyResourceCreated = function (resource, callback, errorCallback) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyResourceCreated", resource, callback, errorCallback);
};
ModelChangesDispatcher.prototype.notifyResourceRemoving = function (args) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyResourceRemoving", args);
};
ModelChangesDispatcher.prototype.notifyResourceRemoved = function (resourceID, errorCallback, resource) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyResourceRemoved", resourceID, errorCallback, resource);
};
ModelChangesDispatcher.prototype.notifyResourceColorChanged = function (resourceID, newValue, errorCallback) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyResourceColorChanged", resourceID, newValue, errorCallback);
};
ModelChangesDispatcher.prototype.notifyResourceAssigning = function (args) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyResourceAssigning", args);
};
ModelChangesDispatcher.prototype.notifyResourceAssigned = function (assignment, callback, errorCallback) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyResourceAssigned", assignment, callback, errorCallback);
};
ModelChangesDispatcher.prototype.notifyResourceUnassigning = function (args) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyResourceUnassigning", args);
};
ModelChangesDispatcher.prototype.notifyResourceUnassigned = function (assignmentID, errorCallback, assignment) {
if (!this.isLocked)
this.onModelChanged.raise("NotifyResourceUnassigned", assignmentID, errorCallback, assignment);
};
ModelChangesDispatcher.prototype.notifyParentDataRecalculated = function (data) {
this.onModelChanged.raise("NotifyParentDataRecalculated", data);
};
ModelChangesDispatcher.prototype.fireResourceUnassigning = function (assignment) {
var args = new ResourceUnassigningArguments_1.ResourceUnassigningArguments(assignment);
this.notifyResourceUnassigning(args);
return !args.cancel;
};
ModelChangesDispatcher.prototype.raiseTaskTitleUpdating = function (task, value, callback) {
return this.raiseTaskUpdating(task, "title", value, callback);
};
ModelChangesDispatcher.prototype.raiseTaskDescriptionUpdating = function (task, value, callback) {
return this.raiseTaskUpdating(task, "description", value, callback);
};
ModelChangesDispatcher.prototype.raiseTaskProgressUpdating = function (task, value, callback) {
return this.raiseTaskUpdating(task, "progress", value, callback);
};
ModelChangesDispatcher.prototype.raiseTaskColorUpdating = function (task, value, callback) {
return this.raiseTaskUpdating(task, "color", value, callback);
};
ModelChangesDispatcher.prototype.raiseTaskStartUpdating = function (task, value, callback) {
return this.raiseTaskUpdating(task, "start", value, callback);
};
ModelChangesDispatcher.prototype.raiseTaskEndUpdating = function (task, value, callback) {
return this.raiseTaskUpdating(task, "end", value, callback);
};
ModelChangesDispatcher.prototype.raiseTaskStartAndEndUpdating = function (task, newStart, newEnd, callback) {
var args = new TaskUpdatingArguments_1.TaskUpdatingArguments(task, ["start", "end"], [newStart, newEnd]);
this.notifyTaskUpdating(args);
if (!args.cancel) {
callback(args["start"], args["end"]);
return true;
}
return false;
};
ModelChangesDispatcher.prototype.raiseTaskUpdating = function (task, fieldName, newValue, callback) {
var oldValue = task[fieldName];
if (oldValue !== newValue) {
var args = new TaskUpdatingArguments_1.TaskUpdatingArguments(task, [fieldName], [newValue]);
this.notifyTaskUpdating(args);
if (!args.cancel && oldValue !== args[fieldName]) {
callback(args[fieldName]);
return true;
}
}
return false;
};
ModelChangesDispatcher.prototype.raiseTaskMultipleUpdating = function (task, newValues, callback) {
var fields = ["title", "progress", "start", "end", "color"];
var values = fields.map(function (f) { return newValues[f]; });
var args = new TaskUpdatingArguments_1.TaskUpdatingArguments(task, fields, values);
this.notifyTaskUpdating(args);
if (!args.cancel) {
callback(args.newValues);
return true;
}
return false;
};
ModelChangesDispatcher.prototype.raiseTaskMoving = function (task, newStart, newEnd, callback) {
var args = new TaskUpdatingArguments_1.TaskUpdatingArguments(task, ["start", "end"], [newStart, newEnd]);
this.notifyTaskMoving(args);
if (!args.cancel) {
callback(args["start"], args["end"]);
return true;
}
return false;
};
ModelChangesDispatcher.prototype.raiseTaskTaskEditDialogShowing = function (params, callback) {
var args = new TaskEditDialogShowingArguments_1.TaskEditDialogShowingArguments(params);
this.notifyTaskEditDialogShowing(args);
if (!args.cancel) {
callback(args);
return true;
}
return false;
};
ModelChangesDispatcher.prototype.raiseResourceManagerDialogShowing = function (params, callback) {
var args = new ResourceManagerDialogShowingArguments_1.ResourceManagerDialogShowingArguments(params);
this.notifyResourceManagerDialogShowing(args);
if (!args.cancel) {
callback(args);
return true;
}
return false;
};
ModelChangesDispatcher.prototype.lock = function () { this.isLocked = true; };
ModelChangesDispatcher.prototype.unlock = function () { this.isLocked = false; };
return ModelChangesDispatcher;
}());
exports.ModelChangesDispatcher = ModelChangesDispatcher;
/***/ }),
/* 176 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourceManagerDialogShowingArguments = void 0;
var tslib_1 = __webpack_require__(0);
var BaseArguments_1 = __webpack_require__(9);
var ResourceManagerDialogShowingArguments = (function (_super) {
(0, tslib_1.__extends)(ResourceManagerDialogShowingArguments, _super);
function ResourceManagerDialogShowingArguments(params) {
var _this = _super.call(this, undefined) || this;
_this.values.resources = params.resources;
return _this;
}
return ResourceManagerDialogShowingArguments;
}(BaseArguments_1.BaseArguments));
exports.ResourceManagerDialogShowingArguments = ResourceManagerDialogShowingArguments;
/***/ }),
/* 177 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskEditDialogShowingArguments = void 0;
var tslib_1 = __webpack_require__(0);
var BaseArguments_1 = __webpack_require__(9);
var TaskEditDialogShowingArguments = (function (_super) {
(0, tslib_1.__extends)(TaskEditDialogShowingArguments, _super);
function TaskEditDialogShowingArguments(params) {
var _this = _super.call(this, params.id) || this;
_this.values = {
start: params.start,
end: params.end,
title: params.title,
progress: params.progress
};
_this.hiddenFields = params.hiddenFields;
_this.readOnlyFields = params.readOnlyFields;
return _this;
}
return TaskEditDialogShowingArguments;
}(BaseArguments_1.BaseArguments));
exports.TaskEditDialogShowingArguments = TaskEditDialogShowingArguments;
/***/ }),
/* 178 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourceUnassigningArguments = void 0;
var tslib_1 = __webpack_require__(0);
var BaseArguments_1 = __webpack_require__(9);
var ResourceUnassigningArguments = (function (_super) {
(0, tslib_1.__extends)(ResourceUnassigningArguments, _super);
function ResourceUnassigningArguments(assignment) {
var _this = _super.call(this, assignment.internalId) || this;
_this.values = assignment;
return _this;
}
return ResourceUnassigningArguments;
}(BaseArguments_1.BaseArguments));
exports.ResourceUnassigningArguments = ResourceUnassigningArguments;
/***/ }),
/* 179 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskUpdatingArguments = void 0;
var tslib_1 = __webpack_require__(0);
var BaseArguments_1 = __webpack_require__(9);
var TaskUpdatingArguments = (function (_super) {
(0, tslib_1.__extends)(TaskUpdatingArguments, _super);
function TaskUpdatingArguments(task, fieldNames, newValues) {
var _this = _super.call(this, task.id) || this;
_this.values = task;
_this.createNewValues(fieldNames, newValues);
return _this;
}
TaskUpdatingArguments.prototype.createNewValues = function (fieldNames, newValues) {
var _this = this;
this.newValues = {};
var _loop_1 = function (i) {
var fieldName = fieldNames[i];
this_1.newValues[fieldName] = newValues[i];
Object.defineProperty(this_1, fieldName, {
get: function () { return _this.newValues[fieldName]; }
});
};
var this_1 = this;
for (var i = 0; i < fieldNames.length; i++) {
_loop_1(i);
}
};
return TaskUpdatingArguments;
}(BaseArguments_1.BaseArguments));
exports.TaskUpdatingArguments = TaskUpdatingArguments;
/***/ }),
/* 180 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventDispatcher = void 0;
var EventDispatcher = (function () {
function EventDispatcher() {
this.listeners = [];
}
EventDispatcher.prototype.add = function (listener) {
if (!listener)
throw new Error("Error");
if (!this.hasEventListener(listener))
this.listeners.push(listener);
};
EventDispatcher.prototype.remove = function (listener) {
for (var i = 0, currentListener = void 0; currentListener = this.listeners[i]; i++)
if (currentListener === listener) {
this.listeners.splice(i, 1);
break;
}
};
EventDispatcher.prototype.raise = function (funcName) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
for (var i = 0, listener = void 0; listener = this.listeners[i]; i++) {
var func = listener[funcName];
func === null || func === void 0 ? void 0 : func.apply(listener, args);
}
};
EventDispatcher.prototype.hasEventListener = function (listener) {
for (var i = 0, l = this.listeners.length; i < l; i++)
if (this.listeners[i] === listener)
return true;
return false;
};
return EventDispatcher;
}());
exports.EventDispatcher = EventDispatcher;
/***/ }),
/* 181 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModelManipulator = void 0;
var DependencyManipulator_1 = __webpack_require__(182);
var ResourcesManipulator_1 = __webpack_require__(183);
var TaskManipulator_1 = __webpack_require__(187);
var ModelManipulator = (function () {
function ModelManipulator(viewModel, dispatcher) {
this.task = new TaskManipulator_1.TaskManipulator(viewModel, dispatcher);
this.dependency = new DependencyManipulator_1.TaskDependencyManipulator(viewModel, dispatcher);
this.resource = new ResourcesManipulator_1.ResourcesManipulator(viewModel, dispatcher);
this.dispatcher = dispatcher;
}
return ModelManipulator;
}());
exports.ModelManipulator = ModelManipulator;
/***/ }),
/* 182 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskDependencyManipulator = void 0;
var tslib_1 = __webpack_require__(0);
var BaseManipulator_1 = __webpack_require__(18);
var TaskDependencyManipulator = (function (_super) {
(0, tslib_1.__extends)(TaskDependencyManipulator, _super);
function TaskDependencyManipulator() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskDependencyManipulator.prototype.insertDependency = function (predecessorId, successorId, type, id) {
var dependency = this.viewModel.dependencies.createItem();
dependency.predecessorId = predecessorId;
dependency.successorId = successorId;
dependency.type = type;
if (id)
dependency.internalId = id;
dependency.id = dependency.internalId;
this.viewModel.dependencies.add(dependency);
this.dispatcher.notifyDependencyInserted(this.getObjectForDataSource(dependency), function (id) { return dependency.id = id; }, this.getErrorCallback());
this.viewModel.updateVisibleItemDependencies();
this.renderHelper.recreateConnectorLineElement(dependency.internalId, true);
return dependency;
};
TaskDependencyManipulator.prototype.removeDependency = function (dependencyId) {
var dependency = this.viewModel.dependencies.getItemById(dependencyId);
this.viewModel.dependencies.remove(dependency);
this.dispatcher.notifyDependencyRemoved(dependency.id, this.getErrorCallback(), this.viewModel.getDependencyObjectForDataSource(dependency));
this.viewModel.updateVisibleItemDependencies();
this.renderHelper.recreateConnectorLineElement(dependency.internalId);
return dependency;
};
TaskDependencyManipulator.prototype.getObjectForDataSource = function (dependency) {
var predecessor = this.viewModel.tasks.getItemById(dependency.predecessorId);
var successor = this.viewModel.tasks.getItemById(dependency.successorId);
var dependencyObject = {
id: dependency.id,
predecessorId: predecessor.id,
successorId: successor.id,
type: dependency.type
};
return dependencyObject;
};
return TaskDependencyManipulator;
}(BaseManipulator_1.BaseManipulator));
exports.TaskDependencyManipulator = TaskDependencyManipulator;
/***/ }),
/* 183 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourcesManipulator = void 0;
var tslib_1 = __webpack_require__(0);
var BaseManipulator_1 = __webpack_require__(18);
var ResourcePropertiesManipulator_1 = __webpack_require__(184);
var ResourcesManipulator = (function (_super) {
(0, tslib_1.__extends)(ResourcesManipulator, _super);
function ResourcesManipulator(viewModel, dispatcher) {
var _this = _super.call(this, viewModel, dispatcher) || this;
_this.properties = new ResourcePropertiesManipulator_1.ResourcePropertiesManipulator(viewModel, dispatcher);
return _this;
}
ResourcesManipulator.prototype.create = function (text, color, id, callback) {
var resource = this.viewModel.resources.createItem();
resource.text = text;
if (color)
resource.color = color;
if (id)
resource.internalId = id;
resource.id = resource.internalId;
this.viewModel.resources.add(resource);
this.dispatcher.notifyResourceCreated(this.getResourceObjectForDataSource(resource), function (id) {
resource.id = id;
if (callback)
callback(id);
}, this.getErrorCallback());
return resource;
};
ResourcesManipulator.prototype.remove = function (resourceId) {
var resource = this.viewModel.resources.getItemById(resourceId);
if (!resource)
throw new Error("Invalid resource id");
var assignments = this.viewModel.assignments.items.filter(function (a) { return a.resourceId === resourceId; });
if (assignments.length)
throw new Error("Can't delete assigned resource");
this.viewModel.resources.remove(resource);
this.dispatcher.notifyResourceRemoved(resource.id, this.getErrorCallback(), this.viewModel.getResourceObjectForDataSource(resource));
return resource;
};
ResourcesManipulator.prototype.assign = function (resourceID, taskId, id) {
var assignment = this.viewModel.assignments.createItem();
assignment.resourceId = resourceID;
assignment.taskId = taskId;
if (id)
assignment.internalId = id;
assignment.id = assignment.internalId;
this.viewModel.assignments.add(assignment);
this.dispatcher.notifyResourceAssigned(this.getResourceAssignmentObjectForDataSource(assignment), function (id) { return assignment.id = id; }, this.getErrorCallback());
this.viewModel.updateModel();
this.viewModel.owner.resetAndUpdate();
return assignment;
};
ResourcesManipulator.prototype.deassig = function (assignmentId) {
var assignment = this.viewModel.assignments.getItemById(assignmentId);
this.viewModel.assignments.remove(assignment);
this.dispatcher.notifyResourceUnassigned(assignment.id, this.getErrorCallback(), this.viewModel.getResourceAssignmentObjectForDataSource(assignment));
this.viewModel.updateModel();
this.viewModel.owner.resetAndUpdate();
return assignment;
};
ResourcesManipulator.prototype.getResourceObjectForDataSource = function (resource) {
return {
id: resource.id,
text: resource.text
};
};
ResourcesManipulator.prototype.getResourceAssignmentObjectForDataSource = function (resourceAssignment) {
return {
id: resourceAssignment.id,
taskId: this.viewModel.tasks.getItemById(resourceAssignment.taskId).id,
resourceId: this.viewModel.resources.getItemById(resourceAssignment.resourceId).id
};
};
return ResourcesManipulator;
}(BaseManipulator_1.BaseManipulator));
exports.ResourcesManipulator = ResourcesManipulator;
/***/ }),
/* 184 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourcePropertiesManipulator = void 0;
var tslib_1 = __webpack_require__(0);
var BaseManipulator_1 = __webpack_require__(18);
var ResourceColorManipulator_1 = __webpack_require__(185);
var ResourcePropertiesManipulator = (function (_super) {
(0, tslib_1.__extends)(ResourcePropertiesManipulator, _super);
function ResourcePropertiesManipulator(viewModel, dispatcher) {
var _this = _super.call(this, viewModel, dispatcher) || this;
_this.color = new ResourceColorManipulator_1.ResourceColorManipulator(viewModel, dispatcher);
return _this;
}
return ResourcePropertiesManipulator;
}(BaseManipulator_1.BaseManipulator));
exports.ResourcePropertiesManipulator = ResourcePropertiesManipulator;
/***/ }),
/* 185 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourceColorManipulator = void 0;
var tslib_1 = __webpack_require__(0);
var ResourcePropertyManipulator_1 = __webpack_require__(186);
var ResourceColorManipulator = (function (_super) {
(0, tslib_1.__extends)(ResourceColorManipulator, _super);
function ResourceColorManipulator() {
return _super !== null && _super.apply(this, arguments) || this;
}
ResourceColorManipulator.prototype.getPropertyValue = function (resource) {
return resource.color;
};
ResourceColorManipulator.prototype.setPropertyValue = function (resource, value) {
resource.color = value;
this.dispatcher.notifyResourceColorChanged(resource.id, value, this.getErrorCallback());
};
return ResourceColorManipulator;
}(ResourcePropertyManipulator_1.ResourcePropertyManipulator));
exports.ResourceColorManipulator = ResourceColorManipulator;
/***/ }),
/* 186 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourcePropertyManipulator = void 0;
var tslib_1 = __webpack_require__(0);
var HistoryItemState_1 = __webpack_require__(80);
var BaseManipulator_1 = __webpack_require__(18);
var ResourcePropertyManipulator = (function (_super) {
(0, tslib_1.__extends)(ResourcePropertyManipulator, _super);
function ResourcePropertyManipulator() {
return _super !== null && _super.apply(this, arguments) || this;
}
ResourcePropertyManipulator.prototype.setValue = function (id, newValue) {
var _this = this;
var resource = this.viewModel.resources.getItemById(id);
var oldState = new HistoryItemState_1.HistoryItemState(id, this.getPropertyValue(resource));
this.setPropertyValue(resource, newValue);
var assignments = this.viewModel.assignments.items.filter(function (a) { return a.resourceId === resource.internalId; });
assignments.forEach(function (a) {
var viewItem = _this.viewModel.findItem(a.taskId);
var index = viewItem.visibleIndex;
_this.renderHelper.recreateTaskElement(index);
});
return oldState;
};
ResourcePropertyManipulator.prototype.restoreValue = function (state) {
var _this = this;
if (!state)
return;
var stateValue = state.value;
var resource = this.viewModel.resources.getItemById(state.id);
this.setPropertyValue(resource, stateValue);
var assignments = this.viewModel.assignments.items.filter(function (a) { return a.resourceId === resource.internalId; });
assignments.forEach(function (a) {
var viewItem = _this.viewModel.findItem(a.taskId);
var index = viewItem.visibleIndex;
_this.renderHelper.recreateTaskElement(index);
});
};
return ResourcePropertyManipulator;
}(BaseManipulator_1.BaseManipulator));
exports.ResourcePropertyManipulator = ResourcePropertyManipulator;
/***/ }),
/* 187 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskManipulator = void 0;
var tslib_1 = __webpack_require__(0);
var BaseManipulator_1 = __webpack_require__(18);
var TaskPropertiesManipulator_1 = __webpack_require__(188);
var TaskManipulator = (function (_super) {
(0, tslib_1.__extends)(TaskManipulator, _super);
function TaskManipulator(viewModel, dispatcher) {
var _this = _super.call(this, viewModel, dispatcher) || this;
_this.properties = new TaskPropertiesManipulator_1.TaskPropertiesManipulator(viewModel, dispatcher);
return _this;
}
TaskManipulator.prototype.create = function (data, id, callback) {
var _this = this;
var task = this.viewModel.tasks.createItem();
task.start = data.start;
task.end = data.end;
task.title = data.title;
task.progress = data.progress;
if (data.color)
task.color = data.color;
var parentItem = this.viewModel.tasks.getItemById(data.parentId);
if (parentItem)
parentItem.expanded = true;
task.parentId = data.parentId;
if (id)
task.internalId = id;
task.id = task.internalId;
this.viewModel.tasks.add(task);
this.viewModel.updateModel();
this.dispatcher.notifyTaskCreated(this.getObjectForDataSource(task), function (id) {
task.id = id;
if (callback)
callback();
if (_this.viewModel.requireFirstLoadParentAutoCalc) {
var data_1 = _this.viewModel.getCurrentTaskData().map(function (t) {
if (t.parentId === "")
t.parentId = null;
return t;
});
_this.dispatcher.notifyParentDataRecalculated(data_1);
}
}, this.getErrorCallback());
this.viewModel.owner.resetAndUpdate();
return task;
};
TaskManipulator.prototype.remove = function (taskId) {
var task = this.viewModel.tasks.getItemById(taskId);
if (!task)
throw new Error("Invalid task id");
var dependencies = this.viewModel.dependencies.items.filter(function (d) { return d.predecessorId == taskId || d.successorId == taskId; });
if (dependencies.length)
throw new Error("Can't delete task with dependency");
var assignments = this.viewModel.assignments.items.filter(function (a) { return a.taskId == taskId; });
if (assignments.length)
throw new Error("Can't delete task with assigned resource");
this.viewModel.tasks.remove(task);
this.dispatcher.notifyTaskRemoved(task.id, this.getErrorCallback(), this.viewModel.getTaskObjectForDataSource(task));
this.viewModel.updateModel();
this.viewModel.owner.resetAndUpdate();
return task;
};
TaskManipulator.prototype.getObjectForDataSource = function (task) {
return this.viewModel.getTaskObjectForDataSource(task);
};
return TaskManipulator;
}(BaseManipulator_1.BaseManipulator));
exports.TaskManipulator = TaskManipulator;
/***/ }),
/* 188 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskPropertiesManipulator = void 0;
var tslib_1 = __webpack_require__(0);
var BaseManipulator_1 = __webpack_require__(18);
var TaskColorManipulator_1 = __webpack_require__(189);
var TaskDescriptionManipulator_1 = __webpack_require__(190);
var TaskEndDateManipulator_1 = __webpack_require__(191);
var TaskMoveManipulator_1 = __webpack_require__(192);
var TaskProgressManipulator_1 = __webpack_require__(193);
var TaskStartDateManipulator_1 = __webpack_require__(194);
var TaskTitleManipulator_1 = __webpack_require__(195);
var TaskPropertiesManipulator = (function (_super) {
(0, tslib_1.__extends)(TaskPropertiesManipulator, _super);
function TaskPropertiesManipulator(viewModel, dispatcher) {
var _this = _super.call(this, viewModel, dispatcher) || this;
_this.title = new TaskTitleManipulator_1.TaskTitleManipulator(viewModel, dispatcher);
_this.description = new TaskDescriptionManipulator_1.TaskDescriptionManipulator(viewModel, dispatcher);
_this.progress = new TaskProgressManipulator_1.TaskProgressManipulator(viewModel, dispatcher);
_this.start = new TaskStartDateManipulator_1.TaskStartDateManipulator(viewModel, dispatcher);
_this.end = new TaskEndDateManipulator_1.TaskEndDateManipulator(viewModel, dispatcher);
_this.move = new TaskMoveManipulator_1.TaskMoveManipulator(viewModel, dispatcher);
_this.color = new TaskColorManipulator_1.TaskColorManipulator(viewModel, dispatcher);
return _this;
}
return TaskPropertiesManipulator;
}(BaseManipulator_1.BaseManipulator));
exports.TaskPropertiesManipulator = TaskPropertiesManipulator;
/***/ }),
/* 189 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskColorManipulator = void 0;
var tslib_1 = __webpack_require__(0);
var TaskPropertyManipulator_1 = __webpack_require__(19);
var TaskColorManipulator = (function (_super) {
(0, tslib_1.__extends)(TaskColorManipulator, _super);
function TaskColorManipulator() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskColorManipulator.prototype.getPropertyValue = function (task) {
return task.color;
};
TaskColorManipulator.prototype.setPropertyValue = function (task, value) {
task.color = value;
this.dispatcher.notifyTaskColorChanged(task.id, value, this.getErrorCallback());
};
return TaskColorManipulator;
}(TaskPropertyManipulator_1.TaskPropertyManipulator));
exports.TaskColorManipulator = TaskColorManipulator;
/***/ }),
/* 190 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskDescriptionManipulator = void 0;
var tslib_1 = __webpack_require__(0);
var TaskPropertyManipulator_1 = __webpack_require__(19);
var TaskDescriptionManipulator = (function (_super) {
(0, tslib_1.__extends)(TaskDescriptionManipulator, _super);
function TaskDescriptionManipulator() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskDescriptionManipulator.prototype.getPropertyValue = function (task) {
return task.description;
};
TaskDescriptionManipulator.prototype.setPropertyValue = function (task, value) {
task.description = value;
this.dispatcher.notifyTaskDescriptionChanged(task.id, value, this.getErrorCallback());
};
return TaskDescriptionManipulator;
}(TaskPropertyManipulator_1.TaskPropertyManipulator));
exports.TaskDescriptionManipulator = TaskDescriptionManipulator;
/***/ }),
/* 191 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskEndDateManipulator = void 0;
var tslib_1 = __webpack_require__(0);
var TaskPropertyManipulator_1 = __webpack_require__(19);
var TaskEndDateManipulator = (function (_super) {
(0, tslib_1.__extends)(TaskEndDateManipulator, _super);
function TaskEndDateManipulator() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskEndDateManipulator.prototype.getPropertyValue = function (task) {
return task.end;
};
TaskEndDateManipulator.prototype.setPropertyValue = function (task, value) {
task.end = value;
this.dispatcher.notifyTaskEndChanged(task.id, value, this.getErrorCallback());
};
return TaskEndDateManipulator;
}(TaskPropertyManipulator_1.TaskPropertyManipulator));
exports.TaskEndDateManipulator = TaskEndDateManipulator;
/***/ }),
/* 192 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskMoveManipulator = void 0;
var tslib_1 = __webpack_require__(0);
var DateRange_1 = __webpack_require__(14);
var TaskPropertyManipulator_1 = __webpack_require__(19);
var TaskMoveManipulator = (function (_super) {
(0, tslib_1.__extends)(TaskMoveManipulator, _super);
function TaskMoveManipulator() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskMoveManipulator.prototype.getPropertyValue = function (task) {
return new DateRange_1.DateRange(task.start, task.end);
};
TaskMoveManipulator.prototype.setPropertyValue = function (task, value) {
task.start = value.start;
task.end = value.end;
this.dispatcher.notifyTaskStartChanged(task.id, value.start, this.getErrorCallback());
this.dispatcher.notifyTaskEndChanged(task.id, value.end, this.getErrorCallback());
};
return TaskMoveManipulator;
}(TaskPropertyManipulator_1.TaskPropertyManipulator));
exports.TaskMoveManipulator = TaskMoveManipulator;
/***/ }),
/* 193 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskProgressManipulator = void 0;
var tslib_1 = __webpack_require__(0);
var TaskPropertyManipulator_1 = __webpack_require__(19);
var TaskProgressManipulator = (function (_super) {
(0, tslib_1.__extends)(TaskProgressManipulator, _super);
function TaskProgressManipulator() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskProgressManipulator.prototype.getPropertyValue = function (task) {
return task.progress;
};
TaskProgressManipulator.prototype.setPropertyValue = function (task, value) {
value = value < 0 ? 0 : value > 100 ? 100 : value;
task.progress = value;
this.dispatcher.notifyTaskProgressChanged(task.id, value, this.getErrorCallback());
};
return TaskProgressManipulator;
}(TaskPropertyManipulator_1.TaskPropertyManipulator));
exports.TaskProgressManipulator = TaskProgressManipulator;
/***/ }),
/* 194 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskStartDateManipulator = void 0;
var tslib_1 = __webpack_require__(0);
var TaskPropertyManipulator_1 = __webpack_require__(19);
var TaskStartDateManipulator = (function (_super) {
(0, tslib_1.__extends)(TaskStartDateManipulator, _super);
function TaskStartDateManipulator() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskStartDateManipulator.prototype.getPropertyValue = function (task) {
return task.start;
};
TaskStartDateManipulator.prototype.setPropertyValue = function (task, value) {
task.start = value;
this.dispatcher.notifyTaskStartChanged(task.id, value, this.getErrorCallback());
};
return TaskStartDateManipulator;
}(TaskPropertyManipulator_1.TaskPropertyManipulator));
exports.TaskStartDateManipulator = TaskStartDateManipulator;
/***/ }),
/* 195 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskTitleManipulator = void 0;
var tslib_1 = __webpack_require__(0);
var TaskPropertyManipulator_1 = __webpack_require__(19);
var TaskTitleManipulator = (function (_super) {
(0, tslib_1.__extends)(TaskTitleManipulator, _super);
function TaskTitleManipulator() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskTitleManipulator.prototype.getPropertyValue = function (task) {
return task.title;
};
TaskTitleManipulator.prototype.setPropertyValue = function (task, value) {
task.title = value;
this.dispatcher.notifyTaskTitleChanged(task.id, value, this.getErrorCallback());
};
return TaskTitleManipulator;
}(TaskPropertyManipulator_1.TaskPropertyManipulator));
exports.TaskTitleManipulator = TaskTitleManipulator;
/***/ }),
/* 196 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PdfGanttExporter = void 0;
var PageDrawer_1 = __webpack_require__(197);
var PdfGanttExporter = (function () {
function PdfGanttExporter(info) {
if (!info.settings.pdfDoc && !info.settings.docCreateMethod)
throw new Error("Cannot convert gantt to pdf without document instance!");
this._info = info;
}
PdfGanttExporter.prototype.export = function () {
var _a, _b;
var pdfDoc = this.pdfDoc;
var info = this._info;
var drawer = new PageDrawer_1.PdfGanttPageDrawer(pdfDoc, info.settings);
var pages = info.getPages(pdfDoc);
var count = pages.length;
for (var i = 0; i < count; i++) {
if (i > 0)
pdfDoc.addPage(this.getDocumentFormat(), this.getOrientation());
var page = pages[i];
drawer.drawPage(page);
}
if ((_a = this.props) === null || _a === void 0 ? void 0 : _a.fileName)
pdfDoc.save((_b = this.props) === null || _b === void 0 ? void 0 : _b.fileName);
return pdfDoc;
};
Object.defineProperty(PdfGanttExporter.prototype, "pdfDoc", {
get: function () {
var _a, _b;
(_a = this._pdfDoc) !== null && _a !== void 0 ? _a : (this._pdfDoc = (_b = this._info.settings.pdfDoc) !== null && _b !== void 0 ? _b : this.createDoc());
return this._pdfDoc;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PdfGanttExporter.prototype, "props", {
get: function () {
return this._info.settings;
},
enumerable: false,
configurable: true
});
PdfGanttExporter.prototype.createDoc = function () {
var jsPDFProps = this.getJsPDFProps();
return this._info.settings.docCreateMethod(jsPDFProps);
};
PdfGanttExporter.prototype.getJsPDFProps = function () {
var props = { putOnlyUsedFonts: true, unit: "px", hotfixes: ["px_scaling"] };
props["orientation"] = this.getOrientation();
props["format"] = this.getDocumentFormat();
return props;
};
PdfGanttExporter.prototype.getOrientation = function () {
var _a;
return ((_a = this.props) === null || _a === void 0 ? void 0 : _a.landscape) ? "l" : "p";
};
PdfGanttExporter.prototype.getDocumentFormat = function () {
var _a, _b, _c, _d;
if (!((_a = this.props) === null || _a === void 0 ? void 0 : _a.format) && !((_b = this.props) === null || _b === void 0 ? void 0 : _b.pageSize))
return "a4";
if ((_c = this.props) === null || _c === void 0 ? void 0 : _c.pageSize)
return [this.props.pageSize.height, this.props.pageSize.width];
return (_d = this.props) === null || _d === void 0 ? void 0 : _d.format;
};
return PdfGanttExporter;
}());
exports.PdfGanttExporter = PdfGanttExporter;
/***/ }),
/* 197 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PdfGanttPageDrawer = void 0;
var point_1 = __webpack_require__(4);
var Drawer_1 = __webpack_require__(198);
var Interfaces_1 = __webpack_require__(29);
var Props_1 = __webpack_require__(54);
var Drawer_2 = __webpack_require__(199);
var PdfGanttPageDrawer = (function () {
function PdfGanttPageDrawer(pdfDoc, props) {
this._pdfDoc = pdfDoc;
this._props = props;
}
PdfGanttPageDrawer.prototype.drawPage = function (info) {
var pdfDoc = this._pdfDoc;
var tableDrawer = new Drawer_2.PdfGanttTableDrawer(pdfDoc);
if (this.needDrawChart()) {
tableDrawer.drawTable(info.tables[Interfaces_1.PdfPageTableNames.chartMain]);
var objectDrawer = new Drawer_1.PdfObjectDrawer(pdfDoc, info.objects);
objectDrawer.draw();
tableDrawer.drawTable(info.tables[Interfaces_1.PdfPageTableNames.chartScaleTop]);
tableDrawer.drawTable(info.tables[Interfaces_1.PdfPageTableNames.chartScaleBottom]);
}
if (this.needDrawTreeList()) {
tableDrawer.drawTable(info.tables[Interfaces_1.PdfPageTableNames.treeListMain]);
tableDrawer.drawTable(info.tables[Interfaces_1.PdfPageTableNames.treeListHeader]);
}
this.drawMargins(info);
return pdfDoc;
};
PdfGanttPageDrawer.prototype.needDrawChart = function () {
return !this._props || this._props.exportMode === Props_1.ExportMode.all || this._props.exportMode === Props_1.ExportMode.chart;
};
PdfGanttPageDrawer.prototype.needDrawTreeList = function () {
return !this._props || this._props.exportMode === Props_1.ExportMode.all || this._props.exportMode === Props_1.ExportMode.treeList;
};
PdfGanttPageDrawer.prototype.getContentRightBottom = function (info) {
var p = new point_1.Point(0, 0);
for (var key in info.tables)
if (Object.prototype.hasOwnProperty.call(info.tables, key)) {
var table = info.tables[key];
p.x = Math.max(p.x, table.position.x + table.size.width);
p.y = Math.max(p.y, table.position.y + table.size.height);
}
return p;
};
PdfGanttPageDrawer.prototype.drawMargins = function (info) {
var pdfDoc = this._pdfDoc;
var props = this._props;
var docWidth = pdfDoc.getPageWidth();
var docHeight = pdfDoc.getPageHeight();
var p = this.getContentRightBottom(info);
pdfDoc.setFillColor(255, 255, 255);
pdfDoc.rect(0, 0, props.margins.left, docHeight, "F");
pdfDoc.rect(0, 0, docWidth, props.margins.top, "F");
pdfDoc.rect(p.x, 0, docWidth, docHeight, "F");
pdfDoc.rect(0, p.y, docWidth, docHeight, "F");
};
return PdfGanttPageDrawer;
}());
exports.PdfGanttPageDrawer = PdfGanttPageDrawer;
/***/ }),
/* 198 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PdfObjectDrawer = void 0;
var Enums_1 = __webpack_require__(2);
var Ellipsis_1 = __webpack_require__(81);
var TaskInfo_1 = __webpack_require__(52);
var PdfObjectDrawer = (function () {
function PdfObjectDrawer(pdfDoc, info) {
this._FONT_ROW_RATIO = 1.15;
this._info = info;
this._pdfDoc = pdfDoc;
}
PdfObjectDrawer.prototype.draw = function () {
this.drawTimeMarkers();
this.drawDependencies();
this.drawTasks();
this.drawResources();
};
PdfObjectDrawer.prototype.drawTasks = function () {
var _this = this;
var _a;
var tasks = (_a = this._info) === null || _a === void 0 ? void 0 : _a.tasks;
if (tasks)
tasks.forEach(function (t) { return _this.drawTask(t); });
};
PdfObjectDrawer.prototype.drawTask = function (info) {
var pdfDoc = this._pdfDoc;
pdfDoc.setFillColor.apply(pdfDoc, info.taskColor.getRBGColor());
pdfDoc.setDrawColor.apply(pdfDoc, info.taskColor.getRBGColor());
if (info.isMilestone)
this.drawMilestone(info);
else
this.drawRegularTask(info);
};
PdfObjectDrawer.prototype.drawMilestone = function (info) {
var pdfDoc = this._pdfDoc;
var x1 = info.sidePoints[0].x;
var y1 = info.sidePoints[0].y;
var x2 = info.sidePoints[1].x;
var y2 = info.sidePoints[1].y;
var x3 = info.sidePoints[2].x;
var y3 = info.sidePoints[2].y;
var x4 = info.sidePoints[3].x;
var y4 = info.sidePoints[3].y;
pdfDoc.triangle(x1, y1, x2, y2, x3, y3, "FD");
pdfDoc.triangle(x1, y1, x4, y4, x3, y3, "FD");
};
PdfObjectDrawer.prototype.drawRegularTask = function (info) {
var pdfDoc = this._pdfDoc;
pdfDoc.rect(info.left, info.top, info.width, info.height, "FD");
if (info.isParent)
this.drawParentBorder(info);
if (info.progressWidth) {
pdfDoc.setFillColor.apply(pdfDoc, info.progressColor.getRBGColor());
pdfDoc.rect(info.left, info.top, info.progressWidth, info.height, "F");
}
if (info.text)
this.printTaskTitle(info);
};
PdfObjectDrawer.prototype.drawParentBorder = function (info) {
var pdfDoc = this._pdfDoc;
var left = info.sidePoints[0].x;
var top = info.sidePoints[1].y;
var bottom = info.sidePoints[3].y;
var right = info.sidePoints[2].x;
var height = info.sidePoints[3].y - info.sidePoints[1].y;
var leftBorderColor = info.progressWidth > height ? info.progressColor.getRBGColor() : info.taskColor.getRBGColor();
pdfDoc.setFillColor.apply(pdfDoc, leftBorderColor);
pdfDoc.triangle(left, top, left, bottom, left + height, top, "FD");
pdfDoc.setFillColor.apply(pdfDoc, info.taskColor.getRBGColor());
pdfDoc.triangle(right, top, right, bottom, right - height, top, "FD");
};
PdfObjectDrawer.prototype.printTaskTitle = function (info) {
var pdfDoc = this._pdfDoc;
var style = info.textStyle;
var colorArray = style && style.textColor.getRBGColor();
var fontSize = style && style.fontSize;
pdfDoc.setTextColor.apply(pdfDoc, colorArray);
pdfDoc.setFontSize(fontSize);
var textPosX;
var textPosY = info.top + fontSize * this._FONT_ROW_RATIO / pdfDoc.internal.scaleFactor;
if (info.isParent)
textPosY -= TaskInfo_1.PdfTaskInfo.defaultParentHeightCorrection;
var leftPadding = style && style.cellPadding.left || 0;
var rightPadding = style && style.cellPadding.right || 0;
if (info.textPosition === Enums_1.TaskTitlePosition.Inside) {
var textWidth = info.width - leftPadding - rightPadding;
textPosX = info.left + leftPadding;
pdfDoc.text(Ellipsis_1.EllipsisHelper.limitPdfTextWithEllipsis(info.text, pdfDoc, textWidth), textPosX, textPosY);
}
else {
textPosX = info.left - rightPadding;
pdfDoc.text(info.text, textPosX, textPosY, { align: "right" });
}
};
PdfObjectDrawer.prototype.drawDependencies = function () {
var _this = this;
var _a;
var dependencies = (_a = this._info) === null || _a === void 0 ? void 0 : _a.dependencies;
if (dependencies)
dependencies.forEach(function (d) { return _this.drawDependencyLine(d); });
};
PdfObjectDrawer.prototype.drawDependencyLine = function (line) {
var _a, _b;
(_a = this._pdfDoc).setFillColor.apply(_a, line.fillColor.getRBGColor());
(_b = this._pdfDoc).setDrawColor.apply(_b, line.fillColor.getRBGColor());
if (line.arrowInfo)
this.drawArrow(line);
else {
var points = line.points;
this._pdfDoc.line(points[0].x, points[0].y, points[1].x, points[1].y);
}
};
PdfObjectDrawer.prototype.isValidLine = function (line) {
var points = line.points;
return !isNaN(points[0].x) && !isNaN(points[0].y) && !isNaN(points[1].x) && !isNaN(points[1].y);
};
PdfObjectDrawer.prototype.drawArrow = function (line) {
var width = line.arrowInfo.width || 0;
var left = line.points[0].x;
var top = line.points[0].y;
switch (line.arrowInfo.position) {
case Enums_1.Position.Left:
this._pdfDoc.triangle(left, top + width, left + width, top, left + width, top + 2 * width, "FD");
break;
case Enums_1.Position.Right:
this._pdfDoc.triangle(left, top, left, top + 2 * width, left + width, top + width, "FD");
break;
case Enums_1.Position.Top:
this._pdfDoc.triangle(left, top + width, left + width, top, left + 2 * width, top + width, "FD");
break;
case Enums_1.Position.Bottom:
this._pdfDoc.triangle(left, top, left + width, top + width, left + 2 * width, top, "FD");
break;
}
};
PdfObjectDrawer.prototype.drawResources = function () {
var _this = this;
var _a;
var pdfDoc = this._pdfDoc;
var resources = (_a = this._info) === null || _a === void 0 ? void 0 : _a.resources;
if (resources)
resources.forEach(function (r) {
var _a, _b, _c;
pdfDoc.setFontSize((_a = r.style.fontSize) !== null && _a !== void 0 ? _a : 11);
var textPosY = r.y + r.style.fontSize * _this._FONT_ROW_RATIO / pdfDoc.internal.scaleFactor;
var paddingLeft = (_b = r.style.cellPadding.left) !== null && _b !== void 0 ? _b : 0;
var paddingRight = (_c = r.style.cellPadding.right) !== null && _c !== void 0 ? _c : 1;
var resWidth = Math.max(r.style.cellWidth.getValue(), paddingLeft + pdfDoc.getTextWidth(r.text) + paddingRight);
pdfDoc.setFillColor.apply(pdfDoc, r.style.fillColor.getRBGColor());
pdfDoc.rect(r.x, r.y, resWidth, r.style.minCellHeight, "F");
pdfDoc.setTextColor.apply(pdfDoc, r.style.textColor.getRBGColor());
pdfDoc.text(r.text, r.x + paddingLeft, textPosY);
});
};
PdfObjectDrawer.prototype.drawTimeMarkers = function () {
var _this = this;
var _a;
var markers = (_a = this._info) === null || _a === void 0 ? void 0 : _a.timeMarkers;
markers === null || markers === void 0 ? void 0 : markers.forEach(function (m) { return _this.drawTimeMarker(m); });
};
PdfObjectDrawer.prototype.drawTimeMarker = function (marker) {
var _a;
var _b;
var pdfDoc = this._pdfDoc;
var isInterval = marker.size.width > 1;
var x = marker.start.x;
var y = marker.start.y;
var width = marker.size.width;
var height = marker.size.height;
var needDrawBorders = marker.isStripLine;
if (isInterval) {
pdfDoc.setFillColor.apply(pdfDoc, marker.color.getRBGColor());
pdfDoc.saveGraphicsState();
pdfDoc.setGState(new pdfDoc.GState({ opacity: (_b = marker.color.opacity) !== null && _b !== void 0 ? _b : 1 }));
pdfDoc.rect(x, y, width, height, "F");
pdfDoc.restoreGraphicsState();
}
if (needDrawBorders) {
this._pdfDoc.setLineDashPattern([3]);
(_a = this._pdfDoc).setDrawColor.apply(_a, marker.lineColor.getRBGColor());
if (isInterval)
this._pdfDoc.line(x + width, y, x + width, y + height, "S");
this._pdfDoc.line(x, y, x, y + height, "S");
this._pdfDoc.setLineDashPattern();
}
};
return PdfObjectDrawer;
}());
exports.PdfObjectDrawer = PdfObjectDrawer;
/***/ }),
/* 199 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PdfGanttTableDrawer = void 0;
var common_1 = __webpack_require__(1);
var Interfaces_1 = __webpack_require__(29);
var Ellipsis_1 = __webpack_require__(81);
var TableOptions_1 = __webpack_require__(200);
var PdfGanttTableDrawer = (function () {
function PdfGanttTableDrawer(pdfDoc) {
this._pdfDoc = pdfDoc;
}
PdfGanttTableDrawer.prototype.drawTable = function (info) {
if (info) {
var options = this.createTableOptions(info);
this._pdfDoc.autoTable(options.getValue());
}
};
PdfGanttTableDrawer.prototype.createTableOptions = function (info) {
var options = this.createDefaultTableOptions();
this.addTableCommonSettings(info, options);
this.addCommonTableStyles(info, options);
this.prepareBodyCells(info);
options.addBody(info.cells);
if (info.hideRowLines)
this.hideRowLines(options);
return options;
};
PdfGanttTableDrawer.prototype.createDefaultTableOptions = function () {
var options = new TableOptions_1.TableOptions();
options.pageBreak = "auto";
options.margin.assign(0);
options.tableWidth.assign("auto");
options.styles.cellPadding.assign(0);
options.styles.halign = "center";
options.styles.valign = "middle";
options.styles.lineWidth = 1;
options.styles.overflow = "hidden";
return options;
};
PdfGanttTableDrawer.prototype.addTableCommonSettings = function (info, options) {
options.startY = info.position.y;
options.margin.assign({ left: info.position.x });
options.tableWidth.assign(info.size.width);
};
PdfGanttTableDrawer.prototype.addCommonTableStyles = function (info, tableInfo) {
var styles = tableInfo.styles;
styles.assign(info.style);
if (styles.fillColor.opacity === 0)
styles.fillColor.assign("#FFFFFF");
styles.minCellHeight = info.baseCellSize.height;
tableInfo.alternateRowStyles.minCellHeight = tableInfo.styles.minCellHeight;
tableInfo.alternateRowStyles.fillColor.assign(tableInfo.styles.fillColor);
if ((0, common_1.isDefined)(info.baseCellSize.width))
styles.cellWidth.assign(info.baseCellSize.width);
};
PdfGanttTableDrawer.prototype.prepareBodyCells = function (info) {
var _a, _b, _c;
var needCheckText = info.name === Interfaces_1.PdfPageTableNames.treeListMain || info.name === Interfaces_1.PdfPageTableNames.chartScaleTop || info.name === Interfaces_1.PdfPageTableNames.chartScaleBottom;
if (needCheckText) {
var source = info.cells;
for (var i = 0; i < source.length; i++) {
var sourceRow = source[i];
for (var j = 0; j < sourceRow.length; j++) {
var cell = sourceRow[j];
var styles = cell.styles;
var width = ((_a = styles === null || styles === void 0 ? void 0 : styles.cellWidth) === null || _a === void 0 ? void 0 : _a.getValue()) || info.baseCellSize.width || 0;
var leftPadding = (_b = styles === null || styles === void 0 ? void 0 : styles.cellPadding.left) !== null && _b !== void 0 ? _b : 0;
var rightPadding = (_c = styles === null || styles === void 0 ? void 0 : styles.cellPadding.right) !== null && _c !== void 0 ? _c : 0;
var textWidth = Math.max(width - leftPadding - rightPadding - PdfGanttTableDrawer.cellEllipsisSpace, 0);
cell.content = Ellipsis_1.EllipsisHelper.limitPdfTextWithEllipsis(cell.content, this._pdfDoc, textWidth);
}
}
}
};
PdfGanttTableDrawer.prototype.hideRowLines = function (options) {
options.styles.lineWidth = 0;
options.onDrawCellCallback = function (data) {
var cell = data.cell;
var doc = data.doc;
var color = cell.styles.lineColor;
var left = cell.x;
var right = cell.x + cell.styles.cellWidth;
var top = cell.y;
var bottom = cell.y + data.row.height;
var isLastColumn = data.column.index === data.table.columns.length - 1;
var isLastRow = data.row.index === data.table.body.length - 1;
var isFirstRow = data.row.index === 0;
doc.setDrawColor(color[0], color[1], color[2]);
doc.setLineWidth(1);
doc.line(left, bottom, left, top);
if (isLastColumn)
doc.line(right, bottom, right, top);
if (isFirstRow)
doc.line(left, top, right, top);
if (isLastRow)
doc.line(left, bottom, right, bottom);
};
};
PdfGanttTableDrawer.cellEllipsisSpace = 3;
return PdfGanttTableDrawer;
}());
exports.PdfGanttTableDrawer = PdfGanttTableDrawer;
/***/ }),
/* 200 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TableOptions = void 0;
var common_1 = __webpack_require__(1);
var CellDef_1 = __webpack_require__(53);
var Color_1 = __webpack_require__(17);
var PredefinedStyles_1 = __webpack_require__(51);
var Margin_1 = __webpack_require__(40);
var StyleDef_1 = __webpack_require__(28);
var Width_1 = __webpack_require__(78);
var TableOptions = (function () {
function TableOptions() {
this._margin = new Margin_1.Margin();
this._tableLineColor = new Color_1.Color();
this._tableWidth = new Width_1.Width();
this._styles = new StyleDef_1.StyleDef();
this._alternateRowStyles = new StyleDef_1.StyleDef();
}
Object.defineProperty(TableOptions.prototype, "pageBreak", {
get: function () { return this._pageBreak; },
set: function (value) { this._pageBreak = PredefinedStyles_1.PredefinedStyles.getPredefinedStringOrUndefined(value, PredefinedStyles_1.PredefinedStyles.pageBreak); },
enumerable: false,
configurable: true
});
Object.defineProperty(TableOptions.prototype, "rowPageBreak", {
get: function () { return this._rowPageBreak; },
set: function (value) { this._rowPageBreak = PredefinedStyles_1.PredefinedStyles.getPredefinedStringOrUndefined(value, PredefinedStyles_1.PredefinedStyles.rowPageBreak); },
enumerable: false,
configurable: true
});
Object.defineProperty(TableOptions.prototype, "showHead", {
get: function () { return this._showHead; },
set: function (value) { this._showHead = PredefinedStyles_1.PredefinedStyles.getPredefinedStringOrUndefined(value, PredefinedStyles_1.PredefinedStyles.headerFooterVisibility); },
enumerable: false,
configurable: true
});
Object.defineProperty(TableOptions.prototype, "showFoot", {
get: function () { return this._showFoot; },
set: function (value) { this._showFoot = PredefinedStyles_1.PredefinedStyles.getPredefinedStringOrUndefined(value, PredefinedStyles_1.PredefinedStyles.headerFooterVisibility); },
enumerable: false,
configurable: true
});
Object.defineProperty(TableOptions.prototype, "startY", {
get: function () { return this._startY; },
set: function (value) { this._startY = value; },
enumerable: false,
configurable: true
});
Object.defineProperty(TableOptions.prototype, "tableLineWidth", {
get: function () { return this._tableLineWidth; },
set: function (value) { this._tableLineWidth = value; },
enumerable: false,
configurable: true
});
Object.defineProperty(TableOptions.prototype, "margin", {
get: function () { return this._margin; },
enumerable: false,
configurable: true
});
Object.defineProperty(TableOptions.prototype, "tableLineColor", {
get: function () { return this._tableLineColor; },
enumerable: false,
configurable: true
});
Object.defineProperty(TableOptions.prototype, "tableWidth", {
get: function () { return this._tableWidth; },
enumerable: false,
configurable: true
});
Object.defineProperty(TableOptions.prototype, "body", {
get: function () { return this._body; },
enumerable: false,
configurable: true
});
Object.defineProperty(TableOptions.prototype, "styles", {
get: function () { return this._styles; },
enumerable: false,
configurable: true
});
Object.defineProperty(TableOptions.prototype, "alternateRowStyles", {
get: function () { return this._alternateRowStyles; },
enumerable: false,
configurable: true
});
TableOptions.prototype.hasValue = function () { return true; };
TableOptions.prototype.getValue = function () {
var _this = this;
var options = {};
options["pageBreak"] = this.pageBreak;
options["rowPageBreak"] = this.rowPageBreak;
options["showFoot"] = this.showFoot;
options["showHead"] = this.showHead;
options["startY"] = this.startY;
options["tableLineWidth"] = this.tableLineWidth;
this.getJsPdfProviderProps().forEach(function (key) {
var prop = _this[key];
if (prop && prop.hasValue())
options[key] = prop.getValue();
});
options["body"] = this.getBodyForJsPdf();
options["columnStyles"] = this.getColumnStylesForJsPdf();
if (this.onDrawCellCallback)
options["didDrawCell"] = this.onDrawCellCallback;
return options;
};
TableOptions.prototype.getJsPdfProviderProps = function () {
return [
"margin",
"tableLineColor",
"tableWidth",
"styles",
"alternateRowStyles"
];
};
TableOptions.prototype.getBodyForJsPdf = function () {
var result = [];
for (var i = 0; i < this._body.length; i++) {
var sourceRow = this._body[i];
var row = [];
for (var j = 0; j < sourceRow.length; j++)
row.push(sourceRow[j].getValue());
result.push(row);
}
return result;
};
TableOptions.prototype.assign = function (source) {
if (!source)
return;
if ((0, common_1.isDefined)(source["margin"]))
this.margin.assign(source["margin"]);
if ((0, common_1.isDefined)(source["pageBreak"]))
this.pageBreak = source["pageBreak"];
if ((0, common_1.isDefined)(source["rowPageBreak"]))
this.rowPageBreak = source["rowPageBreak"];
if ((0, common_1.isDefined)(source["showFoot"]))
this.showFoot = source["showFoot"];
if ((0, common_1.isDefined)(source["showHead"]))
this.showHead = source["showHead"];
if ((0, common_1.isDefined)(source["startY"]))
this.startY = source["startY"];
if ((0, common_1.isDefined)(source["tableLineWidth"]))
this.tableLineWidth = source["tableLineWidth"];
if ((0, common_1.isDefined)(source["tableLineColor"]))
this.tableLineColor.assign(source["tableLineColor"]);
if ((0, common_1.isDefined)(source["tableWidth"]))
this.tableWidth.assign(source["tableWidth"]);
};
TableOptions.prototype.addBody = function (source) {
if (!source)
return;
this._body = new Array();
this.addCells(source, this._body);
};
TableOptions.prototype.addCells = function (source, target) {
var tableBackColor = this.styles.fillColor;
for (var i = 0; i < source.length; i++) {
var sourceRow = source[i];
var row = new Array();
for (var j = 0; j < sourceRow.length; j++) {
var cell = new CellDef_1.CellDef(sourceRow[j]);
if (tableBackColor.hasValue() && cell.styles && cell.styles.fillColor.hasValue())
cell.styles.fillColor.applyOpacityToBackground(tableBackColor);
row.push(cell);
}
target.push(row);
}
};
TableOptions.prototype.applyColumnStyle = function (key, style) {
var _a;
(_a = this._columnStyles) !== null && _a !== void 0 ? _a : (this._columnStyles = new Array());
this._columnStyles[key] = new StyleDef_1.StyleDef(style);
};
TableOptions.prototype.getColumnStylesForJsPdf = function () {
if (this._columnStyles) {
var result_1 = {};
this._columnStyles.forEach(function (v, i) {
if (v)
result_1[i] = v.getValue();
});
return result_1;
}
return null;
};
return TableOptions;
}());
exports.TableOptions = TableOptions;
/***/ }),
/* 201 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RenderHelper = void 0;
var ConnectorLinesRender_1 = __webpack_require__(202);
var EtalonsHelper_1 = __webpack_require__(203);
var EtalonSizeValues_1 = __webpack_require__(204);
var GanttView_1 = __webpack_require__(55);
var GridLayoutCalculator_1 = __webpack_require__(16);
var NoWorkingIntervalRender_1 = __webpack_require__(205);
var ResourceRender_1 = __webpack_require__(206);
var ScaleRender_1 = __webpack_require__(207);
var StripLinesRender_1 = __webpack_require__(208);
var TaskAreaManager_1 = __webpack_require__(209);
var TaskAreaRender_1 = __webpack_require__(210);
var TaskRender_1 = __webpack_require__(211);
var MainElementsRender_1 = __webpack_require__(213);
var size_1 = __webpack_require__(11);
var TaskAreaContainer_1 = __webpack_require__(214);
var ElementTextHelper_1 = __webpack_require__(215);
var RenderHelper = (function () {
function RenderHelper(ganttView) {
this.hlRowElements = [];
this.renderedColIndices = [];
this.renderedRowIndices = [];
this.invalidTaskDependencies = [];
this.etalonSizeValues = new EtalonSizeValues_1.EtalonSizeValues();
this._gridLayoutCalculator = new GridLayoutCalculator_1.GridLayoutCalculator();
this._ganttView = ganttView;
this._connectorLinesRender = new ConnectorLinesRender_1.ConnectorLinesRender(this);
this._etalonsHelper = new EtalonsHelper_1.EtalonsHelper(this);
this._noWorkingIntervalRender = new NoWorkingIntervalRender_1.NoWorkingIntervalRender(this);
this._resourceRender = new ResourceRender_1.ResourseRender(this);
this._scaleRender = new ScaleRender_1.ScaleRender(this);
this._stripLinesRender = new StripLinesRender_1.StripLinesRender(this);
this._taskAreaRender = new TaskAreaRender_1.TaskAreaRender(this);
this._taskRender = new TaskRender_1.TaskRender(this);
this._mainElementsRender = new MainElementsRender_1.MainElementsRender();
}
RenderHelper.prototype.reset = function () {
this._taskArea.innerHTML = "";
this._taskAreaRender.reset();
this._scaleRender.reset();
this._taskRender.reset();
this.hlRowElements = [];
this.renderedRowIndices = [];
this.renderedColIndices = [];
this._connectorLinesRender.reset();
this._stripLinesRender.reset();
this._noWorkingIntervalRender.reset();
this.invalidTaskDependencies = [];
};
RenderHelper.prototype.createMainElement = function (parent) {
this.mainElement = this._mainElementsRender.createMainElement(parent);
parent.appendChild(this.mainElement);
};
RenderHelper.prototype.createHeader = function () {
this.header = this._mainElementsRender.createHeader();
this.mainElement.appendChild(this.header);
};
RenderHelper.prototype.init = function (tickSize, range, viewType, viewModel, firstDayOfWeek) {
if (firstDayOfWeek === void 0) { firstDayOfWeek = 0; }
this._elementTextHelper.setFont(this.mainElement);
this.setupHelpers(tickSize, range, viewType, viewModel, firstDayOfWeek);
this.setSizeForTaskArea();
this.createTimeScale();
this._taskAreaManager = new TaskAreaManager_1.TaskAreaManager(this._ganttView);
};
RenderHelper.prototype.initMarkup = function (element) {
this._elementTextHelper = new ElementTextHelper_1.ElementTextHelper(this.ganttViewSettings.cultureInfo);
this.createMainElement(element);
this.createHeader();
this._etalonsHelper.calculateEtalonSizeValues();
this._taskAreaRender.createTaskAreaContainer();
};
RenderHelper.prototype.processScroll = function (isVertical) {
this._taskAreaRender.recreateTaskAreaBordersAndTaskElements(isVertical);
if (isVertical)
this._connectorLinesRender.recreateConnectorLineElements();
else {
this._noWorkingIntervalRender.recreateNoWorkingIntervalElements();
this._stripLinesRender.recreateStripLines();
this._scaleRender.recreateScalesElements();
}
};
Object.defineProperty(RenderHelper.prototype, "ganttViewSettings", {
get: function () {
return this._ganttView.settings;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "taskTextHeightKey", {
get: function () {
return GanttView_1.GanttView.taskTextHeightKey;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "showResources", {
get: function () {
return this.ganttViewSettings.showResources;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "showDependencies", {
get: function () {
return this.ganttViewSettings.showDependencies;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "viewModelItems", {
get: function () {
return this._ganttView.viewModel.items;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "stripLines", {
get: function () {
return this.ganttViewSettings.stripLines;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "range", {
get: function () {
return this._ganttView.range;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "viewType", {
get: function () {
return this.ganttViewSettings.viewType;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "taskTitlePosition", {
get: function () {
return this.ganttViewSettings.taskTitlePosition;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "tickSize", {
get: function () {
return this._ganttView.tickSize;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "ganttViewTaskAreaContainerScrollTop", {
get: function () {
return this._ganttView.taskAreaContainerScrollTop;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "ganttTaskAreaContainerScrollLeft", {
get: function () {
return this._ganttView.taskAreaContainerScrollLeft;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "scaleCount", {
get: function () {
return this._ganttView.scaleCount;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "areHorizontalBordersEnabled", {
get: function () {
return this.ganttViewSettings.areHorizontalBordersEnabled;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "taskEditController", {
get: function () {
return this._ganttView.taskEditController;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "taskArea", {
get: function () {
return this._taskArea;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "taskAreaManager", {
get: function () {
var _a;
(_a = this._taskAreaManager) !== null && _a !== void 0 ? _a : (this._taskAreaManager = new TaskAreaManager_1.TaskAreaManager(this._ganttView));
return this._taskAreaManager;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "taskAreaContainerScrollTop", {
get: function () {
return this._taskAreaRender.taskAreaContainer.scrollTop;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "taskAreaContainerScrollLeft", {
get: function () {
return this._taskAreaRender.taskAreaContainer.scrollLeft;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "taskAreaContainer", {
get: function () {
return this._taskAreaRender.taskAreaContainer;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "isExternalTaskAreaContainer", {
get: function () {
return this._taskAreaRender.taskAreaContainer.isExternal;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "fakeTaskWrapper", {
get: function () {
return this._taskRender.fakeTaskWrapper;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "taskElements", {
get: function () {
return this._taskRender.taskElements;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "selectionElements", {
get: function () {
return this._taskRender.selectionElements;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "scaleElements", {
get: function () {
return this._scaleRender.scaleElements;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "scaleBorders", {
get: function () {
return this._scaleRender.scaleBorders;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "timeScaleContainer", {
get: function () {
return this._scaleRender.timeScaleContainer;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "gridLayoutCalculator", {
get: function () {
return this._gridLayoutCalculator;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "etalonScaleItemWidths", {
get: function () {
return this.etalonSizeValues.scaleItemWidths[this.viewType];
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "elementTextHelperCultureInfo", {
get: function () {
return this._elementTextHelper.cultureInfo;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "noWorkingIntervalsToElementsMap", {
get: function () {
return this._noWorkingIntervalRender.noWorkingIntervalsToElementsMap;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "stripLinesMap", {
get: function () {
return this._stripLinesRender.stripLinesMap;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "renderedConnectorLines", {
get: function () {
return this._connectorLinesRender.renderedConnectorLines;
},
enumerable: false,
configurable: true
});
Object.defineProperty(RenderHelper.prototype, "resourcesElements", {
get: function () {
return this._resourceRender.resourcesElements;
},
enumerable: false,
configurable: true
});
RenderHelper.prototype.setupHelpers = function (tickSize, range, viewType, viewModel, firstDayOfWeek) {
if (firstDayOfWeek === void 0) { firstDayOfWeek = 0; }
var size = new size_1.Size(this._taskAreaRender.taskAreaContainer.getWidth(), this._taskAreaRender.taskAreaContainer.getHeight());
var scrollBarHeight = this._taskAreaRender.taskAreaContainer.getHeight() - this._taskAreaRender.taskAreaContainer.getElement().clientHeight;
this._gridLayoutCalculator.setSettings(size, tickSize, this.etalonSizeValues, range, viewModel, viewType, scrollBarHeight, firstDayOfWeek);
this._elementTextHelper.setSettings(range.start.getTime(), viewType, viewModel.items);
};
RenderHelper.prototype.resetAndUpdate = function (tickSize, range, viewType, viewModel, firstDayOfWeek) {
if (firstDayOfWeek === void 0) { firstDayOfWeek = 0; }
this.reset();
this.setupHelpers(tickSize, range, viewType, viewModel, firstDayOfWeek);
this._scaleRender.createTimeScaleAreas();
this.setSizeForTaskArea();
};
RenderHelper.prototype.createConnectorLines = function () {
this._gridLayoutCalculator.createTileToConnectorLinesMap();
this._connectorLinesRender.recreateConnectorLineElements();
};
RenderHelper.prototype.getTargetDateByPos = function (leftPos) {
return this._gridLayoutCalculator.getDateByPos(this._taskAreaRender.taskAreaContainer.scrollLeft + leftPos);
};
RenderHelper.prototype.getExternalTaskAreaContainer = function (parent) {
return this._ganttView.getExternalTaskAreaContainer(parent);
};
RenderHelper.prototype.prepareExternalTaskAreaContainer = function (element, info) {
return this._ganttView.prepareExternalTaskAreaContainer(element, info);
};
RenderHelper.prototype.isAllowTaskAreaBorders = function (isVerticalScroll) {
return this._ganttView.allowTaskAreaBorders(isVerticalScroll);
};
RenderHelper.prototype.getHeaderHeight = function () {
return this._ganttView.getHeaderHeight();
};
RenderHelper.prototype.getViewItem = function (index) {
return this._ganttView.getViewItem(index);
};
RenderHelper.prototype.getTask = function (index) {
return this._ganttView.getTask(index);
};
RenderHelper.prototype.destroyTemplate = function (container) {
this._ganttView.destroyTemplate(container);
};
RenderHelper.prototype.getTaskDependencies = function (taskInternalId) {
return this._ganttView.getTaskDependencies(taskInternalId);
};
RenderHelper.prototype.getTaskResources = function (key) {
return this._ganttView.getTaskResources(key);
};
RenderHelper.prototype.isHighlightRowElementAllowed = function (index) {
return this._ganttView.isHighlightRowElementAllowed(index);
};
RenderHelper.prototype.recreateConnectorLineElement = function (dependencyId, forceRender) {
if (forceRender === void 0) { forceRender = false; }
this._connectorLinesRender.recreateConnectorLineElement(dependencyId, forceRender);
};
RenderHelper.prototype.recreateConnectorLineElemensts = function () {
this._connectorLinesRender.recreateConnectorLineElements();
};
RenderHelper.prototype.setMainElementWidth = function (value) {
this.mainElement.style.width = value + "px";
};
RenderHelper.prototype.setMainElementHeight = function (value) {
this.mainElement.style.height = value + "px";
};
RenderHelper.prototype.createResources = function (index) {
this._resourceRender.createResourcesWrapperElement(index);
this._resourceRender.createResources(index);
};
RenderHelper.prototype.createTimeScale = function () {
this._scaleRender.createTimeScaleContainer(this.header);
this._scaleRender.createTimeScaleAreas();
};
RenderHelper.prototype.setTimeScaleContainerScrollLeft = function (value) {
this._scaleRender.setTimeScaleContainerScrollLeft(value);
};
RenderHelper.prototype.recreateStripLines = function () {
if (this._stripLinesRender.recreateStripLines)
this._stripLinesRender.recreateStripLines();
};
RenderHelper.prototype.createTaskArea = function (parent) {
this._taskArea = this._taskAreaRender.createTaskArea();
parent.appendChild(this._taskArea);
};
RenderHelper.prototype.setSizeForTaskArea = function () {
this._taskAreaRender.setSizeForTaskArea();
};
RenderHelper.prototype.getTaskAreaContainerScrollLeft = function () {
return this._taskAreaRender.taskAreaContainer.scrollLeft;
};
RenderHelper.prototype.setTaskAreaContainerScrollLeft = function (leftPosition) {
this._taskAreaRender.taskAreaContainer.scrollLeft = leftPosition;
};
RenderHelper.prototype.setTaskAreaContainerScrollLeftToDate = function (date, addLeftPos) {
this._taskAreaRender.taskAreaContainer.scrollLeft = Math.round(this._gridLayoutCalculator.getPosByDate(date)) + addLeftPos;
};
RenderHelper.prototype.getTaskAreaContainer = function (element) {
return new TaskAreaContainer_1.TaskAreaContainer(element, this._ganttView);
};
RenderHelper.prototype.prepareTaskAreaContainer = function () {
this._taskAreaRender.prepareTaskAreaContainer();
};
RenderHelper.prototype.getTaskAreaContainerWidth = function () {
return this._taskAreaRender.taskAreaContainer.getWidth();
};
RenderHelper.prototype.createHighlightRowElement = function (index) {
this._taskAreaRender.createHighlightRowElement(index);
};
RenderHelper.prototype.getSmallTaskWidth = function (etalonPaddingLeft) {
return this._taskRender.getSmallTaskWidth(etalonPaddingLeft);
};
RenderHelper.prototype.getTaskAreaWidth = function () {
return this._taskAreaRender.getTaskAreaWidth();
};
RenderHelper.prototype.createTaskElement = function (index) {
this._taskRender.createTaskElement(index, this._ganttView.settings.taskContentTemplate);
};
RenderHelper.prototype.removeTaskElement = function (index) {
this._taskRender.removeTaskElement(index);
};
RenderHelper.prototype.recreateTaskElement = function (index) {
this._taskRender.recreateTaskElement(index);
};
RenderHelper.prototype.createDefaultTaskElement = function (index) {
this._taskRender.createDefaultTaskElement(index);
};
RenderHelper.prototype.getScaleItemText = function (index, scaleType) {
var start = this._gridLayoutCalculator.getScaleItemStart(index, scaleType);
return this.getScaleItemTextByStart(start, scaleType);
};
RenderHelper.prototype.getScaleItemTextByStart = function (start, scaleType) {
return this._elementTextHelper.getScaleItemText(start, scaleType);
};
RenderHelper.prototype.getTaskVisibility = function (index) {
return this.gridLayoutCalculator.isTaskInRenderedRange(index) && this._elementTextHelper.getTaskVisibility(index);
};
RenderHelper.prototype.getTaskResourcesVisibility = function (index) {
return this.getTaskVisibility(index) && !this.gridLayoutCalculator.isTaskCutByRange(index);
};
RenderHelper.prototype.getScaleItemTextTemplate = function (viewType) {
return this._elementTextHelper.getScaleItemTextTemplate(viewType);
};
RenderHelper.prototype.getTaskText = function (index) {
return this._elementTextHelper.getTaskText(index);
};
RenderHelper.prototype.taskAreaManagerDetachEvents = function () {
this.taskAreaManager.detachEvents();
};
RenderHelper.prototype.attachEventsOnTask = function (taskIndex) {
this.taskAreaManager.attachEventsOnTask(this._taskRender.taskElements[taskIndex]);
};
RenderHelper.prototype.detachEventsOnTask = function (taskIndex) {
this.taskAreaManager.detachEventsOnTask(this._taskRender.taskElements[taskIndex]);
};
return RenderHelper;
}());
exports.RenderHelper = RenderHelper;
/***/ }),
/* 202 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectorLinesRender = void 0;
var RenderElementUtils_1 = __webpack_require__(13);
var GridLayoutCalculator_1 = __webpack_require__(16);
var ConnectorLinesRender = (function () {
function ConnectorLinesRender(renderHelepr) {
this._connectorLinesToElementsMap = {};
this._renderedConnectorLines = [];
this._renderHelper = renderHelepr;
}
Object.defineProperty(ConnectorLinesRender.prototype, "taskEditController", {
get: function () {
return this._renderHelper.taskEditController;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ConnectorLinesRender.prototype, "taskAreaContainerScrollTop", {
get: function () {
return this._renderHelper.ganttViewTaskAreaContainerScrollTop;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ConnectorLinesRender.prototype, "gridLayoutCalculator", {
get: function () {
return this._renderHelper.gridLayoutCalculator;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ConnectorLinesRender.prototype, "connectorLinesToElementsMap", {
get: function () {
return this._connectorLinesToElementsMap;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ConnectorLinesRender.prototype, "taskArea", {
get: function () {
return this._renderHelper.taskArea;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ConnectorLinesRender.prototype, "invalidTaskDependencies", {
get: function () {
return this._renderHelper.invalidTaskDependencies;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ConnectorLinesRender.prototype, "showDependencies", {
get: function () {
return this._renderHelper.showDependencies;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ConnectorLinesRender.prototype, "renderedConnectorLines", {
get: function () {
return this._renderedConnectorLines;
},
enumerable: false,
configurable: true
});
ConnectorLinesRender.prototype.reset = function () {
this._connectorLinesToElementsMap = {};
this._renderedConnectorLines = [];
};
ConnectorLinesRender.prototype.createConnectorLineElement = function (info) {
if (!this.showDependencies)
return;
var dependencyId = info.attr["dependency-id"];
var isInvalid = this.invalidTaskDependencies.some(function (d) { return d.id == dependencyId; });
if (isInvalid)
return;
if (this.taskEditController.isDependencySelected(dependencyId))
info.className = info.className + " active";
var isArrow = info.className.indexOf(GridLayoutCalculator_1.GridLayoutCalculator.arrowClassName) > -1;
var element = RenderElementUtils_1.RenderElementUtils.create(info, null, this.taskArea, this.connectorLinesToElementsMap);
if (isArrow)
this.gridLayoutCalculator.checkAndCorrectArrowElementDisplayByRange(element);
return element;
};
ConnectorLinesRender.prototype.removeConnectorLineElement = function (info) {
RenderElementUtils_1.RenderElementUtils.remove(info, null, this.taskArea, this.connectorLinesToElementsMap);
};
ConnectorLinesRender.prototype.recreateConnectorLineElement = function (dependencyId, forceRender) {
var _this = this;
if (forceRender === void 0) { forceRender = false; }
var infos = [];
this._renderedConnectorLines = this.renderedConnectorLines.filter(function (info) {
if (info.attr["dependency-id"] != dependencyId)
return true;
infos.push(info);
return false;
});
var isRendered = infos.length > 0;
infos.forEach(function (info) { _this.removeConnectorLineElement(info); });
infos = this.gridLayoutCalculator.updateTileToConnectorLinesMap(dependencyId);
if (isRendered || forceRender)
infos.forEach(function (info) { _this.createConnectorLineElement(info); _this.renderedConnectorLines.push(info); });
};
ConnectorLinesRender.prototype.recreateConnectorLineElements = function () {
var _this = this;
var newRenderedConnectorLines = this.gridLayoutCalculator.getRenderedConnectorLines(this.taskAreaContainerScrollTop);
RenderElementUtils_1.RenderElementUtils.recreate(this.renderedConnectorLines, newRenderedConnectorLines, function (info) { _this.removeConnectorLineElement(info); }, function (info) { _this.createConnectorLineElement(info); });
this._renderedConnectorLines = newRenderedConnectorLines;
};
return ConnectorLinesRender;
}());
exports.ConnectorLinesRender = ConnectorLinesRender;
/***/ }),
/* 203 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EtalonsHelper = void 0;
var dom_1 = __webpack_require__(3);
var Enums_1 = __webpack_require__(2);
var GridElementInfo_1 = __webpack_require__(72);
var RenderElementUtils_1 = __webpack_require__(13);
var EtalonsHelper = (function () {
function EtalonsHelper(renderHelepr) {
this._renderHelper = renderHelepr;
}
Object.defineProperty(EtalonsHelper.prototype, "mainElement", {
get: function () {
return this._renderHelper.mainElement;
},
enumerable: false,
configurable: true
});
Object.defineProperty(EtalonsHelper.prototype, "etalonSizeValues", {
get: function () {
return this._renderHelper.etalonSizeValues;
},
enumerable: false,
configurable: true
});
Object.defineProperty(EtalonsHelper.prototype, "scaleCount", {
get: function () {
return this._renderHelper.scaleCount;
},
enumerable: false,
configurable: true
});
EtalonsHelper.prototype.getScaleItemTextTemplate = function (viewType) {
return this._renderHelper.getScaleItemTextTemplate(viewType);
};
EtalonsHelper.prototype.getHeaderHeight = function () {
return this._renderHelper.getHeaderHeight();
};
EtalonsHelper.prototype.getSmallTaskWidth = function (etalonPaddingLeft) {
return this._renderHelper.getSmallTaskWidth(etalonPaddingLeft);
};
EtalonsHelper.prototype.createEtalonElementsContainer = function () {
var result = document.createElement("DIV");
result.style.visibility = "hidden";
result.style.position = "absolute";
result.style.left = "-1000px";
this.mainElement.appendChild(result);
return result;
};
EtalonsHelper.prototype.createEtalonElements = function (parent) {
var etalonElements = [];
var wrapper = RenderElementUtils_1.RenderElementUtils.create(new GridElementInfo_1.GridElementInfo("dx-gantt-taskWrapper"), null, parent);
var task = RenderElementUtils_1.RenderElementUtils.create(new GridElementInfo_1.GridElementInfo("dx-gantt-task"), null, wrapper);
var taskTitle = RenderElementUtils_1.RenderElementUtils.create(new GridElementInfo_1.GridElementInfo("dx-gantt-taskTitle dx-gantt-titleIn"), null, task);
taskTitle.innerText = "WWW";
etalonElements.push(wrapper);
var milestoneWrapper = RenderElementUtils_1.RenderElementUtils.create(new GridElementInfo_1.GridElementInfo("dx-gantt-taskWrapper"), null, parent);
RenderElementUtils_1.RenderElementUtils.create(new GridElementInfo_1.GridElementInfo("dx-gantt-task dx-gantt-milestone"), null, milestoneWrapper);
etalonElements.push(milestoneWrapper);
var etalonElementClassNames = ["dx-gantt-conn-h", "dx-gantt-arrow", "dx-gantt-si", "dx-gantt-taskTitle dx-gantt-titleOut"];
for (var i = 0; i < etalonElementClassNames.length; i++) {
var etalonElementInfo = new GridElementInfo_1.GridElementInfo(etalonElementClassNames[i]);
etalonElements.push(RenderElementUtils_1.RenderElementUtils.create(etalonElementInfo, null, parent));
}
var parentWrapper = RenderElementUtils_1.RenderElementUtils.create(new GridElementInfo_1.GridElementInfo("dx-gantt-taskWrapper"), null, parent);
var parentTask = RenderElementUtils_1.RenderElementUtils.create(new GridElementInfo_1.GridElementInfo("dx-gantt-task dx-gantt-parent"), null, parentWrapper);
var parentTaskTitle = RenderElementUtils_1.RenderElementUtils.create(new GridElementInfo_1.GridElementInfo("dx-gantt-taskTitle dx-gantt-titleIn"), null, parentTask);
parentTaskTitle.innerText = "WWW";
etalonElements.push(parentWrapper);
return etalonElements;
};
EtalonsHelper.prototype.calculateEtalonSizeValues = function () {
var etalonElementsContainer = this.createEtalonElementsContainer();
var etalonElements = this.createEtalonElements(etalonElementsContainer);
this.calculateEtalonSizeValuesCore(etalonElements);
this.mainElement.removeChild(etalonElementsContainer);
};
EtalonsHelper.prototype.calculateEtalonSizeValuesCore = function (etalonElements) {
this.etalonSizeValues.taskHeight = etalonElements[0].firstChild.offsetHeight;
this.etalonSizeValues.milestoneWidth = etalonElements[1].firstChild.offsetWidth;
this.etalonSizeValues.taskWrapperTopPadding = dom_1.DomUtils.pxToInt(dom_1.DomUtils.getCurrentStyle(etalonElements[0]).paddingTop);
this.etalonSizeValues.connectorLineThickness = dom_1.DomUtils.getVerticalBordersWidth(etalonElements[2]);
this.etalonSizeValues.connectorArrowWidth = dom_1.DomUtils.getHorizontalBordersWidth(etalonElements[3]);
for (var i = 0; i <= Enums_1.ViewType.Years; i++) {
etalonElements[4].innerText = this.getScaleItemTextTemplate(i);
this.etalonSizeValues.scaleItemWidths[i] = etalonElements[4].offsetWidth;
}
this.etalonSizeValues.smallTaskWidth = this.getSmallTaskWidth(dom_1.DomUtils.getCurrentStyle(etalonElements[0].firstChild.firstChild).paddingLeft);
this.etalonSizeValues.outsideTaskTextDefaultWidth = dom_1.DomUtils.pxToFloat(dom_1.DomUtils.getCurrentStyle(etalonElements[5]).width);
this.etalonSizeValues.scaleItemHeight = this.getHeaderHeight() / this.scaleCount;
this.etalonSizeValues.parentTaskHeight = etalonElements[etalonElements.length - 1].firstChild.offsetHeight;
};
return EtalonsHelper;
}());
exports.EtalonsHelper = EtalonsHelper;
/***/ }),
/* 204 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EtalonSizeValues = void 0;
var EtalonSizeValues = (function () {
function EtalonSizeValues() {
this.scaleItemWidths = {};
}
return EtalonSizeValues;
}());
exports.EtalonSizeValues = EtalonSizeValues;
/***/ }),
/* 205 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoWorkingIntervalRender = void 0;
var RenderElementUtils_1 = __webpack_require__(13);
var NoWorkingIntervalRender = (function () {
function NoWorkingIntervalRender(renderHelepr) {
this._noWorkingIntervalsToElementsMap = {};
this._renderedNoWorkingIntervals = [];
this._renderHelper = renderHelepr;
}
Object.defineProperty(NoWorkingIntervalRender.prototype, "noWorkingIntervalsToElementsMap", {
get: function () {
return this._noWorkingIntervalsToElementsMap;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NoWorkingIntervalRender.prototype, "taskAreaContainerScrollLeft", {
get: function () {
return this._renderHelper.ganttTaskAreaContainerScrollLeft;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NoWorkingIntervalRender.prototype, "gridLayoutCalculator", {
get: function () {
return this._renderHelper.gridLayoutCalculator;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NoWorkingIntervalRender.prototype, "taskArea", {
get: function () {
return this._renderHelper.taskArea;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NoWorkingIntervalRender.prototype, "renderedNoWorkingIntervals", {
get: function () {
return this._renderedNoWorkingIntervals;
},
set: function (renderedNoWorkingIntervals) {
this._renderedNoWorkingIntervals = renderedNoWorkingIntervals;
},
enumerable: false,
configurable: true
});
NoWorkingIntervalRender.prototype.reset = function () {
this._noWorkingIntervalsToElementsMap = {};
this._renderedNoWorkingIntervals = [];
};
NoWorkingIntervalRender.prototype.createNoWorkingIntervalElement = function (info) {
return RenderElementUtils_1.RenderElementUtils.create(info, null, this.taskArea, this.noWorkingIntervalsToElementsMap);
};
NoWorkingIntervalRender.prototype.removeNoWorkingIntervalElement = function (info) {
RenderElementUtils_1.RenderElementUtils.remove(info, null, this.taskArea, this.noWorkingIntervalsToElementsMap);
};
NoWorkingIntervalRender.prototype.recreateNoWorkingIntervalElements = function () {
var _this = this;
var newRenderedNoWorkingIntervals = this.gridLayoutCalculator.getRenderedNoWorkingIntervals(this.taskAreaContainerScrollLeft);
RenderElementUtils_1.RenderElementUtils.recreate(this.renderedNoWorkingIntervals, newRenderedNoWorkingIntervals, function (info) { _this.removeNoWorkingIntervalElement(info); }, function (info) { _this.createNoWorkingIntervalElement(info); });
this.renderedNoWorkingIntervals = newRenderedNoWorkingIntervals;
};
return NoWorkingIntervalRender;
}());
exports.NoWorkingIntervalRender = NoWorkingIntervalRender;
/***/ }),
/* 206 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourseRender = void 0;
var RenderElementUtils_1 = __webpack_require__(13);
var ResourseRender = (function () {
function ResourseRender(renderHelepr) {
this._resourcesElements = [];
this._renderHelper = renderHelepr;
}
Object.defineProperty(ResourseRender.prototype, "gridLayoutCalculator", {
get: function () {
return this._renderHelper.gridLayoutCalculator;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ResourseRender.prototype, "taskArea", {
get: function () {
return this._renderHelper.taskArea;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ResourseRender.prototype, "resourcesElements", {
get: function () {
return this._resourcesElements;
},
enumerable: false,
configurable: true
});
ResourseRender.prototype.getViewItem = function (index) {
return this._renderHelper.getViewItem(index);
};
ResourseRender.prototype.getTaskResourcesVisibility = function (index) {
return this._renderHelper.getTaskResourcesVisibility(index);
};
ResourseRender.prototype.createResources = function (index) {
var viewItem = this.getViewItem(index);
var resources = viewItem.resources.items;
for (var i = 0; i < resources.length; i++)
this.createResourceElement(index, resources[i]);
};
ResourseRender.prototype.createResourcesWrapperElement = function (index) {
var resourcesWrapperElementInfo = this.gridLayoutCalculator.getTaskResourcesWrapperElementInfo(index);
RenderElementUtils_1.RenderElementUtils.create(resourcesWrapperElementInfo, index, this.taskArea, this.resourcesElements);
this.resourcesElements[index].style.display = this.getTaskResourcesVisibility(index) ? "" : "none";
};
ResourseRender.prototype.createResourceElement = function (index, resource) {
var resourceElementInfo = this.gridLayoutCalculator.getTaskResourceElementInfo();
if (resource.color)
resourceElementInfo.style.backgroundColor = resource.color;
var resElement = RenderElementUtils_1.RenderElementUtils.create(resourceElementInfo, index, this.resourcesElements[index]);
resElement.innerText = resource.text;
this.gridLayoutCalculator.checkAndCorrectElementDisplayByRange(resElement);
};
return ResourseRender;
}());
exports.ResourseRender = ResourseRender;
/***/ }),
/* 207 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ScaleRender = void 0;
var Enums_1 = __webpack_require__(2);
var DateUtils_1 = __webpack_require__(21);
var RenderElementUtils_1 = __webpack_require__(13);
var ScaleRender = (function () {
function ScaleRender(renderHelper) {
this._scaleBorders = [];
this._scaleElements = [];
this._renderedScaleItemIndices = [];
this._timeScaleAreas = new Array();
this._renderHelper = renderHelper;
}
Object.defineProperty(ScaleRender.prototype, "gridLayoutCalculator", {
get: function () {
return this._renderHelper.gridLayoutCalculator;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleRender.prototype, "etalonSizeValues", {
get: function () {
return this._renderHelper.etalonSizeValues;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleRender.prototype, "timeScaleContainer", {
get: function () {
return this._timeScaleContainer;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleRender.prototype, "scaleCount", {
get: function () {
return this._renderHelper.scaleCount;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleRender.prototype, "range", {
get: function () {
return this._renderHelper.range;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleRender.prototype, "viewType", {
get: function () {
return this._renderHelper.viewType;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleRender.prototype, "timeScaleAreas", {
get: function () {
return this._timeScaleAreas;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleRender.prototype, "scaleElements", {
get: function () {
return this._scaleElements;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleRender.prototype, "scaleBorders", {
get: function () {
return this._scaleBorders;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleRender.prototype, "renderedColIndices", {
get: function () {
return this._renderHelper.renderedColIndices;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleRender.prototype, "renderedScaleItemIndices", {
get: function () {
return this._renderedScaleItemIndices;
},
enumerable: false,
configurable: true
});
ScaleRender.prototype.getScaleItemText = function (index, scaleType) {
return this._renderHelper.getScaleItemText(index, scaleType);
};
ScaleRender.prototype.getTaskAreaWidth = function () {
return this._renderHelper.getTaskAreaWidth();
};
ScaleRender.prototype.reset = function () {
this._scaleBorders = [];
this._scaleElements = [];
this._renderedScaleItemIndices = [];
this._timeScaleAreas = [];
this._timeScaleContainer.innerHTML = "";
};
ScaleRender.prototype.setTimeScaleContainerScrollLeft = function (value) {
this._timeScaleContainer.scrollLeft = value;
};
ScaleRender.prototype.createTimeScaleContainer = function (header) {
var timeScaleContainer = document.createElement("DIV");
timeScaleContainer.className = "dx-gantt-tsac";
timeScaleContainer.style.height = this.etalonSizeValues.scaleItemHeight * this.scaleCount + "px";
this._timeScaleContainer = timeScaleContainer;
header.appendChild(this.timeScaleContainer);
};
ScaleRender.prototype.createTimeScaleArea = function () {
var timeScaleArea = document.createElement("DIV");
timeScaleArea.className = "dx-gantt-tsa";
timeScaleArea.style.width = this.getTaskAreaWidth() + "px";
timeScaleArea.style.height = this.etalonSizeValues.scaleItemHeight + "px";
this.timeScaleContainer.appendChild(timeScaleArea);
this.timeScaleAreas.unshift(timeScaleArea);
return timeScaleArea;
};
ScaleRender.prototype.createTimeScaleAreas = function () {
for (var i = 0; i < this.scaleCount; i++)
this.createTimeScaleArea();
};
ScaleRender.prototype.createScaleElementCore = function (index, info, scaleIndex, dictionary) {
if (!dictionary[scaleIndex])
dictionary[scaleIndex] = [];
return RenderElementUtils_1.RenderElementUtils.create(info, index, this.timeScaleAreas[scaleIndex], dictionary[scaleIndex]);
};
ScaleRender.prototype.createScaleElement = function (index, scaleIndex, scaleType) {
var info = this.gridLayoutCalculator.getScaleElementInfo(index, scaleType);
var scaleElement = this.createScaleElementCore(index, info, scaleIndex, this.scaleElements);
scaleElement.innerText = this.getScaleItemText(index, scaleType);
scaleElement.style.lineHeight = this.etalonSizeValues.scaleItemHeight + "px";
if (scaleType === Enums_1.ViewType.Quarter)
scaleElement.style.padding = "0";
};
ScaleRender.prototype.createScaleBorder = function (index, scaleIndex, scaleType) {
var info = this.gridLayoutCalculator.getScaleBorderInfo(index, scaleType);
this.createScaleElementCore(index, info, scaleIndex, this.scaleBorders);
};
ScaleRender.prototype.createScaleElementAndBorder = function (index, scaleIndex, scaleType) {
this.createScaleElement(index, scaleIndex, scaleType);
this.createScaleBorder(index, scaleIndex, scaleType);
};
ScaleRender.prototype.removeScaleElementAndBorder = function (index, scaleIndex) {
RenderElementUtils_1.RenderElementUtils.remove(null, index, this.timeScaleAreas[scaleIndex], this.scaleElements[scaleIndex]);
RenderElementUtils_1.RenderElementUtils.remove(null, index, this.timeScaleAreas[scaleIndex], this.scaleBorders[scaleIndex]);
};
ScaleRender.prototype.recreateScalesElements = function () {
this.recreateScaleElements(this.viewType, 0);
this.recreateScaleElements(DateUtils_1.DateUtils.ViewTypeToScaleMap[this.viewType], 1);
};
ScaleRender.prototype.recreateScaleElements = function (scaleType, scaleIndex) {
var _this = this;
var newRenderedIndices = this.gridLayoutCalculator.getRenderedScaleItemIndices(scaleType, this.renderedColIndices);
var renderedIndices = this.renderedScaleItemIndices[scaleType - this.viewType] || [];
RenderElementUtils_1.RenderElementUtils.recreate(renderedIndices, newRenderedIndices, function (index) { _this.removeScaleElementAndBorder(index, scaleIndex); }, function (index) { _this.createScaleElementAndBorder(index, scaleIndex, scaleType); });
this.renderedScaleItemIndices[scaleType - this.viewType] = newRenderedIndices;
};
return ScaleRender;
}());
exports.ScaleRender = ScaleRender;
/***/ }),
/* 208 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StripLinesRender = void 0;
var RenderElementUtils_1 = __webpack_require__(13);
var StripLinesRender = (function () {
function StripLinesRender(renderHelepr) {
this._stripLinesMap = [];
this._renderedStripLines = [];
this._renderHelper = renderHelepr;
}
Object.defineProperty(StripLinesRender.prototype, "gridLayoutCalculator", {
get: function () {
return this._renderHelper.gridLayoutCalculator;
},
enumerable: false,
configurable: true
});
Object.defineProperty(StripLinesRender.prototype, "taskArea", {
get: function () {
return this._renderHelper.taskArea;
},
enumerable: false,
configurable: true
});
Object.defineProperty(StripLinesRender.prototype, "stripLinesMap", {
get: function () {
return this._stripLinesMap;
},
enumerable: false,
configurable: true
});
Object.defineProperty(StripLinesRender.prototype, "renderedStripLines", {
get: function () {
return this._renderedStripLines;
},
set: function (renderedStripLines) {
this._renderedStripLines = renderedStripLines;
},
enumerable: false,
configurable: true
});
Object.defineProperty(StripLinesRender.prototype, "stripLines", {
get: function () {
return this._renderHelper.stripLines;
},
enumerable: false,
configurable: true
});
StripLinesRender.prototype.reset = function () {
this._renderedStripLines = [];
};
StripLinesRender.prototype.recreateStripLines = function () {
var _this = this;
var newRenderedStripLines = this.gridLayoutCalculator.getRenderedStripLines(this.stripLines);
RenderElementUtils_1.RenderElementUtils.recreate(this.renderedStripLines, newRenderedStripLines, function (info) { RenderElementUtils_1.RenderElementUtils.remove(info, null, _this.taskArea, _this.stripLinesMap); }, function (info) { return RenderElementUtils_1.RenderElementUtils.create(info, null, _this.taskArea, _this.stripLinesMap); });
this.renderedStripLines = newRenderedStripLines;
};
return StripLinesRender;
}());
exports.StripLinesRender = StripLinesRender;
/***/ }),
/* 209 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskAreaManager = void 0;
var browser_1 = __webpack_require__(8);
var point_1 = __webpack_require__(4);
var dom_1 = __webpack_require__(3);
var evt_1 = __webpack_require__(10);
var touch_1 = __webpack_require__(27);
var GridLayoutCalculator_1 = __webpack_require__(16);
var TaskAreaManager = (function () {
function TaskAreaManager(ganttView) {
this.time = new Date();
this.touchTime = new Date();
this.ganttView = ganttView;
this.position = new point_1.Point(-1, -1);
if (!browser_1.Browser.WebKitTouchUI)
this.initMouseEvents();
if (browser_1.Browser.isTouchEnabled())
this.initTouchEvents();
}
Object.defineProperty(TaskAreaManager.prototype, "eventManager", {
get: function () {
return this.ganttView.eventManager;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaManager.prototype, "taskArea", {
get: function () {
return this.ganttView.renderHelper.taskArea;
},
enumerable: false,
configurable: true
});
TaskAreaManager.prototype.taskAreaAddEventListener = function (type, eventHandler) {
this.ganttView.renderHelper.taskArea.addEventListener(type, eventHandler);
};
TaskAreaManager.prototype.taskAreaRemoveEventListener = function (type, eventHandler) {
this.ganttView.renderHelper.taskArea.removeEventListener(type, eventHandler);
};
TaskAreaManager.prototype.initMouseEventHandlers = function () {
var _this = this;
this.onMouseClickHandler = function (evt) { _this.onTaskAreaClick(evt); };
this.onMouseDblClickHandler = function (evt) { _this.onTaskAreaDblClick(evt); };
this.onScrollHandler = this.ganttView.updateView.bind(this.ganttView);
this.onContextMenuHandler = function (evt) { _this.onContextMenu(evt); };
this.onMouseWheelHandler = function (evt) { _this.onMouseWheel(evt); };
this.onMouseDownHandler = function (evt) { _this.onMouseDown(evt); };
this.onMouseMoveHandler = function (evt) { _this.onDocumentMouseMove(evt); };
this.onMouseUpHandler = function (evt) { _this.onDocumentMouseUp(evt); };
this.onKeyDownHandler = function (evt) { _this.onDocumentKeyDown(evt); };
this.onTaskAreaMouseLeave = function () { _this.ganttView.hideTaskEditControl(); };
};
TaskAreaManager.prototype.initTouchEventHandlers = function () {
var _this = this;
this.onTouchStartHandler = function (evt) { _this.onTouchStart(evt); };
this.onTouchEndHandler = function (evt) { _this.onTouchEnd(evt); };
this.onTouchMoveHandler = function (evt) { _this.onTouchMove(evt); };
this.onPointerDownHandler = function (evt) { _this.onMouseDown(evt); };
this.onPointerUpHandler = function (evt) { _this.onDocumentMouseUp(evt); };
this.onPointerMoveHandler = function (evt) { _this.onDocumentMouseMove(evt); };
};
TaskAreaManager.prototype.initMouseEvents = function () {
this.initMouseEventHandlers();
this.taskAreaAddEventListener("click", this.onMouseClickHandler);
this.taskAreaAddEventListener("dblclick", this.onMouseDblClickHandler);
this.taskAreaAddEventListener("scroll", this.onScrollHandler);
this.taskAreaAddEventListener("contextmenu", this.onContextMenuHandler);
this.taskAreaAddEventListener(evt_1.EvtUtils.getMouseWheelEventName(), this.onMouseWheelHandler);
this.taskAreaAddEventListener("mousedown", this.onMouseDownHandler);
this.taskAreaAddEventListener("mouseleave", this.onTaskAreaMouseLeave);
document.addEventListener("mousemove", this.onMouseMoveHandler);
document.addEventListener("mouseup", this.onMouseUpHandler);
document.addEventListener("keydown", this.onKeyDownHandler);
};
TaskAreaManager.prototype.detachMouseEvents = function () {
this.initTouchEventHandlers();
this.taskAreaRemoveEventListener("click", this.onMouseClickHandler);
this.taskAreaRemoveEventListener("dblclick", this.onMouseDblClickHandler);
this.taskAreaRemoveEventListener("scroll", this.onScrollHandler);
this.taskAreaRemoveEventListener("contextmenu", this.onContextMenuHandler);
this.taskAreaRemoveEventListener(evt_1.EvtUtils.getMouseWheelEventName(), this.onMouseWheelHandler);
this.taskAreaRemoveEventListener("mouseleave", this.onTaskAreaMouseLeave);
this.taskAreaRemoveEventListener("mousedown", this.onMouseDownHandler);
document.removeEventListener("mousemove", this.onMouseMoveHandler);
document.removeEventListener("mouseup", this.onMouseUpHandler);
document.removeEventListener("keydown", this.onKeyDownHandler);
};
TaskAreaManager.prototype.initTouchEvents = function () {
if (browser_1.Browser.WebKitTouchUI || browser_1.Browser.WindowsPlatform && !browser_1.Browser.Edge && !browser_1.Browser.IE) {
this.taskAreaAddEventListener("touchstart", this.onTouchStartHandler);
this.taskAreaAddEventListener("touchend", this.onTouchEndHandler);
this.taskAreaAddEventListener("touchmove", this.onTouchMoveHandler);
}
else if (browser_1.Browser.MSTouchUI) {
this.taskArea.classList.add(TaskAreaManager.MS_POINTER_ACTIVE_CLASS);
this.taskAreaAddEventListener("pointerdown", this.onPointerDownHandler);
this.taskAreaAddEventListener("pointerup", this.onPointerUpHandler);
this.taskAreaAddEventListener("pointermove", this.onPointerMoveHandler);
}
};
TaskAreaManager.prototype.detachTouchEvents = function () {
this.taskAreaRemoveEventListener("touchstart", this.onTouchStartHandler);
this.taskAreaRemoveEventListener("touchend", this.onTouchEndHandler);
this.taskAreaRemoveEventListener("touchmove", this.onTouchMoveHandler);
this.taskAreaRemoveEventListener("pointerdown", this.onPointerDownHandler);
this.taskAreaRemoveEventListener("pointerup", this.onPointerUpHandler);
this.taskAreaRemoveEventListener("pointermove", this.onPointerMoveHandler);
};
TaskAreaManager.prototype.attachEventsOnTask = function (taskElement) {
var _this = this;
this.onTaskMouseEnterHandler = function (evt) {
if (browser_1.Browser.MSTouchUI)
setTimeout(function () { return _this.onTaskElementHover(evt); }, 0);
else
_this.onTaskElementHover(evt);
};
this.onTaskMouseLeaveHandler = function () {
_this.onTaskElementUnhover();
};
taskElement === null || taskElement === void 0 ? void 0 : taskElement.addEventListener("mouseenter", this.onTaskMouseEnterHandler);
taskElement === null || taskElement === void 0 ? void 0 : taskElement.addEventListener("mouseleave", this.onTaskMouseLeaveHandler);
};
TaskAreaManager.prototype.detachEventsOnTask = function (taskElement) {
taskElement === null || taskElement === void 0 ? void 0 : taskElement.removeEventListener("mouseenter", this.onTaskMouseEnterHandler);
taskElement === null || taskElement === void 0 ? void 0 : taskElement.removeEventListener("mouseleave", this.onTaskMouseLeaveHandler);
};
TaskAreaManager.prototype.detachEvents = function () {
this.detachMouseEvents();
this.detachTouchEvents();
};
TaskAreaManager.prototype.onMouseDown = function (evt) {
this.eventManager.onMouseDown(evt);
this.preventSelect = false;
this.position = new point_1.Point(evt.clientX, evt.clientY);
};
TaskAreaManager.prototype.onDocumentMouseUp = function (evt) {
this.eventManager.onMouseUp(evt);
};
TaskAreaManager.prototype.onChangeTaskSelection = function (evt) {
var _this = this;
var clickedTaskIndex = this.getClickedTaskIndex(evt);
this.ganttView.isFocus = dom_1.DomUtils.isItParent(this.taskArea, evt_1.EvtUtils.getEventSource(evt));
if (this.ganttView.isFocus && !this.preventSelect && this.ganttView.settings.allowSelectTask && !this.isConnectorLine(evt))
setTimeout(function () { _this.changeTaskSelection(clickedTaskIndex); }, 0);
};
TaskAreaManager.prototype.onMouseWheel = function (evt) {
this.eventManager.onMouseWheel(evt);
};
TaskAreaManager.prototype.onDocumentKeyDown = function (evt) {
this.eventManager.onKeyDown(evt);
};
TaskAreaManager.prototype.onDocumentMouseMove = function (evt) {
if (this.position.x !== evt.clientX || this.position.y !== evt.clientY) {
this.eventManager.onMouseMove(evt);
this.preventSelect = true;
}
};
TaskAreaManager.prototype.onTouchStart = function (evt) {
this.position = new point_1.Point(touch_1.TouchUtils.getEventX(evt), touch_1.TouchUtils.getEventY(evt));
var clickedItem = this.ganttView.viewModel.items[this.getClickedTaskIndex(evt)];
var now = new Date();
if (evt.touches.length === 1 && now.getTime() - this.touchTime.getTime() < TaskAreaManager.DBLCLICK_INTERVAL) {
evt.preventDefault();
if (clickedItem && this.ganttView.onTaskDblClick(clickedItem.task.id, evt))
this.ganttView.commandManager.showTaskEditDialog.execute(clickedItem.task);
}
else
this.eventManager.onTouchStart(evt);
if (clickedItem && this.ganttView.onTaskClick(clickedItem.task.id, evt))
this.touchTime = now;
this.preventSelect = false;
};
TaskAreaManager.prototype.onTouchEnd = function (evt) {
this.eventManager.onTouchEnd(evt);
};
TaskAreaManager.prototype.onTouchMove = function (evt) {
if (this.position.x !== touch_1.TouchUtils.getEventX(evt) || this.position.y !== touch_1.TouchUtils.getEventY(evt)) {
this.eventManager.onTouchMove(evt);
this.preventSelect = true;
}
};
TaskAreaManager.prototype.getDependencyKeyFromSource = function (source) {
return this.ganttView.viewModel.convertInternalToPublicKey("dependency", source.getAttribute("dependency-id"));
};
TaskAreaManager.prototype.onContextMenu = function (evt) {
var source = evt_1.EvtUtils.getEventSource(evt);
var isDependency = this.isConnectorLine(evt);
var type = isDependency ? "dependency" : "task";
var key = isDependency ? this.getDependencyKeyFromSource(source) : this.getClickedTaskKey(this.getClickedTaskIndex(evt));
if (!isDependency)
this.onChangeTaskSelection(evt);
if (evt.stopPropagation)
evt.stopPropagation();
if (evt.preventDefault)
evt.preventDefault();
if (browser_1.Browser.WebKitFamily)
evt.returnValue = false;
if (this.ganttView.onGanttViewContextMenu(evt, key, type)) {
var info = {
event: evt,
type: type,
key: key,
position: new point_1.Point(evt_1.EvtUtils.getEventX(evt), evt_1.EvtUtils.getEventY(evt))
};
this.ganttView.showPopupMenu(info);
}
};
TaskAreaManager.prototype.onTaskElementHover = function (evt) {
evt.preventDefault();
var hoveredTaskIndex = this.getClickedTaskIndex(evt);
this.ganttView.taskEditController.show(hoveredTaskIndex);
this.ganttView.taskEditController.showTaskInfo(evt_1.EvtUtils.getEventX(evt));
};
TaskAreaManager.prototype.onTaskElementUnhover = function () {
this.ganttView.taskEditController.cancel();
};
TaskAreaManager.prototype.getClickedTaskIndex = function (evt) {
var y = evt_1.EvtUtils.getEventY(evt);
var taskAreaY = dom_1.DomUtils.getAbsolutePositionY(this.taskArea);
var relativeY = y - taskAreaY;
return Math.floor(relativeY / this.ganttView.tickSize.height);
};
TaskAreaManager.prototype.getClickedTaskKey = function (index) {
var clickedItem = this.ganttView.viewModel.items[index];
return clickedItem && clickedItem.task && clickedItem.task.id;
};
TaskAreaManager.prototype.changeTaskSelection = function (index) {
var clickedTask = this.ganttView.viewModel.items[index];
if (clickedTask)
this.ganttView.changeGanttTaskSelection(clickedTask.task.id, true);
};
TaskAreaManager.prototype.onTaskAreaClick = function (evt) {
var clickedTaskIndex = this.getClickedTaskIndex(evt);
this.onChangeTaskSelection(evt);
var clickedItem = this.ganttView.viewModel.items[clickedTaskIndex];
if (clickedItem)
this.ganttView.onTaskClick(clickedItem.task.id, evt);
};
TaskAreaManager.prototype.onTaskAreaDblClick = function (evt) {
evt.preventDefault();
var clickedTaskIndex = this.getClickedTaskIndex(evt);
var clickedItem = this.ganttView.viewModel.items[clickedTaskIndex];
if (clickedItem && this.ganttView.onTaskDblClick(clickedItem.task.id, evt))
this.ganttView.commandManager.showTaskEditDialog.execute(clickedItem.task);
};
TaskAreaManager.prototype.isConnectorLine = function (evt) {
var source = evt_1.EvtUtils.getEventSource(evt);
return dom_1.DomUtils.hasClassName(source, GridLayoutCalculator_1.GridLayoutCalculator.CLASSNAMES.CONNECTOR_HORIZONTAL) ||
dom_1.DomUtils.hasClassName(source, GridLayoutCalculator_1.GridLayoutCalculator.CLASSNAMES.CONNECTOR_VERTICAL);
};
TaskAreaManager.DBLCLICK_INTERVAL = 300;
TaskAreaManager.MS_POINTER_ACTIVE_CLASS = "ms-pointer-active";
return TaskAreaManager;
}());
exports.TaskAreaManager = TaskAreaManager;
/***/ }),
/* 210 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskAreaRender = void 0;
var dom_1 = __webpack_require__(3);
var RenderElementUtils_1 = __webpack_require__(13);
var TaskAreaRender = (function () {
function TaskAreaRender(renderHelepr) {
this._vertTaskAreaBorders = [];
this._horTaskAreaBorders = [];
this._isExternalTaskAreaContainer = false;
this._renderHelper = renderHelepr;
}
Object.defineProperty(TaskAreaRender.prototype, "gridLayoutCalculator", {
get: function () {
return this._renderHelper.gridLayoutCalculator;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaRender.prototype, "taskArea", {
get: function () {
return this._renderHelper.taskArea;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaRender.prototype, "mainElement", {
get: function () {
return this._renderHelper.mainElement;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaRender.prototype, "etalonSizeValues", {
get: function () {
return this._renderHelper.etalonSizeValues;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaRender.prototype, "scaleCount", {
get: function () {
return this._renderHelper.scaleCount;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaRender.prototype, "tickSize", {
get: function () {
return this._renderHelper.tickSize;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaRender.prototype, "taskAreaContainerScrollTop", {
get: function () {
return this._renderHelper.ganttViewTaskAreaContainerScrollTop;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaRender.prototype, "taskAreaContainerScrollLeft", {
get: function () {
return this._renderHelper.ganttTaskAreaContainerScrollLeft;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaRender.prototype, "areHorizontalBordersEnabled", {
get: function () {
return this._renderHelper.areHorizontalBordersEnabled;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaRender.prototype, "renderedRowIndices", {
get: function () {
return this._renderHelper.renderedRowIndices;
},
set: function (renderedRowIndices) {
this._renderHelper.renderedRowIndices = renderedRowIndices;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaRender.prototype, "renderedColIndices", {
get: function () {
return this._renderHelper.renderedColIndices;
},
set: function (renderedColIndices) {
this._renderHelper.renderedColIndices = renderedColIndices;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaRender.prototype, "vertTaskAreaBorders", {
get: function () {
return this._vertTaskAreaBorders;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaRender.prototype, "horTaskAreaBorders", {
get: function () {
return this._horTaskAreaBorders;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaRender.prototype, "hlRowElements", {
get: function () {
return this._renderHelper.hlRowElements;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaRender.prototype, "taskAreaContainer", {
get: function () {
return this._taskAreaContainer;
},
enumerable: false,
configurable: true
});
TaskAreaRender.prototype.getExternalTaskAreaContainer = function (parent) {
return this._renderHelper.getExternalTaskAreaContainer(parent);
};
TaskAreaRender.prototype.prepareExternalTaskAreaContainer = function (element, info) {
return this._renderHelper.prepareExternalTaskAreaContainer(element, info);
};
TaskAreaRender.prototype.isAllowTaskAreaBorders = function (isVerticalScroll) {
return this._renderHelper.isAllowTaskAreaBorders(isVerticalScroll);
};
TaskAreaRender.prototype.getTaskAreaContainerElement = function () {
return this._taskAreaContainer.getElement();
};
TaskAreaRender.prototype.initTaskAreaContainer = function (element) {
this._renderHelper.createTaskArea(element);
this._taskAreaContainer = this.getExternalTaskAreaContainer(element);
this._isExternalTaskAreaContainer = !!this._taskAreaContainer;
if (this.taskAreaContainer == null)
this._taskAreaContainer = this._renderHelper.getTaskAreaContainer(element);
};
TaskAreaRender.prototype.createTaskElement = function (index) {
this._renderHelper.createTaskElement(index);
};
TaskAreaRender.prototype.removeTaskElement = function (index) {
this._renderHelper.removeTaskElement(index);
};
TaskAreaRender.prototype.reset = function () {
this._horTaskAreaBorders = [];
this._vertTaskAreaBorders = [];
};
TaskAreaRender.prototype.prepareTaskAreaContainer = function () {
var className = "dx-gantt-tac-hb";
var element = this.getTaskAreaContainerElement();
this.areHorizontalBordersEnabled ?
dom_1.DomUtils.addClassName(element, className) : dom_1.DomUtils.removeClassName(element, className);
var marginTop = parseInt(getComputedStyle(element).getPropertyValue("margin-top")) || 0;
var height = "calc(100% - " + (this.etalonSizeValues.scaleItemHeight * this.scaleCount + marginTop) + "px)";
if (this._isExternalTaskAreaContainer)
this.prepareExternalTaskAreaContainer(element, { height: height });
else
element.style.height = height;
};
TaskAreaRender.prototype.createTaskAreaContainer = function () {
var element = document.createElement("DIV");
element.className = "dx-gantt-tac";
this.mainElement.appendChild(element);
this.initTaskAreaContainer(element);
this.prepareTaskAreaContainer();
};
TaskAreaRender.prototype.createTaskAreaBorder = function (index, isVertical) {
var info = this.gridLayoutCalculator.getTaskAreaBorderInfo(index, isVertical);
RenderElementUtils_1.RenderElementUtils.create(info, index, this.taskArea, this.getTaskAreaBordersDictionary(isVertical));
};
TaskAreaRender.prototype.createTaskArea = function () {
var taskArea = document.createElement("DIV");
taskArea.id = "dx-gantt-ta";
return taskArea;
};
TaskAreaRender.prototype.removeTaskAreaBorder = function (index, isVertical) {
RenderElementUtils_1.RenderElementUtils.remove(null, index, this.taskArea, this.getTaskAreaBordersDictionary(isVertical));
};
TaskAreaRender.prototype.createTaskAreaBorderAndTaskElement = function (index, isVerticalScroll) {
if (this.isAllowTaskAreaBorders(isVerticalScroll))
this.createTaskAreaBorder(index, !isVerticalScroll);
if (isVerticalScroll)
this.createTaskElement(index);
};
TaskAreaRender.prototype.removeTaskAreaBorderAndTaskElement = function (index, isVerticalScroll) {
if (this.isAllowTaskAreaBorders(isVerticalScroll))
this.removeTaskAreaBorder(index, !isVerticalScroll);
if (isVerticalScroll)
this.removeTaskElement(index);
};
TaskAreaRender.prototype.recreateTaskAreaBordersAndTaskElements = function (isVertical) {
var _this = this;
var scrollPos = isVertical ? this.taskAreaContainerScrollTop : this.taskAreaContainerScrollLeft;
var newRenderedIndices = this.gridLayoutCalculator.getRenderedRowColumnIndices(scrollPos, isVertical);
var renderedIndices = isVertical ? this.renderedRowIndices : this.renderedColIndices;
RenderElementUtils_1.RenderElementUtils.recreate(renderedIndices, newRenderedIndices, function (index) { _this.removeTaskAreaBorderAndTaskElement(index, isVertical); }, function (index) { _this.createTaskAreaBorderAndTaskElement(index, isVertical); });
if (isVertical)
this.renderedRowIndices = newRenderedIndices;
else
this.renderedColIndices = newRenderedIndices;
this.gridLayoutCalculator.createTileToConnectorLinesMap();
};
TaskAreaRender.prototype.getTaskAreaBordersDictionary = function (isVertical) {
return isVertical ? this.vertTaskAreaBorders : this.horTaskAreaBorders;
};
TaskAreaRender.prototype.setSizeForTaskArea = function () {
this.taskArea.style.width = this.getTaskAreaWidth() + "px";
this.taskArea.style.height = this.getTaskAreaHeight() + "px";
};
TaskAreaRender.prototype.getTaskAreaWidth = function () {
return this.gridLayoutCalculator.getTotalWidth();
};
TaskAreaRender.prototype.getTaskAreaHeight = function () {
return this.gridLayoutCalculator.getVerticalGridLineHeight();
};
TaskAreaRender.prototype.createHighlightRowElement = function (index) {
var hlRowInfo = this.gridLayoutCalculator.getHighlightRowInfo(index);
RenderElementUtils_1.RenderElementUtils.create(hlRowInfo, index, this.taskArea, this.hlRowElements);
};
return TaskAreaRender;
}());
exports.TaskAreaRender = TaskAreaRender;
/***/ }),
/* 211 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskRender = void 0;
var dom_1 = __webpack_require__(3);
var Enums_1 = __webpack_require__(2);
var CustomTaskRender_1 = __webpack_require__(212);
var RenderElementUtils_1 = __webpack_require__(13);
var TaskRender = (function () {
function TaskRender(renderHelper) {
this._selectionElements = [];
this._taskElements = [];
this._renderHelper = renderHelper;
this.customTaskRender = new CustomTaskRender_1.CustomTaskRender(renderHelper, this);
}
Object.defineProperty(TaskRender.prototype, "gridLayoutCalculator", {
get: function () {
return this._renderHelper.gridLayoutCalculator;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskRender.prototype, "taskElements", {
get: function () {
return this._taskElements;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskRender.prototype, "selectionElements", {
get: function () {
return this._selectionElements;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskRender.prototype, "taskArea", {
get: function () {
return this._renderHelper.taskArea;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskRender.prototype, "isExternalTaskAreaContainer", {
get: function () {
return this._renderHelper.isExternalTaskAreaContainer;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskRender.prototype, "resourcesElements", {
get: function () {
return this._renderHelper.resourcesElements;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskRender.prototype, "hlRowElements", {
get: function () {
return this._renderHelper.hlRowElements;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskRender.prototype, "renderedRowIndices", {
get: function () {
return this._renderHelper.renderedRowIndices;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskRender.prototype, "taskTitlePosition", {
get: function () {
return this._renderHelper.taskTitlePosition;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskRender.prototype, "showResources", {
get: function () {
return this._renderHelper.showResources;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskRender.prototype, "areHorizontalBordersEnabled", {
get: function () {
return this._renderHelper.areHorizontalBordersEnabled;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskRender.prototype, "taskTextHeightKey", {
get: function () {
return this._renderHelper.taskTextHeightKey;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskRender.prototype, "viewModelItems", {
get: function () {
return this._renderHelper.viewModelItems;
},
enumerable: false,
configurable: true
});
TaskRender.prototype.isHighlightRowElementAllowed = function (index) {
return this._renderHelper.isHighlightRowElementAllowed(index);
};
TaskRender.prototype.getTaskVisibility = function (index) {
return this._renderHelper.getTaskVisibility(index);
};
TaskRender.prototype.getTaskText = function (index) {
return this._renderHelper.getTaskText(index);
};
Object.defineProperty(TaskRender.prototype, "invalidTaskDependencies", {
get: function () {
return this._renderHelper.invalidTaskDependencies;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskRender.prototype, "fakeTaskWrapper", {
get: function () {
var _a;
(_a = this._fakeTaskWrapper) !== null && _a !== void 0 ? _a : (this._fakeTaskWrapper = this.createFakeTaskWrapper());
return this._fakeTaskWrapper;
},
enumerable: false,
configurable: true
});
TaskRender.prototype.getViewItem = function (index) {
return this._renderHelper.getViewItem(index);
};
TaskRender.prototype.getTask = function (index) {
return this._renderHelper.getTask(index);
};
TaskRender.prototype.createHighlightRowElement = function (index) {
this._renderHelper.createHighlightRowElement(index);
};
TaskRender.prototype.getTaskDependencies = function (taskInternalId) {
return this._renderHelper.getTaskDependencies(taskInternalId);
};
TaskRender.prototype.addInvalidTaskDependencies = function (taskDependencies) {
this._renderHelper.invalidTaskDependencies = this._renderHelper.invalidTaskDependencies.concat(taskDependencies);
};
TaskRender.prototype.removeInvalidTaskDependencies = function (taskId) {
this._renderHelper.invalidTaskDependencies = this._renderHelper.invalidTaskDependencies.filter(function (d) { return d.predecessorId != taskId || d.successorId != taskId; });
};
TaskRender.prototype.createResources = function (index) {
if (this.showResources)
this._renderHelper.createResources(index);
};
TaskRender.prototype.attachEventsOnTask = function (taskIndex) {
this._renderHelper.attachEventsOnTask(taskIndex);
};
TaskRender.prototype.detachEventsOnTask = function (taskIndex) {
this._renderHelper.detachEventsOnTask(taskIndex);
};
TaskRender.prototype.recreateConnectorLineElement = function (dependencyId, forceRender) {
if (forceRender === void 0) { forceRender = false; }
this._renderHelper.recreateConnectorLineElement(dependencyId, forceRender);
};
TaskRender.prototype.renderTaskElement = function (index) {
this._renderHelper.createTaskElement(index);
};
TaskRender.prototype.reset = function () {
this._selectionElements = [];
this._taskElements = [];
};
TaskRender.prototype.createTaskWrapperElement = function (index) {
var taskWrapperInfo = this.gridLayoutCalculator.getTaskWrapperElementInfo(index);
RenderElementUtils_1.RenderElementUtils.create(taskWrapperInfo, index, this.taskArea, this.taskElements);
this.taskElements[index].style.display = this.getTaskVisibility(index) ? "" : "none";
};
TaskRender.prototype.createTaskElement = function (index, taskTemplateFunction) {
var viewItem = this.getViewItem(index);
if (taskTemplateFunction)
this.customTaskRender.createCustomTaskElement(index, taskTemplateFunction);
if (!viewItem.task.isValid() || !viewItem.visible) {
var taskDependencies = this.getTaskDependencies(viewItem.task.internalId);
this.addInvalidTaskDependencies(taskDependencies);
return;
}
if (!viewItem.isCustom)
this.createDefaultTaskElement(index);
};
TaskRender.prototype.createTaskVisualElement = function (index) {
var taskElementInfo = this.gridLayoutCalculator.getTaskElementInfo(index, this.taskTitlePosition !== Enums_1.TaskTitlePosition.Inside);
var taskElement = RenderElementUtils_1.RenderElementUtils.create(taskElementInfo, index, this.taskElements[index]);
this.attachEventsOnTask(index);
return taskElement;
};
TaskRender.prototype.createDefaultTaskElement = function (index) {
var viewItem = this.getViewItem(index);
if (this.isHighlightRowElementAllowed(index))
this.createHighlightRowElement(index);
if (viewItem.selected)
this.createTaskSelectionElement(index);
this.createTaskWrapperElement(index);
if (this.taskTitlePosition === Enums_1.TaskTitlePosition.Outside)
this.createTaskTextElement(index, this.taskElements[index]);
var taskVisualElement = this.createTaskVisualElement(index);
if (!viewItem.task.isMilestone()) {
if (this.taskTitlePosition === Enums_1.TaskTitlePosition.Inside)
this.createTaskTextElement(index, taskVisualElement);
this.createTaskProgressElement(index, taskVisualElement);
}
this.createResources(index);
};
TaskRender.prototype.removeTaskElement = function (index) {
var task = this.getTask(index);
this.removeInvalidTaskDependencies(task.id);
this.detachEventsOnTask(index);
RenderElementUtils_1.RenderElementUtils.remove(null, index, this.taskArea, this.taskElements);
RenderElementUtils_1.RenderElementUtils.remove(null, index, this.taskArea, this.resourcesElements);
RenderElementUtils_1.RenderElementUtils.remove(null, index, this.taskArea, this.selectionElements);
if (this.isHighlightRowElementAllowed(index))
RenderElementUtils_1.RenderElementUtils.remove(null, index, this.taskArea, this.hlRowElements);
this.gridLayoutCalculator.resetTaskInfo(index);
};
TaskRender.prototype.recreateTaskElement = function (index) {
var _this = this;
var isVisible = this.renderedRowIndices.filter(function (r) { return r === index; }).length > 0;
var task = this.getTask(index);
if (!task)
return;
if (isVisible) {
this.removeTaskElement(index);
this.renderTaskElement(index);
}
var dependencies = this.getTaskDependencies(task.internalId);
if (dependencies.length)
dependencies.forEach(function (d) { return _this.recreateConnectorLineElement(d.internalId, true); });
};
TaskRender.prototype.createFakeTaskWrapper = function () {
var _a, _b;
var index = (_b = (_a = this.viewModelItems.filter(function (v) { return v.task && !v.task.isMilestone; })[0]) === null || _a === void 0 ? void 0 : _a.visibleIndex) !== null && _b !== void 0 ? _b : 0;
var calc = this.gridLayoutCalculator;
var fakeWrapper = RenderElementUtils_1.RenderElementUtils.create(calc.getTaskWrapperElementInfo(index), null, this.taskArea);
var taskVisualElement = RenderElementUtils_1.RenderElementUtils.create(calc.getTaskElementInfo(index), null, fakeWrapper);
this.createTaskTextElement(index, taskVisualElement);
this.createTaskProgressElement(index, taskVisualElement);
fakeWrapper.style.display = "none";
return fakeWrapper;
};
TaskRender.prototype.createTaskProgressElement = function (index, parent) {
var taskProgressInfo = this.gridLayoutCalculator.getTaskProgressElementInfo(index);
RenderElementUtils_1.RenderElementUtils.create(taskProgressInfo, index, parent);
};
TaskRender.prototype.createTaskTextElement = function (index, parent) {
var _a;
var _b;
var taskTextInfo = this.gridLayoutCalculator.getTaskTextElementInfo(index, this.taskTitlePosition === Enums_1.TaskTitlePosition.Inside);
var taskTextElement = RenderElementUtils_1.RenderElementUtils.create(taskTextInfo, index, parent);
var text = this.getTaskText(index);
if (!text) {
(_a = this[_b = this.taskTextHeightKey]) !== null && _a !== void 0 ? _a : (this[_b] = this.getTaskTextHeight(taskTextElement));
taskTextElement.style.height = this[this.taskTextHeightKey];
}
taskTextElement.innerText = text;
};
TaskRender.prototype.createTaskSelectionElement = function (index) {
var selectionInfo = this.gridLayoutCalculator.getSelectionElementInfo(index);
if (this.isExternalTaskAreaContainer && !this.areHorizontalBordersEnabled)
selectionInfo.size.height++;
RenderElementUtils_1.RenderElementUtils.create(selectionInfo, index, this.taskArea, this.selectionElements);
};
TaskRender.prototype.getTaskTextHeight = function (textElement) {
textElement.innerText = "WWW";
var height = getComputedStyle(textElement).height;
textElement.innerText = "";
return height;
};
TaskRender.prototype.getSmallTaskWidth = function (etalonPaddingLeft) {
var result = 0;
if (etalonPaddingLeft != null && etalonPaddingLeft !== "") {
var indexOfRem = etalonPaddingLeft.indexOf("rem");
if (indexOfRem > -1)
try {
var remSize = parseFloat(etalonPaddingLeft.substr(0, indexOfRem));
result = remSize * parseFloat(getComputedStyle(document.documentElement).fontSize);
}
catch (e) { }
else
result = dom_1.DomUtils.pxToInt(etalonPaddingLeft);
}
return result * 2;
};
return TaskRender;
}());
exports.TaskRender = TaskRender;
/***/ }),
/* 212 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CustomTaskRender = void 0;
var Enums_1 = __webpack_require__(2);
var RenderElementUtils_1 = __webpack_require__(13);
var CustomTaskRender = (function () {
function CustomTaskRender(renderHelepr, taskRender) {
this._renderHelper = renderHelepr;
this._taskRender = taskRender;
}
Object.defineProperty(CustomTaskRender.prototype, "gridLayoutCalculator", {
get: function () {
return this._renderHelper.gridLayoutCalculator;
},
enumerable: false,
configurable: true
});
Object.defineProperty(CustomTaskRender.prototype, "tickSize", {
get: function () {
return this._renderHelper.tickSize;
},
enumerable: false,
configurable: true
});
Object.defineProperty(CustomTaskRender.prototype, "taskTitlePosition", {
get: function () {
return this._renderHelper.taskTitlePosition;
},
enumerable: false,
configurable: true
});
Object.defineProperty(CustomTaskRender.prototype, "taskElements", {
get: function () {
return this._taskRender.taskElements;
},
enumerable: false,
configurable: true
});
Object.defineProperty(CustomTaskRender.prototype, "taskArea", {
get: function () {
return this._renderHelper.taskArea;
},
enumerable: false,
configurable: true
});
CustomTaskRender.prototype.getViewItem = function (index) {
return this._renderHelper.getViewItem(index);
};
CustomTaskRender.prototype.getTask = function (index) {
return this._renderHelper.getTask(index);
};
CustomTaskRender.prototype.destroyTemplate = function (container) {
this._renderHelper.destroyTemplate(container);
};
CustomTaskRender.prototype.getTaskDependencies = function (taskInternalId) {
return this._renderHelper.getTaskDependencies(taskInternalId);
};
CustomTaskRender.prototype.getTaskResources = function (key) {
return this._renderHelper.getTaskResources(key);
};
CustomTaskRender.prototype.attachEventsOnTask = function (taskIndex) {
this._renderHelper.attachEventsOnTask(taskIndex);
};
CustomTaskRender.prototype.recreateConnectorLineElement = function (dependencyId, forceRender) {
if (forceRender === void 0) { forceRender = false; }
this._renderHelper.recreateConnectorLineElement(dependencyId, forceRender);
};
CustomTaskRender.prototype.createTaskSelectionElement = function (taskIndex) {
this._taskRender.createTaskSelectionElement(taskIndex);
};
CustomTaskRender.prototype.createCustomTaskElement = function (index, taskTemplateFunction) {
var _this = this;
var viewItem = this.getViewItem(index);
viewItem.isCustom = false;
var taskTemplateContainer = document.createElement("DIV");
var taskInformation = this.createCustomTaskInformation(index);
viewItem.isCustom = true;
taskTemplateFunction(taskTemplateContainer, taskInformation, function (taskTemplateContainer, taskIndex) { _this.drawCustomTask(taskTemplateContainer, taskIndex); }, index);
};
CustomTaskRender.prototype.createCustomTaskWrapperElement = function (index, taskWrapperInfo) {
RenderElementUtils_1.RenderElementUtils.create(taskWrapperInfo, index, this.taskArea, this.taskElements);
};
CustomTaskRender.prototype.createCustomTaskVisualElement = function (index, taskElementInfo) {
var taskElement = RenderElementUtils_1.RenderElementUtils.create(taskElementInfo, index, this.taskElements[index]);
return taskElement;
};
CustomTaskRender.prototype.drawCustomTask = function (taskTemplateContainer, taskIndex) {
var _this = this;
if (!this.taskElements[taskIndex])
return;
var viewItem = this.getViewItem(taskIndex);
viewItem.visible = !!taskTemplateContainer.innerHTML;
this.taskElements[taskIndex].innerHTML = taskTemplateContainer.innerHTML;
viewItem.size.height = this.taskElements[taskIndex].offsetHeight;
viewItem.size.width = this.taskElements[taskIndex].offsetWidth;
this.destroyTemplate(this.taskElements[taskIndex]);
this._taskRender.removeTaskElement(taskIndex);
if (viewItem.visible) {
var taskWrapperInfo = this.gridLayoutCalculator.getTaskWrapperElementInfo(taskIndex);
this.createCustomTaskWrapperElement(taskIndex, taskWrapperInfo);
this.taskElements[taskIndex].appendChild(taskTemplateContainer);
this.attachEventsOnTask(taskIndex);
}
else {
var taskDependencies = this.getTaskDependencies(viewItem.task.internalId);
if (taskDependencies.length) {
this._taskRender.addInvalidTaskDependencies(taskDependencies);
taskDependencies.forEach(function (d) { return _this.recreateConnectorLineElement(d.internalId, true); });
}
}
if (this._taskRender.isHighlightRowElementAllowed(taskIndex))
this._taskRender.createHighlightRowElement(taskIndex);
if (viewItem.selected)
this.createTaskSelectionElement(taskIndex);
};
CustomTaskRender.prototype.createCustomTaskInformation = function (index) {
var task = this.getTask(index);
var viewItem = this.getViewItem(index);
var taskWrapperInfo = this.gridLayoutCalculator.getTaskWrapperElementInfo(index);
var taskElementInfo = this.gridLayoutCalculator.getTaskElementInfo(index, this.taskTitlePosition !== Enums_1.TaskTitlePosition.Inside);
this.createCustomTaskWrapperElement(index, taskWrapperInfo);
var taskVisualElement = this.createCustomTaskVisualElement(index, taskElementInfo);
this._taskRender.createTaskTextElement(index, taskVisualElement);
var taskResources = this.getTaskResources(task.id);
var taskInformation = {
cellSize: this.tickSize,
isMilestone: task.isMilestone(),
isParent: !!(viewItem === null || viewItem === void 0 ? void 0 : viewItem.children.length),
taskData: task,
taskHTML: taskVisualElement,
taskPosition: taskWrapperInfo.position,
taskResources: taskResources,
taskSize: taskElementInfo.size,
};
return taskInformation;
};
return CustomTaskRender;
}());
exports.CustomTaskRender = CustomTaskRender;
/***/ }),
/* 213 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MainElementsRender = void 0;
var MainElementsRender = (function () {
function MainElementsRender() {
}
MainElementsRender.prototype.createMainElement = function (parent) {
var mainElement = document.createElement("DIV");
mainElement.style.width = parent.offsetWidth + "px";
mainElement.style.height = parent.offsetHeight + "px";
return mainElement;
};
MainElementsRender.prototype.createHeader = function () {
var header = document.createElement("DIV");
header.className = "dx-gantt-header";
return header;
};
return MainElementsRender;
}());
exports.MainElementsRender = MainElementsRender;
/***/ }),
/* 214 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskAreaContainer = void 0;
var TaskAreaContainer = (function () {
function TaskAreaContainer(element, ganttView) {
this.element = element;
this.onScrollHandler = function () { ganttView.updateView(); };
this.element.addEventListener("scroll", this.onScrollHandler);
}
Object.defineProperty(TaskAreaContainer.prototype, "scrollTop", {
get: function () {
return this.element.scrollTop;
},
set: function (value) {
this.element.scrollTop = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaContainer.prototype, "scrollLeft", {
get: function () {
return this.element.scrollLeft;
},
set: function (value) {
this.element.scrollLeft = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaContainer.prototype, "scrollWidth", {
get: function () {
return this.element.scrollWidth;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaContainer.prototype, "scrollHeight", {
get: function () {
return this.element.scrollHeight;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TaskAreaContainer.prototype, "isExternal", {
get: function () {
return false;
},
enumerable: false,
configurable: true
});
TaskAreaContainer.prototype.getWidth = function () {
return this.element.offsetWidth;
};
TaskAreaContainer.prototype.getHeight = function () {
return this.element.offsetHeight;
};
TaskAreaContainer.prototype.getElement = function () {
return this.element;
};
TaskAreaContainer.prototype.detachEvents = function () {
this.element.removeEventListener("scroll", this.onScrollHandler);
};
return TaskAreaContainer;
}());
exports.TaskAreaContainer = TaskAreaContainer;
/***/ }),
/* 215 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ElementTextHelper = void 0;
var dom_1 = __webpack_require__(3);
var Enums_1 = __webpack_require__(2);
var DateUtils_1 = __webpack_require__(21);
var ElementTextHelper = (function () {
function ElementTextHelper(cultureInfo) {
this.longestAbbrMonthName = null;
this.longestMonthName = null;
this.longestAbbrDayName = null;
var canvas = document.createElement("canvas");
this.textMeasureContext = canvas.getContext("2d");
this.cultureInfo = cultureInfo;
}
ElementTextHelper.prototype.setFont = function (fontHolder) {
var computedStyle = dom_1.DomUtils.getCurrentStyle(fontHolder);
var font = computedStyle.font ? computedStyle.font :
computedStyle.fontStyle + " " + computedStyle.fontVariant + " " + computedStyle.fontWeight + " "
+ computedStyle.fontSize + " / " + computedStyle.lineHeight + " " + computedStyle.fontFamily;
this.textMeasureContext.font = font;
};
ElementTextHelper.prototype.setSettings = function (startTime, viewType, modelItems) {
this.startTime = startTime;
this.viewType = viewType;
this.modelItems = modelItems;
};
ElementTextHelper.prototype.getScaleStartDateCorrectedWithDST = function (date) {
var timeZoneDiff = DateUtils_1.DateUtils.getTimezoneOffsetDiff(new Date(this.startTime), date);
return timeZoneDiff > 0 ? new Date(date.getTime() + timeZoneDiff * 60000) : date;
};
ElementTextHelper.prototype.getScaleItemText = function (date, scaleType) {
date = this.getScaleStartDateCorrectedWithDST(date);
var isViewTypeScale = this.viewType.valueOf() === scaleType.valueOf();
switch (scaleType) {
case Enums_1.ViewType.TenMinutes:
return this.getTenMinutesScaleItemText(date);
case Enums_1.ViewType.Hours:
case Enums_1.ViewType.SixHours:
return this.getHoursScaleItemText(date);
case Enums_1.ViewType.Days:
return this.getDaysScaleItemText(date, isViewTypeScale);
case Enums_1.ViewType.Weeks:
return this.getWeeksScaleItemText(date, isViewTypeScale);
case Enums_1.ViewType.Months:
return this.getMonthsScaleItemText(date, isViewTypeScale);
case Enums_1.ViewType.Quarter:
return this.getQuarterScaleItemText(date, isViewTypeScale);
case Enums_1.ViewType.Years:
return this.getYearsScaleItemText(date);
case Enums_1.ViewType.FiveYears:
return this.getFiveYearsScaleItemText(date);
}
};
ElementTextHelper.prototype.getTenMinutesScaleItemText = function (scaleItemDate) {
var minutes = scaleItemDate.getMinutes() + 1;
return (Math.ceil(minutes / 10) * 10).toString();
};
ElementTextHelper.prototype.getThirtyMinutesScaleItemText = function (scaleItemDate) {
var minutes = scaleItemDate.getMinutes();
return minutes < 30 ? "30" : "60";
};
ElementTextHelper.prototype.getHoursScaleItemText = function (scaleItemDate) {
var hours = scaleItemDate.getHours();
var hourDisplayText = this.getHourDisplayText(hours);
var amPmText = hours < 12 ? this.getAmText() : this.getPmText();
return this.getHoursScaleItemTextCore(hourDisplayText, amPmText);
};
ElementTextHelper.prototype.getDaysScaleItemText = function (scaleItemDate, isViewTypeScale) {
return this.getDayTotalText(scaleItemDate, true, isViewTypeScale, isViewTypeScale, !isViewTypeScale);
};
ElementTextHelper.prototype.getWeeksScaleItemText = function (scaleItemDate, isViewTypeScale) {
var weekLastDayDate = new Date(scaleItemDate.getTime() + DateUtils_1.DateUtils.msPerWeek - DateUtils_1.DateUtils.msPerDay);
return this.getWeeksScaleItemTextCore(this.getDayTotalText(scaleItemDate, isViewTypeScale, true, isViewTypeScale, !isViewTypeScale), this.getDayTotalText(weekLastDayDate, isViewTypeScale, true, isViewTypeScale, !isViewTypeScale));
};
ElementTextHelper.prototype.getMonthsScaleItemText = function (scaleItemDate, isViewTypeScale) {
var monthNames = this.getMonthNames();
var yearDisplayText = !isViewTypeScale ? scaleItemDate.getFullYear().toString() : "";
return this.getMonthsScaleItemTextCore(monthNames[scaleItemDate.getMonth()], yearDisplayText);
};
ElementTextHelper.prototype.getQuarterScaleItemText = function (scaleItemDate, isViewTypeScale) {
var quarterNames = this.getQuarterNames();
var yearDisplayText = !isViewTypeScale ? scaleItemDate.getFullYear().toString() : "";
return this.getMonthsScaleItemTextCore(quarterNames[Math.floor(scaleItemDate.getMonth() / 3)], yearDisplayText);
};
ElementTextHelper.prototype.getYearsScaleItemText = function (scaleItemDate) {
return scaleItemDate.getFullYear().toString();
};
ElementTextHelper.prototype.getFiveYearsScaleItemText = function (scaleItemDate) {
return scaleItemDate.getFullYear().toString() + " - " + (scaleItemDate.getFullYear() + 4).toString();
};
ElementTextHelper.prototype.getHourDisplayText = function (hours) {
if (this.hasAmPm())
return (hours == 0 ? 12 : (hours <= 12 ? hours : hours - 12)).toString();
return hours < 10 ? "0" + hours : hours.toString();
};
ElementTextHelper.prototype.getDayTotalText = function (scaleItemDate, displayDayName, useAbbrDayNames, useAbbrMonthNames, displayYear) {
var monthNames = useAbbrMonthNames ? this.getAbbrMonthNames() : this.getMonthNames();
var dayNames = useAbbrDayNames ? this.getAbbrDayNames() : this.getDayNames();
var dayNameDisplayText = displayDayName ? dayNames[scaleItemDate.getDay()] : "";
var day = scaleItemDate.getDate();
var monthName = monthNames[scaleItemDate.getMonth()];
var yearDisplayText = displayYear ? scaleItemDate.getFullYear().toString() : "";
return this.getDayTotalTextCore(dayNameDisplayText, day.toString(), monthName, yearDisplayText);
};
ElementTextHelper.prototype.getTaskText = function (index) {
var item = this.modelItems[index];
return item ? item.task.title : "";
};
ElementTextHelper.prototype.getTaskVisibility = function (index) {
var item = this.modelItems[index];
return !!item && item.getVisible();
};
ElementTextHelper.prototype.hasAmPm = function () {
return this.getAmText().length > 0 || this.getPmText().length > 0;
};
ElementTextHelper.prototype.getScaleItemTextTemplate = function (viewType) {
switch (viewType) {
case Enums_1.ViewType.TenMinutes:
return "00";
case Enums_1.ViewType.Hours:
case Enums_1.ViewType.SixHours:
return this.getHoursScaleItemTextCore("00", this.getAmText());
case Enums_1.ViewType.Days:
return this.getDayTextTemplate();
case Enums_1.ViewType.Weeks:
return this.getWeekTextTemplate();
case Enums_1.ViewType.Months:
return this.getMonthsScaleItemTextCore(this.getLongestMonthName(), "");
case Enums_1.ViewType.Quarter:
return "Q4";
case Enums_1.ViewType.Years:
return "0000";
}
};
ElementTextHelper.prototype.getDayTextTemplate = function () {
return this.getDayTotalTextCore(this.getLongestAbbrDayName(), "00", this.getLongestAbbrMonthName(), "");
};
ElementTextHelper.prototype.getWeekTextTemplate = function () {
var dayTextTemplate = this.getDayTextTemplate();
return this.getWeeksScaleItemTextCore(dayTextTemplate, dayTextTemplate);
};
ElementTextHelper.prototype.getHoursScaleItemTextCore = function (hourDisplayText, amPmText) {
return hourDisplayText + ":00" + (this.hasAmPm() ? " " + amPmText : "");
};
ElementTextHelper.prototype.getDayTotalTextCore = function (dayName, dayValueString, monthName, yearValueString) {
var result = dayName.length > 0 ? dayName + ", " : "";
result += dayValueString + " " + monthName;
result += yearValueString.length > 0 ? " " + yearValueString : "";
return result;
};
ElementTextHelper.prototype.getWeeksScaleItemTextCore = function (firstDayOfWeekString, lastDayOfWeekString) {
return firstDayOfWeekString + " - " + lastDayOfWeekString;
};
ElementTextHelper.prototype.getMonthsScaleItemTextCore = function (monthName, yearValueString) {
var result = monthName;
if (yearValueString.length > 0)
result += " " + yearValueString;
return result;
};
ElementTextHelper.prototype.getLongestAbbrMonthName = function () {
if (this.longestAbbrMonthName == null)
this.longestAbbrMonthName = this.getLongestText(this.getAbbrMonthNames());
return this.longestAbbrMonthName;
};
ElementTextHelper.prototype.getLongestMonthName = function () {
if (this.longestMonthName == null)
this.longestMonthName = this.getLongestText(this.getMonthNames());
return this.longestMonthName;
};
ElementTextHelper.prototype.getLongestAbbrDayName = function () {
if (this.longestAbbrDayName == null)
this.longestAbbrDayName = this.getLongestText(this.getAbbrDayNames());
return this.longestAbbrDayName;
};
ElementTextHelper.prototype.getLongestText = function (texts) {
var _this = this;
var result = "";
var longestTextWidth = 0;
texts.forEach(function (text) {
var textWidth = _this.getTextWidth(text);
if (textWidth > longestTextWidth) {
longestTextWidth = textWidth;
result = text;
}
});
return result;
};
ElementTextHelper.prototype.getTextWidth = function (text) {
return Math.round(this.textMeasureContext.measureText(text).width);
};
ElementTextHelper.prototype.getAmText = function () {
return this.cultureInfo.amText;
};
ElementTextHelper.prototype.getPmText = function () {
return this.cultureInfo.pmText;
};
ElementTextHelper.prototype.getQuarterNames = function () {
return this.cultureInfo.quarterNames;
};
ElementTextHelper.prototype.getMonthNames = function () {
return this.cultureInfo.monthNames;
};
ElementTextHelper.prototype.getDayNames = function () {
return this.cultureInfo.dayNames;
};
ElementTextHelper.prototype.getAbbrMonthNames = function () {
return this.cultureInfo.abbrMonthNames;
};
ElementTextHelper.prototype.getAbbrDayNames = function () {
return this.cultureInfo.abbrDayNames;
};
return ElementTextHelper;
}());
exports.ElementTextHelper = ElementTextHelper;
/***/ }),
/* 216 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Settings = void 0;
var common_1 = __webpack_require__(1);
var DateTimeUtils_1 = __webpack_require__(7);
var Enums_1 = __webpack_require__(2);
var EditingSettings_1 = __webpack_require__(217);
var StripLineSettings_1 = __webpack_require__(82);
var ValidationSettings_1 = __webpack_require__(218);
var ViewTypeRange_1 = __webpack_require__(219);
var Settings = (function () {
function Settings() {
this.viewType = undefined;
this.taskTitlePosition = Enums_1.TaskTitlePosition.Inside;
this.showResources = true;
this.showDependencies = true;
this.areHorizontalBordersEnabled = true;
this.areVerticalBordersEnabled = true;
this.areAlternateRowsEnabled = true;
this.allowSelectTask = true;
this.firstDayOfWeek = 0;
this.editing = new EditingSettings_1.EditingSettings();
this.validation = new ValidationSettings_1.ValidationSettings();
this.stripLines = new StripLineSettings_1.StripLineSettings();
this.viewTypeRange = new ViewTypeRange_1.ViewTypeRangeSettings();
}
Settings.parse = function (settings) {
var result = new Settings();
if (settings) {
if ((0, common_1.isDefined)(settings.viewType))
result.viewType = settings.viewType;
if ((0, common_1.isDefined)(settings.taskTitlePosition))
result.taskTitlePosition = settings.taskTitlePosition;
if ((0, common_1.isDefined)(settings.showResources))
result.showResources = settings.showResources;
if ((0, common_1.isDefined)(settings.showDependencies))
result.showDependencies = settings.showDependencies;
if ((0, common_1.isDefined)(settings.areHorizontalBordersEnabled))
result.areHorizontalBordersEnabled = settings.areHorizontalBordersEnabled;
if ((0, common_1.isDefined)(settings.areVerticalBordersEnabled))
result.areHorizontalBordersEnabled = settings.areHorizontalBordersEnabled;
if ((0, common_1.isDefined)(settings.areAlternateRowsEnabled))
result.areAlternateRowsEnabled = settings.areAlternateRowsEnabled;
if ((0, common_1.isDefined)(settings.allowSelectTask))
result.allowSelectTask = settings.allowSelectTask;
if ((0, common_1.isDefined)(settings.firstDayOfWeek))
result.firstDayOfWeek = settings.firstDayOfWeek;
if ((0, common_1.isDefined)(settings.startDateRange))
result.startDateRange = new Date(settings.startDateRange);
if ((0, common_1.isDefined)(settings.endDateRange))
result.endDateRange = new Date(settings.endDateRange);
if ((0, common_1.isDefined)(settings.editing))
result.editing = EditingSettings_1.EditingSettings.parse(settings.editing);
if ((0, common_1.isDefined)(settings.validation))
result.validation = ValidationSettings_1.ValidationSettings.parse(settings.validation);
if ((0, common_1.isDefined)(settings.stripLines))
result.stripLines = StripLineSettings_1.StripLineSettings.parse(settings.stripLines);
if ((0, common_1.isDefined)(settings.viewTypeRange))
result.viewTypeRange = ViewTypeRange_1.ViewTypeRangeSettings.parse(settings.viewTypeRange);
if ((0, common_1.isDefined)(settings.taskTooltipContentTemplate))
result.taskTooltipContentTemplate = settings.taskTooltipContentTemplate;
if ((0, common_1.isDefined)(settings.taskProgressTooltipContentTemplate))
result.taskProgressTooltipContentTemplate = settings.taskProgressTooltipContentTemplate;
if ((0, common_1.isDefined)(settings.taskTimeTooltipContentTemplate))
result.taskTimeTooltipContentTemplate = settings.taskTimeTooltipContentTemplate;
if ((0, common_1.isDefined)(settings.taskContentTemplate))
result.taskContentTemplate = settings.taskContentTemplate;
if ((0, common_1.isDefined)(settings.cultureInfo))
result.cultureInfo = settings.cultureInfo;
}
return result;
};
Settings.prototype.equal = function (settings) {
var result = true;
result = result && this.viewType === settings.viewType;
result = result && this.taskTitlePosition === settings.taskTitlePosition;
result = result && this.showResources === settings.showResources;
result = result && this.showDependencies === settings.showDependencies;
result = result && this.areHorizontalBordersEnabled === settings.areHorizontalBordersEnabled;
result = result && this.areAlternateRowsEnabled === settings.areAlternateRowsEnabled;
result = result && this.allowSelectTask === settings.allowSelectTask;
result = result && this.editing.equal(settings.editing);
result = result && this.validation.equal(settings.validation);
result = result && this.stripLines.equal(settings.stripLines);
result = result && DateTimeUtils_1.DateTimeUtils.areDatesEqual(this.startDateRange, settings.startDateRange);
result = result && DateTimeUtils_1.DateTimeUtils.areDatesEqual(this.endDateRange, settings.endDateRange);
return result;
};
return Settings;
}());
exports.Settings = Settings;
/***/ }),
/* 217 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EditingSettings = void 0;
var common_1 = __webpack_require__(1);
var EditingSettings = (function () {
function EditingSettings() {
this.enabled = false;
this.allowDependencyDelete = true;
this.allowDependencyInsert = true;
this.allowTaskDelete = true;
this.allowTaskInsert = true;
this.allowTaskUpdate = true;
this.allowResourceDelete = true;
this.allowResourceInsert = true;
this.allowResourceUpdate = true;
this.allowTaskResourceUpdate = true;
}
EditingSettings.parse = function (settings) {
var result = new EditingSettings();
if (settings) {
if ((0, common_1.isDefined)(settings.enabled))
result.enabled = settings.enabled;
if ((0, common_1.isDefined)(settings.allowDependencyDelete))
result.allowDependencyDelete = settings.allowDependencyDelete;
if ((0, common_1.isDefined)(settings.allowDependencyInsert))
result.allowDependencyInsert = settings.allowDependencyInsert;
if ((0, common_1.isDefined)(settings.allowTaskDelete))
result.allowTaskDelete = settings.allowTaskDelete;
if ((0, common_1.isDefined)(settings.allowTaskInsert))
result.allowTaskInsert = settings.allowTaskInsert;
if ((0, common_1.isDefined)(settings.allowTaskUpdate))
result.allowTaskUpdate = settings.allowTaskUpdate;
if ((0, common_1.isDefined)(settings.allowResourceDelete))
result.allowResourceDelete = settings.allowResourceDelete;
if ((0, common_1.isDefined)(settings.allowResourceInsert))
result.allowResourceInsert = settings.allowResourceInsert;
if ((0, common_1.isDefined)(settings.allowResourceUpdate))
result.allowResourceUpdate = settings.allowResourceUpdate;
if ((0, common_1.isDefined)(settings.allowTaskResourceUpdate))
result.allowTaskResourceUpdate = settings.allowTaskResourceUpdate;
}
return result;
};
EditingSettings.prototype.equal = function (settings) {
var result = true;
result = result && this.enabled === settings.enabled;
result = result && this.allowDependencyDelete === settings.allowDependencyDelete;
result = result && this.allowDependencyInsert === settings.allowDependencyInsert;
result = result && this.allowTaskDelete === settings.allowTaskDelete;
result = result && this.allowTaskInsert === settings.allowTaskInsert;
result = result && this.allowTaskUpdate === settings.allowTaskUpdate;
result = result && this.allowResourceDelete === settings.allowResourceDelete;
result = result && this.allowResourceInsert === settings.allowResourceInsert;
result = result && this.allowResourceUpdate === settings.allowResourceUpdate;
result = result && this.allowTaskResourceUpdate === settings.allowTaskResourceUpdate;
return result;
};
return EditingSettings;
}());
exports.EditingSettings = EditingSettings;
/***/ }),
/* 218 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValidationSettings = void 0;
var common_1 = __webpack_require__(1);
var ValidationSettings = (function () {
function ValidationSettings() {
this.validateDependencies = false;
this.autoUpdateParentTasks = false;
this.enablePredecessorGap = false;
}
ValidationSettings.parse = function (settings) {
var result = new ValidationSettings();
if (settings) {
if ((0, common_1.isDefined)(settings.validateDependencies))
result.validateDependencies = settings.validateDependencies;
if ((0, common_1.isDefined)(settings.autoUpdateParentTasks))
result.autoUpdateParentTasks = settings.autoUpdateParentTasks;
if ((0, common_1.isDefined)(settings.enablePredecessorGap))
result.enablePredecessorGap = settings.enablePredecessorGap;
}
return result;
};
ValidationSettings.prototype.equal = function (settings) {
var result = true;
result = result && this.validateDependencies === settings.validateDependencies;
result = result && this.autoUpdateParentTasks === settings.autoUpdateParentTasks;
result = result && this.enablePredecessorGap === settings.enablePredecessorGap;
return result;
};
return ValidationSettings;
}());
exports.ValidationSettings = ValidationSettings;
/***/ }),
/* 219 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ViewTypeRangeSettings = void 0;
var common_1 = __webpack_require__(1);
var Enums_1 = __webpack_require__(2);
var ViewTypeRangeSettings = (function () {
function ViewTypeRangeSettings() {
this.min = Enums_1.ViewType.TenMinutes;
this.max = Enums_1.ViewType.Years;
}
ViewTypeRangeSettings.parse = function (settings) {
var result = new ViewTypeRangeSettings();
if (settings) {
if ((0, common_1.isDefined)(settings.min))
result.min = settings.min;
if ((0, common_1.isDefined)(settings.max))
result.max = settings.max;
}
return result;
};
ViewTypeRangeSettings.prototype.equal = function (settings) {
var result = true;
result = result && this.min === settings.min;
result = result && this.max === settings.max;
return result;
};
return ViewTypeRangeSettings;
}());
exports.ViewTypeRangeSettings = ViewTypeRangeSettings;
/***/ }),
/* 220 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskEditSettings = void 0;
var tslib_1 = __webpack_require__(0);
var common_1 = __webpack_require__(1);
var TooltipSettings_1 = __webpack_require__(71);
var TaskEditSettings = (function (_super) {
(0, tslib_1.__extends)(TaskEditSettings, _super);
function TaskEditSettings() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskEditSettings.parse = function (settings) {
var result = new TaskEditSettings();
if (settings) {
if ((0, common_1.isDefined)(settings.getCommandManager))
result.getCommandManager = settings.getCommandManager;
if ((0, common_1.isDefined)(settings.getViewModel))
result.getViewModel = settings.getViewModel;
if ((0, common_1.isDefined)(settings.getGanttSettings))
result.getGanttSettings = settings.getGanttSettings;
if ((0, common_1.isDefined)(settings.getRenderHelper))
result.getRenderHelper = settings.getRenderHelper;
if ((0, common_1.isDefined)(settings.destroyTemplate))
result.destroyTemplate = settings.destroyTemplate;
if ((0, common_1.isDefined)(settings.formatDate))
result.formatDate = settings.formatDate;
if ((0, common_1.isDefined)(settings.getModelManipulator))
result.getModelManipulator = settings.getModelManipulator;
if ((0, common_1.isDefined)(settings.getValidationController))
result.getValidationController = settings.getValidationController;
}
return result;
};
return TaskEditSettings;
}(TooltipSettings_1.TooltipSettings));
exports.TaskEditSettings = TaskEditSettings;
/***/ }),
/* 221 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValidationController = void 0;
var tslib_1 = __webpack_require__(0);
var common_1 = __webpack_require__(1);
var Enums_1 = __webpack_require__(24);
var TaskEndHistoryItem_1 = __webpack_require__(35);
var TaskMoveHistoryItem_1 = __webpack_require__(65);
var TaskProgressHistoryItem_1 = __webpack_require__(36);
var TaskStartHistoryItem_1 = __webpack_require__(37);
var DateRange_1 = __webpack_require__(14);
var DateTimeUtils_1 = __webpack_require__(7);
var ValidationError_1 = __webpack_require__(222);
var ValidationController = (function () {
function ValidationController(settings) {
this.lockPredecessorToSuccessor = true;
this.settings = settings;
}
Object.defineProperty(ValidationController.prototype, "viewModel", {
get: function () {
return this.settings.getViewModel();
},
enumerable: false,
configurable: true
});
Object.defineProperty(ValidationController.prototype, "history", {
get: function () {
return this.settings.getHistory();
},
enumerable: false,
configurable: true
});
Object.defineProperty(ValidationController.prototype, "modelManipulator", {
get: function () {
return this.settings.getModelManipulator();
},
enumerable: false,
configurable: true
});
Object.defineProperty(ValidationController.prototype, "range", {
get: function () {
return this.settings.getRange();
},
enumerable: false,
configurable: true
});
Object.defineProperty(ValidationController.prototype, "validationSettings", {
get: function () {
return this.settings.getValidationSettings();
},
enumerable: false,
configurable: true
});
Object.defineProperty(ValidationController.prototype, "_parentAutoCalc", {
get: function () {
return this.viewModel.parentAutoCalc;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ValidationController.prototype, "enablePredecessorGap", {
get: function () {
return this.viewModel.enablePredecessorGap;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ValidationController.prototype, "isValidateDependenciesRequired", {
get: function () {
return this.settings.getIsValidateDependenciesRequired();
},
enumerable: false,
configurable: true
});
ValidationController.prototype.updateOwnerInAutoParentMode = function () {
this.settings.updateOwnerInAutoParentMode();
};
ValidationController.prototype.checkStartDependencies = function (taskId, date) {
var _this = this;
var result = [];
var task = this.viewModel.tasks.getItemById(taskId);
var dependencies = this.viewModel.dependencies.items.filter(function (d) { return d.successorId === taskId; });
dependencies.forEach(function (dep) {
var predecessorTask = _this.viewModel.tasks.getItemById(dep.predecessorId);
if (dep.type === Enums_1.DependencyType.FS && predecessorTask.end > date
|| dep.type === Enums_1.DependencyType.SS && predecessorTask.start > date)
result.push(new ValidationError_1.ValidationError(dep.internalId, true));
if (dep.type === Enums_1.DependencyType.FS && predecessorTask.end.valueOf() === task.start.valueOf() && date > predecessorTask.end ||
dep.type === Enums_1.DependencyType.SS && predecessorTask.start.valueOf() === task.start.valueOf() && date > predecessorTask.start)
result.push(new ValidationError_1.ValidationError(dep.internalId));
});
return result;
};
ValidationController.prototype.checkEndDependencies = function (taskId, date) {
var _this = this;
var result = [];
var task = this.viewModel.tasks.getItemById(taskId);
var dependencies = this.viewModel.dependencies.items.filter(function (d) { return d.successorId === taskId; });
dependencies.forEach(function (dep) {
var predecessorTask = _this.viewModel.tasks.getItemById(dep.predecessorId);
if (dep.type === Enums_1.DependencyType.SF && predecessorTask.start > date
|| dep.type === Enums_1.DependencyType.FF && predecessorTask.end > date)
result.push(new ValidationError_1.ValidationError(dep.internalId, true));
if ((dep.type === Enums_1.DependencyType.SF && predecessorTask.start.valueOf() === task.end.valueOf() && date > predecessorTask.start) ||
(dep.type === Enums_1.DependencyType.FF && predecessorTask.end.valueOf() === task.end.valueOf() && date > predecessorTask.end))
result.push(new ValidationError_1.ValidationError(dep.internalId));
});
return result;
};
ValidationController.prototype.moveEndDependTasks = function (predecessorTaskId, predecessorPreviousEndDate, isAfterCorrectParents) {
var _this = this;
if (isAfterCorrectParents === void 0) { isAfterCorrectParents = false; }
var dependencies = this.viewModel.dependencies.items.filter(function (d) { return d.predecessorId === predecessorTaskId && !d.isStartDependency; });
var predecessorTask = this.viewModel.tasks.getItemById(predecessorTaskId);
dependencies.forEach(function (dependency) {
var successorTask = _this.viewModel.tasks.getItemById(dependency.successorId);
var isMoveNotRequired = !successorTask || (isAfterCorrectParents && predecessorTask.parentId === successorTask.parentId) || (successorTask.parentId == predecessorTask.id);
if (isMoveNotRequired)
return;
var successorRangeBeforeMove = new DateRange_1.DateRange(new Date(successorTask.start.getTime()), new Date(successorTask.end.getTime()));
var validTaskRange = new DateRange_1.DateRange(new Date(successorTask.start.getTime()), new Date(successorTask.end.getTime()));
var delta = predecessorTask.end.getTime() - predecessorPreviousEndDate.getTime();
var predecessorEnd = _this.enablePredecessorGap ? predecessorTask.end : predecessorPreviousEndDate;
if (dependency.type === Enums_1.DependencyType.FS
&& (successorTask.start < predecessorEnd
|| (_this.lockPredecessorToSuccessor && successorTask.start.getTime() === predecessorPreviousEndDate.getTime()))) {
validTaskRange.start.setTime(predecessorTask.end.getTime());
validTaskRange.end.setTime(validTaskRange.start.getTime() + (successorTask.end.getTime() - successorTask.start.getTime()));
_this.correctMoving(successorTask.internalId, validTaskRange);
}
else if (dependency.type === Enums_1.DependencyType.FF
&& (successorTask.end < predecessorEnd
|| (_this.lockPredecessorToSuccessor && successorTask.end.getTime() === predecessorPreviousEndDate.getTime()))) {
validTaskRange.start.setTime(predecessorTask.end.getTime() - (successorTask.end.getTime() - successorTask.start.getTime()));
validTaskRange.end.setTime(predecessorTask.end.getTime());
_this.correctMoving(successorTask.internalId, validTaskRange);
}
else if (!_this.enablePredecessorGap) {
validTaskRange.start.setTime(successorTask.start.getTime() + delta);
validTaskRange.end.setTime(successorTask.end.getTime() + delta);
}
if (!successorRangeBeforeMove.equal(validTaskRange)) {
_this.history.addAndRedo(new TaskMoveHistoryItem_1.TaskMoveHistoryItem(_this.modelManipulator, dependency.successorId, validTaskRange));
_this.moveRelatedTasks(dependency, successorRangeBeforeMove, successorTask, validTaskRange);
}
});
};
ValidationController.prototype.moveStartDependTasks = function (predecessorTaskId, predecessorPreviousStartDate, isAfterCorrectParents) {
var _this = this;
if (isAfterCorrectParents === void 0) { isAfterCorrectParents = false; }
var dependencies = this.viewModel.dependencies.items.filter(function (d) { return d.predecessorId === predecessorTaskId && d.isStartDependency; });
var predecessorTask = this.viewModel.tasks.getItemById(predecessorTaskId);
dependencies.forEach(function (dependency) {
var successorTask = _this.viewModel.tasks.getItemById(dependency.successorId);
var isMoveNotRequired = !successorTask || (isAfterCorrectParents && predecessorTask.parentId === successorTask.parentId) || (successorTask.parentId == predecessorTask.id);
if (isMoveNotRequired)
return;
var successorRangeBeforeMove = new DateRange_1.DateRange(new Date(successorTask.start.getTime()), new Date(successorTask.end.getTime()));
var validTaskRange = new DateRange_1.DateRange(new Date(successorTask.start.getTime()), new Date(successorTask.end.getTime()));
var delta = predecessorTask.start.getTime() - predecessorPreviousStartDate.getTime();
var predecessorStart = _this.enablePredecessorGap ? predecessorTask.start : predecessorPreviousStartDate;
if (dependency.type === Enums_1.DependencyType.SF
&& (successorTask.end < predecessorStart
|| (_this.lockPredecessorToSuccessor && successorTask.end.getTime() === predecessorPreviousStartDate.getTime()))) {
validTaskRange.start.setTime(predecessorTask.start.getTime() - (successorTask.end.getTime() - successorTask.start.getTime()));
validTaskRange.end.setTime(predecessorTask.start.getTime());
_this.correctMoving(successorTask.internalId, validTaskRange);
}
else if (dependency.type === Enums_1.DependencyType.SS
&& (successorTask.start < predecessorStart
|| (_this.lockPredecessorToSuccessor && successorTask.start.getTime() === predecessorPreviousStartDate.getTime()))) {
validTaskRange.start.setTime(predecessorTask.start.getTime());
validTaskRange.end.setTime(predecessorTask.start.getTime() + (successorTask.end.getTime() - successorTask.start.getTime()));
_this.correctMoving(successorTask.internalId, validTaskRange);
}
else if (!_this.enablePredecessorGap) {
validTaskRange.start.setTime(successorTask.start.getTime() + delta);
validTaskRange.end.setTime(successorTask.end.getTime() + delta);
}
if (!successorRangeBeforeMove.equal(validTaskRange)) {
_this.history.addAndRedo(new TaskMoveHistoryItem_1.TaskMoveHistoryItem(_this.modelManipulator, dependency.successorId, validTaskRange));
_this.moveRelatedTasks(dependency, successorRangeBeforeMove, successorTask, validTaskRange);
}
});
};
ValidationController.prototype.moveRelatedTasks = function (dependency, successorRangeBeforeMove, successorTask, validTaskRange) {
var delta = validTaskRange.start.getTime() - successorRangeBeforeMove.start.getTime();
this.correctParentsOnChildMoving(successorTask.internalId, delta);
this.moveStartDependTasks(dependency.successorId, successorRangeBeforeMove.start);
this.moveEndDependTasks(dependency.successorId, successorRangeBeforeMove.end);
};
ValidationController.prototype.getCorrectDateRange = function (taskId, startDate, endDate) {
var _this = this;
var dateRange = new DateRange_1.DateRange(new Date(startDate), new Date(endDate));
var validationErrors = (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], this.checkStartDependencies(taskId, dateRange.start), true), this.checkEndDependencies(taskId, dateRange.end), true);
var criticalErrors = validationErrors.filter(function (e) { return e.critical; });
criticalErrors.forEach(function (error) {
var dependency = _this.viewModel.dependencies.getItemById(error.dependencyId);
var predecessorTask = _this.viewModel.tasks.getItemById(dependency.predecessorId);
if (dependency.type === Enums_1.DependencyType.FS)
if (dateRange.start < predecessorTask.end)
dateRange.start.setTime(predecessorTask.end.getTime());
if (dependency.type === Enums_1.DependencyType.SS)
if (dateRange.start < predecessorTask.start)
dateRange.start.setTime(predecessorTask.start.getTime());
if (dependency.type === Enums_1.DependencyType.FF)
if (dateRange.end < predecessorTask.end)
dateRange.end.setTime(predecessorTask.end.getTime());
if (dependency.type === Enums_1.DependencyType.SF)
if (dateRange.end < predecessorTask.start)
dateRange.end.setTime(predecessorTask.start.getTime());
});
return dateRange;
};
ValidationController.prototype.correctMoving = function (taskId, dateRange) {
var _this = this;
var deltaDate = dateRange.end.getTime() - dateRange.start.getTime();
var validationErrors = (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], this.checkStartDependencies(taskId, dateRange.start), true), this.checkEndDependencies(taskId, dateRange.end), true);
var criticalErrors = validationErrors.filter(function (e) { return e.critical; });
criticalErrors.forEach(function (error) {
var dependency = _this.viewModel.dependencies.getItemById(error.dependencyId);
var predecessorTask = _this.viewModel.tasks.getItemById(dependency.predecessorId);
if (dependency.type === Enums_1.DependencyType.FS)
if (dateRange.start < predecessorTask.end) {
dateRange.start.setTime(predecessorTask.end.getTime());
dateRange.end.setTime(dateRange.start.getTime() + deltaDate);
}
if (dependency.type === Enums_1.DependencyType.SS)
if (dateRange.start < predecessorTask.start) {
dateRange.start.setTime(predecessorTask.start.getTime());
dateRange.end.setTime(dateRange.start.getTime() + deltaDate);
}
if (dependency.type === Enums_1.DependencyType.FF)
if (dateRange.end < predecessorTask.end) {
dateRange.end.setTime(predecessorTask.end.getTime());
dateRange.start.setTime(dateRange.end.getTime() - deltaDate);
}
if (dependency.type === Enums_1.DependencyType.SF)
if (dateRange.end < predecessorTask.start) {
dateRange.end.setTime(predecessorTask.start.getTime());
dateRange.start.setTime(dateRange.end.getTime() - deltaDate);
}
});
return dateRange;
};
ValidationController.prototype.recalculateParents = function (child, calcStepCallback) {
var parent = child && child.parent;
while (parent && parent.task) {
var children = parent.children;
var start = this.range.end;
var end = this.range.start;
var progress = 0;
var totalDuration = 0;
var data = { id: parent.task.internalId };
for (var i = 0; i < children.length; i++) {
var childTask = children[i].task;
if (!childTask.isValid())
continue;
start = DateTimeUtils_1.DateTimeUtils.getMinDate(start, childTask.start);
end = DateTimeUtils_1.DateTimeUtils.getMaxDate(end, childTask.end);
var duration = childTask.getDuration();
progress += childTask.progress * duration;
totalDuration += duration;
}
if (!DateTimeUtils_1.DateTimeUtils.areDatesEqual(parent.task.start, start))
data["start"] = start;
if (!DateTimeUtils_1.DateTimeUtils.areDatesEqual(parent.task.end, end))
data["end"] = end;
data["oldStart"] = parent.task.start;
data["oldEnd"] = parent.task.end;
progress = totalDuration > 0 ? Math.round(progress / totalDuration) : 0;
if (progress !== parent.task.progress)
data["progress"] = progress;
calcStepCallback(data);
parent = parent.parent;
}
};
ValidationController.prototype.updateParentsRangeByChild = function (taskId) {
var _this = this;
this.recalculateParents(this.viewModel.findItem(taskId), function (data) {
if (!(0, common_1.isDefined)(data.id))
return;
var history = _this.history;
var manipulator = _this.modelManipulator;
if ((0, common_1.isDefined)(data.start)) {
history.addAndRedo(new TaskStartHistoryItem_1.TaskStartHistoryItem(manipulator, data.id, data.start));
_this.moveStartDependTasks(data.id, data.oldStart);
}
if ((0, common_1.isDefined)(data.end)) {
history.addAndRedo(new TaskEndHistoryItem_1.TaskEndHistoryItem(manipulator, data.id, data.end));
_this.moveEndDependTasks(data.id, data.oldEnd);
}
if ((0, common_1.isDefined)(data.progress))
history.addAndRedo(new TaskProgressHistoryItem_1.TaskProgressHistoryItem(manipulator, data.id, data.progress));
});
};
ValidationController.prototype.updateChildRangeByParent = function (parentId, delta, changedTasks) {
var item = this.viewModel.findItem(parentId);
if (!item || item.children.length === 0)
return;
var children = item.children;
for (var i = 0; i < children.length; i++) {
var childTask = children[i].task;
var newStart = new Date(childTask.start.getTime() + delta);
var newEnd = new Date(childTask.end.getTime() + delta);
changedTasks.push({ id: childTask.internalId, start: childTask.start, end: childTask.end });
if (newStart < childTask.end) {
this.history.addAndRedo(new TaskStartHistoryItem_1.TaskStartHistoryItem(this.modelManipulator, childTask.internalId, newStart));
this.history.addAndRedo(new TaskEndHistoryItem_1.TaskEndHistoryItem(this.modelManipulator, childTask.internalId, newEnd));
}
else {
this.history.addAndRedo(new TaskEndHistoryItem_1.TaskEndHistoryItem(this.modelManipulator, childTask.internalId, newEnd));
this.history.addAndRedo(new TaskStartHistoryItem_1.TaskStartHistoryItem(this.modelManipulator, childTask.internalId, newStart));
}
this.updateChildRangeByParent(childTask.internalId, delta, changedTasks);
}
};
ValidationController.prototype.updateParentsIfRequired = function (childId) {
if (this._parentAutoCalc) {
this.updateParentsRangeByChild(childId);
this.updateOwnerInAutoParentMode();
}
};
ValidationController.prototype.correctParentsOnChildMoving = function (taskId, delta) {
var _this = this;
if (this._parentAutoCalc && delta !== 0) {
this.updateParentsRangeByChild(taskId);
var changedTasks = [];
this.updateChildRangeByParent(taskId, delta, changedTasks);
if (this.isValidateDependenciesRequired)
changedTasks.forEach(function (i) {
_this.moveStartDependTasks(i.id, i.start, true);
_this.moveEndDependTasks(i.id, i.end, true);
});
this.updateOwnerInAutoParentMode();
}
};
ValidationController.prototype.canCreateDependency = function (predecessorId, successorId) {
if (!predecessorId || !successorId || predecessorId === successorId)
return false;
var model = this.viewModel;
if (model.dependencies.items.some(function (d) { return (d.predecessorId === predecessorId && d.successorId === successorId) || (d.predecessorId === successorId && d.successorId === predecessorId); }))
return false;
if (this._parentAutoCalc && this.isValidateDependenciesRequired) {
if (model.checkParent(predecessorId, successorId))
return false;
if (model.checkParent(successorId, predecessorId))
return false;
}
return true;
};
return ValidationController;
}());
exports.ValidationController = ValidationController;
/***/ }),
/* 222 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValidationError = void 0;
var ValidationError = (function () {
function ValidationError(dependencyId, critical) {
if (critical === void 0) { critical = false; }
this.dependencyId = dependencyId;
this.critical = critical;
}
return ValidationError;
}());
exports.ValidationError = ValidationError;
/***/ }),
/* 223 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValidationControllerSettings = void 0;
var common_1 = __webpack_require__(1);
var ValidationControllerSettings = (function () {
function ValidationControllerSettings() {
}
ValidationControllerSettings.parse = function (settings) {
var result = new ValidationControllerSettings();
if (settings) {
if ((0, common_1.isDefined)(settings.getViewModel))
result.getViewModel = settings.getViewModel;
if ((0, common_1.isDefined)(settings.getHistory))
result.getHistory = settings.getHistory;
if ((0, common_1.isDefined)(settings.getModelManipulator))
result.getModelManipulator = settings.getModelManipulator;
if ((0, common_1.isDefined)(settings.getRange))
result.getRange = settings.getRange;
if ((0, common_1.isDefined)(settings.getValidationSettings))
result.getValidationSettings = settings.getValidationSettings;
if ((0, common_1.isDefined)(settings.updateOwnerInAutoParentMode))
result.updateOwnerInAutoParentMode = settings.updateOwnerInAutoParentMode;
if ((0, common_1.isDefined)(settings.getIsValidateDependenciesRequired))
result.getIsValidateDependenciesRequired = settings.getIsValidateDependenciesRequired;
}
return result;
};
return ValidationControllerSettings;
}());
exports.ValidationControllerSettings = ValidationControllerSettings;
/***/ }),
/* 224 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ViewVisualModel = void 0;
var ResourceCollection_1 = __webpack_require__(22);
var TaskCollection_1 = __webpack_require__(225);
var DependencyCollection_1 = __webpack_require__(227);
var ResourceAssignmentCollection_1 = __webpack_require__(228);
var ViewVisualModelItem_1 = __webpack_require__(229);
var ViewVisualModelDependencyInfo_1 = __webpack_require__(230);
var WorkingTimeCalculator_1 = __webpack_require__(231);
var common_1 = __webpack_require__(1);
var Dependency_1 = __webpack_require__(83);
var Resource_1 = __webpack_require__(56);
var ResourceAssignment_1 = __webpack_require__(84);
var ViewVisualModel = (function () {
function ViewVisualModel(owner, tasks, dependencies, resources, assignments, dateRange, workTimeRules) {
this._fLockCount = 0;
this.lockChangesProcessing = false;
this.owner = owner;
this.tasks = new TaskCollection_1.TaskCollection();
this.tasks.importFromObject(tasks);
this.dependencies = new DependencyCollection_1.DependencyCollection();
this.dependencies.importFromObject(dependencies);
this.resources = new ResourceCollection_1.ResourceCollection();
this.resources.importFromObject(resources);
this.assignments = new ResourceAssignmentCollection_1.ResourceAssignmentCollection();
this.assignments.importFromObject(assignments);
this._itemList = new Array();
this._viewItemList = new Array();
this._workTimeCalculator = new WorkingTimeCalculator_1.WorkingTimeCalculator(dateRange, workTimeRules);
this.updateModel(true);
}
Object.defineProperty(ViewVisualModel.prototype, "renderHelper", {
get: function () {
return this.owner.renderHelper;
},
enumerable: false,
configurable: true
});
ViewVisualModel.prototype.updateModel = function (isFirstLoad) {
this._itemList.splice(0, this._itemList.length);
var tasks = this.tasks.items;
for (var i = 0; i < tasks.length; i++) {
var task = tasks[i];
if (task)
this._itemList.push(new ViewVisualModelItem_1.ViewVisualModelItem(task, this.getAssignedResources(task)));
}
this.createHierarchy(isFirstLoad);
this.populateItemsForView();
if (this.owner && this.owner.currentSelectedTaskID)
this.changeTaskSelected(this.owner.currentSelectedTaskID, true);
};
ViewVisualModel.prototype.createHierarchy = function (isFirstLoad) {
var _this = this;
this.root = new ViewVisualModelItem_1.ViewVisualModelItem(null, null);
var list = this._itemList;
var inverted = list.reduce(function (previous, item) {
var _a;
var key = (_a = item.task) === null || _a === void 0 ? void 0 : _a.internalId;
if ((0, common_1.isDefined)(key))
previous[key] = item;
return previous;
}, {});
var recalculateParentRequired = this.requireFirstLoadParentAutoCalc && isFirstLoad;
for (var i = 0; i < list.length; i++) {
var item = list[i];
var parentId = item.task.parentId;
var parentItem = inverted[parentId] || this.root;
item.parent = parentItem;
parentItem.addChild(item);
if (recalculateParentRequired)
this.owner.validationController.recalculateParents(item, function (data) {
if (!(0, common_1.isDefined)(data.id))
return;
var task = _this.tasks.getItemById(data.id);
if ((0, common_1.isDefined)(data.start))
task.start = data.start;
if ((0, common_1.isDefined)(data.end))
task.end = data.end;
if ((0, common_1.isDefined)(data.progress))
task.progress = data.progress;
});
}
if (recalculateParentRequired)
this.owner.dispatcher.notifyParentDataRecalculated(this.getCurrentTaskData());
};
ViewVisualModel.prototype.getCurrentTaskData = function () {
var _this = this;
return this.tasks.items.map(function (t) { return _this.getTaskObjectForDataSource(t); });
};
ViewVisualModel.prototype.getTaskObjectForDataSource = function (task) {
var parentTask = task.parentId && this.tasks.getItemById(task.parentId);
var rootId = this.getRootTaskId();
var parentId = rootId && task.parentId === rootId ? task.parentId : parentTask === null || parentTask === void 0 ? void 0 : parentTask.id;
var taskObject = {
id: task.id,
start: task.start,
end: task.end,
duration: task.duration,
description: task.description,
parentId: parentId,
progress: task.progress,
color: task.color,
taskType: task.taskType,
title: task.title,
customFields: task.customFields,
expanded: task.expanded
};
return taskObject;
};
ViewVisualModel.prototype.getDependencyObjectForDataSource = function (key) {
var dependency = key instanceof Dependency_1.Dependency ? key : this.getItemByPublicId("dependency", key);
if (dependency) {
var predecessorId = this.convertInternalToPublicKey("task", dependency.predecessorId);
var successorId = this.convertInternalToPublicKey("task", dependency.successorId);
return {
id: dependency.id,
predecessorId: (0, common_1.isDefined)(predecessorId) ? predecessorId : dependency.predecessorId,
successorId: (0, common_1.isDefined)(successorId) ? successorId : dependency.successorId,
type: dependency.type
};
}
return null;
};
ViewVisualModel.prototype.getResourceObjectForDataSource = function (key) {
var resource = key instanceof Resource_1.Resource ? key : this.getItemByPublicId("resource", key);
if (resource)
return {
id: resource.id,
text: resource.text,
color: resource.color
};
return null;
};
ViewVisualModel.prototype.getResourceAssignmentObjectForDataSource = function (key) {
var assignment = key instanceof ResourceAssignment_1.ResourceAssignment ? key : this.getItemByPublicId("assignment", key);
if (assignment) {
var taskId = this.convertInternalToPublicKey("task", assignment.taskId);
var resourceId = this.convertInternalToPublicKey("resource", assignment.resourceId);
return {
id: assignment.id,
taskId: (0, common_1.isDefined)(taskId) ? taskId : assignment.taskId,
resourceId: (0, common_1.isDefined)(resourceId) ? resourceId : assignment.resourceId
};
}
return null;
};
ViewVisualModel.prototype.populateItemsForView = function () {
this._viewItemList.splice(0, this._viewItemList.length);
this.populateVisibleItems(this.root);
this.updateVisibleItemDependencies();
};
ViewVisualModel.prototype.populateVisibleItems = function (item) {
var _this = this;
var isRoot = item === this.root;
if (!item || (!item.task && !isRoot))
return;
if (!isRoot) {
this._viewItemList.push(item);
item.visibleIndex = this._viewItemList.length - 1;
}
if (item.getExpanded() || item === this.root)
item.children.forEach(function (n) { return _this.populateVisibleItems(n); });
};
ViewVisualModel.prototype.updateVisibleItemDependencies = function () {
var list = this._viewItemList;
for (var i = 0; i < list.length; i++) {
var item = list[i];
var visibleDependencies = this.getTasVisibleDependencies(item.task);
item.setDependencies(visibleDependencies);
}
};
ViewVisualModel.prototype.getAssignedResources = function (task) {
var _this = this;
var res = new ResourceCollection_1.ResourceCollection();
var assignments = this.assignments.items.filter(function (value) { return value.taskId == task.internalId; });
assignments.forEach(function (assignment) { res.add(_this.resources.getItemById(assignment.resourceId)); });
return res;
};
ViewVisualModel.prototype.getTasVisibleDependencies = function (task) {
var res = new Array();
var id = task.internalId;
var dependencies = this.dependencies.items.filter(function (value) { return value.successorId == id; });
for (var i = 0; i < dependencies.length; i++) {
var dependency = dependencies[i];
var item = this.findItem(dependency.predecessorId);
if (item && item.getVisible())
res.push(new ViewVisualModelDependencyInfo_1.ViewVisualModelDependencyInfo(dependency.internalId, item, dependency.type));
}
return res;
};
ViewVisualModel.prototype.changeTaskExpanded = function (id, expanded) {
var task = this.tasks.getItemById(String(id));
if (task) {
task.expanded = expanded;
this.changed();
}
};
ViewVisualModel.prototype.changeTaskVisibility = function (id, visible) {
var item = this.findItem(id);
if (item) {
item.visible = visible;
this.changed();
}
};
ViewVisualModel.prototype.changeTaskSelected = function (id, selected) {
var item = this._itemList.filter(function (value) { return value.task && value.task.internalId === id; })[0];
if (item) {
item.selected = selected;
var viewItem = this.findItem(id);
var taskIndex = viewItem && viewItem.visibleIndex;
if (taskIndex > -1)
this.renderHelper.recreateTaskElement(taskIndex);
}
};
ViewVisualModel.prototype.beginUpdate = function () {
this._fLockCount++;
};
ViewVisualModel.prototype.endUpdate = function () {
this._fLockCount--;
if (this._fLockCount == 0)
this.changed();
};
ViewVisualModel.prototype.compareTaskOrder = function (taskModel) {
var newTasks = new TaskCollection_1.TaskCollection();
newTasks.importFromObject(taskModel);
var newItems = newTasks.items;
var oldItems = this.tasks.items;
if (newItems.length !== oldItems.length)
return false;
for (var i = 0; i < newItems.length; i++) {
var newTask = newItems[i];
var oldTask = oldItems[i];
if (newTask.id !== oldTask.id)
return false;
}
return true;
};
ViewVisualModel.prototype.refreshTaskDataIfRequires = function (tasks) {
var changed = !this.lockChangesProcessing && !this.compareTaskOrder(tasks);
if (changed) {
var hash = this.saveTaskInternalIds();
this.tasks.importFromObject(tasks);
this.restoreTaskInternalIds(hash);
this.updateModel();
}
return changed;
};
ViewVisualModel.prototype.saveTaskInternalIds = function () {
var hash = {};
this.tasks.items.map(function (t) { return hash[t.id] = t.internalId; });
return hash;
};
ViewVisualModel.prototype.restoreTaskInternalIds = function (hash) {
for (var id in hash) {
if (!Object.prototype.hasOwnProperty.call(hash, id))
continue;
var task = this.tasks.getItemByPublicId(id);
if (task)
task.internalId = hash[id];
}
};
ViewVisualModel.prototype.getTaskTreeLine = function (taskId) {
var result = [];
var item = this.findItem(taskId);
if (item) {
result.push(taskId);
item = item.parent;
while (item === null || item === void 0 ? void 0 : item.task) {
result.push(item === null || item === void 0 ? void 0 : item.task.internalId);
item = item.parent;
}
}
return result;
};
ViewVisualModel.prototype.checkParent = function (childId, parentId) {
return this.getTaskTreeLine(childId).indexOf(parentId) > -1;
};
ViewVisualModel.prototype.getTasksExpandedState = function () {
var items = this.tasks.items;
var state = {};
items.forEach(function (t) { return state[t.id] = t.expanded; });
return state;
};
ViewVisualModel.prototype.applyTasksExpandedState = function (state) {
if (!state)
return;
this.beginUpdate();
for (var key in state)
if (Object.prototype.hasOwnProperty.call(state, key))
this.changeTaskExpanded(key, state[key]);
this.endUpdate();
};
ViewVisualModel.prototype.changed = function () {
if (this._fLockCount !== 0)
return;
this.populateItemsForView();
if (this.owner && this.owner.onVisualModelChanged)
this.owner.onVisualModelChanged();
};
ViewVisualModel.prototype.findItem = function (taskId) {
return this._viewItemList.filter(function (value) { return value.task && value.task.internalId === taskId; })[0];
};
Object.defineProperty(ViewVisualModel.prototype, "items", {
get: function () { return this._viewItemList; },
enumerable: false,
configurable: true
});
Object.defineProperty(ViewVisualModel.prototype, "itemCount", {
get: function () { return this.items.length; },
enumerable: false,
configurable: true
});
ViewVisualModel.prototype.getTaskVisibility = function (id) {
var item = this.findItem(id);
return !!item && item.getVisible();
};
ViewVisualModel.prototype.getTaskSelected = function (id) {
var item = this.findItem(id);
return !!item && item.selected;
};
Object.defineProperty(ViewVisualModel.prototype, "noWorkingIntervals", {
get: function () { return this._workTimeCalculator.noWorkingIntervals; },
enumerable: false,
configurable: true
});
ViewVisualModel.prototype.updateRange = function (range) { this._workTimeCalculator.updateRange(range); };
ViewVisualModel.prototype.taskHasChildrenByIndex = function (index) { return this._viewItemList[index].children.length > 0; };
ViewVisualModel.prototype.taskHasChildren = function (id) {
var item = this.findItem(id);
return item && item.children.length > 0;
};
Object.defineProperty(ViewVisualModel.prototype, "parentAutoCalc", {
get: function () {
var settings = this.owner && this.owner.settings;
return settings && settings.validation && settings.validation.autoUpdateParentTasks;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ViewVisualModel.prototype, "enablePredecessorGap", {
get: function () {
var settings = this.owner && this.owner.settings;
return settings && settings.validation && settings.validation.enablePredecessorGap;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ViewVisualModel.prototype, "requireFirstLoadParentAutoCalc", {
get: function () { return this.parentAutoCalc && this.owner.requireFirstLoadParentAutoCalc(); },
enumerable: false,
configurable: true
});
ViewVisualModel.prototype.isTaskToCalculateByChildren = function (id) { return this.parentAutoCalc && this.taskHasChildren(id); };
ViewVisualModel.prototype.hasTasks = function () { return this.tasks.length > 0; };
ViewVisualModel.prototype.getDataUpdateErrorCallback = function () {
return this.owner.getDataUpdateErrorCallback && this.owner.getDataUpdateErrorCallback();
};
ViewVisualModel.prototype.convertPublicToInternalKey = function (dataType, publicKey) {
var item = this.getItemByPublicId(dataType, publicKey);
return item && item.internalId;
};
ViewVisualModel.prototype.convertInternalToPublicKey = function (dataType, internalId) {
var item = this.getItemByInternalId(dataType, internalId);
return item && item.id;
};
ViewVisualModel.prototype.getItemByPublicId = function (dataType, publicKey) {
var strKey = publicKey.toString();
switch (dataType) {
case "task":
return this.tasks.getItemByPublicId(strKey);
case "dependency":
return this.dependencies.getItemByPublicId(strKey);
case "resource":
return this.resources.getItemByPublicId(strKey);
case "assignment":
return this.assignments.getItemByPublicId(strKey);
}
return null;
};
ViewVisualModel.prototype.getItemByInternalId = function (dataType, internalId) {
switch (dataType) {
case "task":
return this.tasks.getItemById(internalId);
case "dependency":
return this.dependencies.getItemById(internalId);
case "resource":
return this.resources.getItemById(internalId);
case "assignment":
return this.assignments.getItemById(internalId);
}
return null;
};
ViewVisualModel.prototype.findAssignment = function (resourceKey, taskKey) {
var resourceInternalKey = this.convertPublicToInternalKey("resource", resourceKey);
var taskInternalKey = this.convertPublicToInternalKey("task", taskKey);
return this.assignments.items.filter(function (val) { return val.resourceId === resourceInternalKey && val.taskId === taskInternalKey; })[0];
};
ViewVisualModel.prototype.findAllTaskAssignments = function (taskInternalKey) {
return this.assignments.items.filter(function (val) { return val.taskId === taskInternalKey; });
};
ViewVisualModel.prototype.getAllVisibleTaskIndices = function (start, end) {
var _a;
var result = [];
start !== null && start !== void 0 ? start : (start = 0);
end !== null && end !== void 0 ? end : (end = this._viewItemList.length - 1);
for (var i = start; i <= end; i++) {
var item = this._viewItemList[i];
if (item.getVisible() && ((_a = item.task) === null || _a === void 0 ? void 0 : _a.isValid))
result.push(i);
}
return result;
};
ViewVisualModel.prototype.getVisibleTasks = function () {
var _this = this;
return this.tasks.items.filter(function (t) { return t && _this.getTaskVisibility(t.internalId) && t.isValid(); });
};
ViewVisualModel.prototype.getVisibleDependencies = function () {
var visibleTasksKeys = this.getVisibleTasks().map(function (t) { return t.internalId; });
return this.dependencies.items.filter(function (d) { return d && visibleTasksKeys.indexOf(d.successorId) > -1 && visibleTasksKeys.indexOf(d.predecessorId) > -1; });
};
ViewVisualModel.prototype.getVisibleResourceAssignments = function () {
var visibleTasksKeys = this.getVisibleTasks().map(function (t) { return t.internalId; });
return this.assignments.items.filter(function (a) { return a && visibleTasksKeys.indexOf(a.taskId) > -1; });
};
ViewVisualModel.prototype.getVisibleResources = function () {
var visibleResources = [];
var visibleAssignments = this.getVisibleResourceAssignments();
for (var i = 0; i < visibleAssignments.length; i++) {
var resource = this.getItemByInternalId("resource", visibleAssignments[i].resourceId);
if (resource && visibleResources.indexOf(resource) === -1)
visibleResources.push(resource);
}
return visibleResources;
};
ViewVisualModel.prototype.getRootTaskId = function () {
var _a;
(_a = this.rootTaskId) !== null && _a !== void 0 ? _a : (this.rootTaskId = this.calculateRootTaskId());
return this.rootTaskId;
};
ViewVisualModel.prototype.calculateRootTaskId = function () {
var item = this.items[0];
if (!item)
return null;
while (item.parent && item.task)
item = item.parent;
return item.children[0].task.parentId;
};
return ViewVisualModel;
}());
exports.ViewVisualModel = ViewVisualModel;
/***/ }),
/* 225 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TaskCollection = void 0;
var tslib_1 = __webpack_require__(0);
var Task_1 = __webpack_require__(226);
var CollectionBase_1 = __webpack_require__(23);
var TaskCollection = (function (_super) {
(0, tslib_1.__extends)(TaskCollection, _super);
function TaskCollection() {
return _super !== null && _super.apply(this, arguments) || this;
}
TaskCollection.prototype.createItem = function () { return new Task_1.Task(); };
return TaskCollection;
}(CollectionBase_1.CollectionBase));
exports.TaskCollection = TaskCollection;
/***/ }),
/* 226 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Task = void 0;
var tslib_1 = __webpack_require__(0);
var common_1 = __webpack_require__(1);
var DataObject_1 = __webpack_require__(20);
var Task = (function (_super) {
(0, tslib_1.__extends)(Task, _super);
function Task() {
var _this = _super.call(this) || this;
_this.start = null;
_this.end = null;
_this.duration = null;
_this.description = "";
_this.parentId = null;
_this.title = "";
_this.owner = null;
_this.progress = 0;
_this.taskType = null;
_this.customFields = {};
_this.expanded = true;
_this.color = "";
return _this;
}
Task.prototype.assignFromObject = function (sourceObj) {
if ((0, common_1.isDefined)(sourceObj)) {
_super.prototype.assignFromObject.call(this, sourceObj);
this.owner = sourceObj.owner;
this.parentId = (0, common_1.isDefined)(sourceObj.parentId) ? String(sourceObj.parentId) : null;
this.description = sourceObj.description;
this.title = sourceObj.title;
this.start = typeof sourceObj.start === "string" ? new Date(sourceObj.start) : sourceObj.start || new Date(0);
this.end = typeof sourceObj.end === "string" ? new Date(sourceObj.end) : sourceObj.end || new Date(0);
this.duration = sourceObj.duration;
this.progress = sourceObj.progress;
this.taskType = sourceObj.taskType;
if ((0, common_1.isDefined)(sourceObj.expanded))
this.expanded = !!sourceObj.expanded;
if ((0, common_1.isDefined)(sourceObj.color))
this.color = sourceObj.color;
this.assignCustomFields(sourceObj.customFields);
}
};
Task.prototype.assignCustomFields = function (sourceObj) {
if (!sourceObj)
return;
for (var property in sourceObj) {
if (!Object.prototype.hasOwnProperty.call(sourceObj, property))
continue;
this.customFields[property] = sourceObj[property];
}
};
Task.prototype.isMilestone = function () {
return this.start.getTime() === this.end.getTime();
};
Task.prototype.getDuration = function () {
return this.end.getTime() - this.start.getTime();
};
Task.prototype.isValid = function () {
return !!this.start.getTime() && !!this.end.getTime();
};
return Task;
}(DataObject_1.DataObject));
exports.Task = Task;
/***/ }),
/* 227 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DependencyCollection = void 0;
var tslib_1 = __webpack_require__(0);
var CollectionBase_1 = __webpack_require__(23);
var Dependency_1 = __webpack_require__(83);
var DependencyCollection = (function (_super) {
(0, tslib_1.__extends)(DependencyCollection, _super);
function DependencyCollection() {
return _super !== null && _super.apply(this, arguments) || this;
}
DependencyCollection.prototype.createItem = function () { return new Dependency_1.Dependency(); };
return DependencyCollection;
}(CollectionBase_1.CollectionBase));
exports.DependencyCollection = DependencyCollection;
/***/ }),
/* 228 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResourceAssignmentCollection = void 0;
var tslib_1 = __webpack_require__(0);
var CollectionBase_1 = __webpack_require__(23);
var ResourceAssignment_1 = __webpack_require__(84);
var ResourceAssignmentCollection = (function (_super) {
(0, tslib_1.__extends)(ResourceAssignmentCollection, _super);
function ResourceAssignmentCollection() {
return _super !== null && _super.apply(this, arguments) || this;
}
ResourceAssignmentCollection.prototype.createItem = function () { return new ResourceAssignment_1.ResourceAssignment(); };
return ResourceAssignmentCollection;
}(CollectionBase_1.CollectionBase));
exports.ResourceAssignmentCollection = ResourceAssignmentCollection;
/***/ }),
/* 229 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ViewVisualModelItem = void 0;
var common_1 = __webpack_require__(1);
var size_1 = __webpack_require__(11);
var ViewVisualModelItem = (function () {
function ViewVisualModelItem(task, resources) {
this.dependencies = new Array();
this.parent = null;
this.visible = true;
this.selected = false;
this.visibleIndex = -1;
this.task = task;
this.resources = resources;
this.children = new Array();
this.isCustom = false;
this.size = new size_1.Size(0, 0);
}
Object.defineProperty(ViewVisualModelItem.prototype, "resourceText", {
get: function () {
var text = "";
this.resources.items.forEach(function (r) { return text += r.text + " "; });
return text;
},
enumerable: false,
configurable: true
});
ViewVisualModelItem.prototype.addChild = function (child) {
if ((0, common_1.isDefined)(child) && this.children.indexOf(child) < 0)
this.children.push(child);
};
ViewVisualModelItem.prototype.removeChild = function (child) {
var index = this.children.indexOf(child);
if (index > -1)
this.children.splice(index, 1);
};
ViewVisualModelItem.prototype.getExpanded = function () {
return !!this.task && this.task.expanded;
};
ViewVisualModelItem.prototype.getVisible = function () {
if (!this.visible)
return false;
var parentItem = this.parent;
while (parentItem) {
if (!parentItem.visible)
return false;
parentItem = parentItem.parent;
}
return true;
};
ViewVisualModelItem.prototype.changeVisibility = function (visible) {
this.visible = visible;
};
ViewVisualModelItem.prototype.changeSelection = function (selected) {
this.selected = selected;
};
ViewVisualModelItem.prototype.setDependencies = function (dependencies) {
if (dependencies)
this.dependencies = dependencies.slice();
};
return ViewVisualModelItem;
}());
exports.ViewVisualModelItem = ViewVisualModelItem;
/***/ }),
/* 230 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ViewVisualModelDependencyInfo = void 0;
var ViewVisualModelDependencyInfo = (function () {
function ViewVisualModelDependencyInfo(id, predecessor, type) {
this.id = id;
this.predecessor = predecessor;
this.type = type;
}
return ViewVisualModelDependencyInfo;
}());
exports.ViewVisualModelDependencyInfo = ViewVisualModelDependencyInfo;
/***/ }),
/* 231 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkingTimeCalculator = void 0;
var GanttWorkingDayRuleCollection_1 = __webpack_require__(232);
var DayWorkingTimeInfo_1 = __webpack_require__(240);
var DateTimeUtils_1 = __webpack_require__(7);
var WorkingTimeCalculator = (function () {
function WorkingTimeCalculator(range, rules) {
this._workingRules = new GanttWorkingDayRuleCollection_1.WorkingDayRuleCollection();
this._workDayList = new Array();
this._calculationRange = range;
this._workingRules.importFromObject(rules);
}
WorkingTimeCalculator.prototype.calculateWorkDayList = function () {
if (!this._calculationRange)
return;
this.clearList();
var rules = this._workingRules.items;
for (var i = 0; i < rules.length; i++)
this.processRule(rules[i]);
this.sortList();
};
WorkingTimeCalculator.prototype.processRule = function (rule) {
var points = rule.recurrence.calculatePoints(this._calculationRange.start, this._calculationRange.end);
var _loop_1 = function (i) {
var point = points[i];
var dayNum = DateTimeUtils_1.DateTimeUtils.getDayNumber(point);
var dayInfo = this_1._workDayList.filter(function (i) { return i.dayNumber == dayNum; })[0];
if (dayInfo) {
dayInfo.isWorkDay = dayInfo.isWorkDay && rule.isWorkDay;
dayInfo.addWorkingIntervals(rule.workTimeRanges);
}
else
this_1._workDayList.push(new DayWorkingTimeInfo_1.DayWorkingTimeInfo(dayNum, rule.isWorkDay, rule.workTimeRanges));
};
var this_1 = this;
for (var i = 0; i < points.length; i++) {
_loop_1(i);
}
};
WorkingTimeCalculator.prototype.sortList = function () {
this._workDayList.sort(function (d1, d2) { return d1.dayNumber - d2.dayNumber; });
};
WorkingTimeCalculator.prototype.clearList = function () {
this._workDayList.splice(0, this._workDayList.length);
};
WorkingTimeCalculator.prototype.calculateNoWorkTimeIntervals = function () {
var _this = this;
var res = new Array();
if (this._workDayList.length == 0)
this.calculateWorkDayList();
this._workDayList.forEach(function (d) { return res = res.concat(_this.getNoWorkTimeRangesFromDay(d)); });
return this.concatJointedRanges(res);
};
WorkingTimeCalculator.prototype.concatJointedRanges = function (list) {
var res = new Array();
for (var i = 0; i < list.length; i++) {
var interval = list[i];
var needExpandPrevInterval = res.length > 0 && DateTimeUtils_1.DateTimeUtils.compareDates(res[res.length - 1].end, interval.start) < 2;
if (needExpandPrevInterval)
res[res.length - 1].end = interval.end;
else
res.push(interval);
}
return res;
};
WorkingTimeCalculator.prototype.getNoWorkTimeRangesFromDay = function (day) {
return day.noWorkingIntervals.map(function (i) { return DateTimeUtils_1.DateTimeUtils.convertTimeRangeToDateRange(i, day.dayNumber); });
};
Object.defineProperty(WorkingTimeCalculator.prototype, "noWorkingIntervals", {
get: function () {
if (!this._noWorkingIntervals)
this._noWorkingIntervals = this.calculateNoWorkTimeIntervals();
return this._noWorkingIntervals.slice();
},
enumerable: false,
configurable: true
});
WorkingTimeCalculator.prototype.updateRange = function (range) {
this._calculationRange = range;
this.invalidate();
};
WorkingTimeCalculator.prototype.invalidate = function () {
this._noWorkingIntervals = null;
this.clearList();
};
return WorkingTimeCalculator;
}());
exports.WorkingTimeCalculator = WorkingTimeCalculator;
/***/ }),
/* 232 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkingDayRuleCollection = void 0;
var tslib_1 = __webpack_require__(0);
var CollectionBase_1 = __webpack_require__(23);
var WorkingTimeRule_1 = __webpack_require__(233);
var WorkingDayRuleCollection = (function (_super) {
(0, tslib_1.__extends)(WorkingDayRuleCollection, _super);
function WorkingDayRuleCollection() {
return _super !== null && _super.apply(this, arguments) || this;
}
WorkingDayRuleCollection.prototype.createItem = function () { return new WorkingTimeRule_1.WorkingTimeRule(); };
return WorkingDayRuleCollection;
}(CollectionBase_1.CollectionBase));
exports.WorkingDayRuleCollection = WorkingDayRuleCollection;
/***/ }),
/* 233 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkingTimeRule = void 0;
var tslib_1 = __webpack_require__(0);
var DataObject_1 = __webpack_require__(20);
var common_1 = __webpack_require__(1);
var DateTimeUtils_1 = __webpack_require__(7);
var RecurrenceFactory_1 = __webpack_require__(85);
var Daily_1 = __webpack_require__(86);
var WorkingTimeRule = (function (_super) {
(0, tslib_1.__extends)(WorkingTimeRule, _super);
function WorkingTimeRule(recurrence, isWorkDay, workTimeRanges) {
if (recurrence === void 0) { recurrence = null; }
if (isWorkDay === void 0) { isWorkDay = true; }
if (workTimeRanges === void 0) { workTimeRanges = null; }
var _this = _super.call(this) || this;
_this.isWorkDay = true;
_this.workTimeRanges = new Array();
_this.recurrence = recurrence;
_this.isWorkDay = isWorkDay;
if (workTimeRanges)
_this.workTimeRanges.concat(workTimeRanges);
return _this;
}
WorkingTimeRule.prototype.assignFromObject = function (sourceObj) {
if ((0, common_1.isDefined)(sourceObj)) {
_super.prototype.assignFromObject.call(this, sourceObj);
this.recurrence = RecurrenceFactory_1.RecurrenceFactory.createRecurrenceByType(sourceObj.recurrenceType) || new Daily_1.Daily();
if ((0, common_1.isDefined)(sourceObj.recurrence))
this.recurrence.assignFromObject(sourceObj.recurrence);
if ((0, common_1.isDefined)(sourceObj.isWorkDay))
this.isWorkDay = !!sourceObj.isWorkDay;
var ranges = DateTimeUtils_1.DateTimeUtils.convertToTimeRanges(sourceObj.workTimeRanges);
if (ranges)
this.workTimeRanges = ranges;
}
};
return WorkingTimeRule;
}(DataObject_1.DataObject));
exports.WorkingTimeRule = WorkingTimeRule;
/***/ }),
/* 234 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DayOfWeek = void 0;
var DayOfWeek;
(function (DayOfWeek) {
DayOfWeek[DayOfWeek["Sunday"] = 0] = "Sunday";
DayOfWeek[DayOfWeek["Monday"] = 1] = "Monday";
DayOfWeek[DayOfWeek["Tuesday"] = 2] = "Tuesday";
DayOfWeek[DayOfWeek["Wednesday"] = 3] = "Wednesday";
DayOfWeek[DayOfWeek["Thursday"] = 4] = "Thursday";
DayOfWeek[DayOfWeek["Friday"] = 5] = "Friday";
DayOfWeek[DayOfWeek["Saturday"] = 6] = "Saturday";
})(DayOfWeek = exports.DayOfWeek || (exports.DayOfWeek = {}));
/***/ }),
/* 235 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Month = void 0;
var Month;
(function (Month) {
Month[Month["January"] = 0] = "January";
Month[Month["February"] = 1] = "February";
Month[Month["March"] = 2] = "March";
Month[Month["April"] = 3] = "April";
Month[Month["May"] = 4] = "May";
Month[Month["June"] = 5] = "June";
Month[Month["July"] = 6] = "July";
Month[Month["August"] = 7] = "August";
Month[Month["September"] = 8] = "September";
Month[Month["October"] = 9] = "October";
Month[Month["November"] = 10] = "November";
Month[Month["December"] = 11] = "December";
})(Month = exports.Month || (exports.Month = {}));
/***/ }),
/* 236 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Weekly = void 0;
var tslib_1 = __webpack_require__(0);
var RecurrenceBase_1 = __webpack_require__(41);
var DateTimeUtils_1 = __webpack_require__(7);
var Weekly = (function (_super) {
(0, tslib_1.__extends)(Weekly, _super);
function Weekly() {
return _super !== null && _super.apply(this, arguments) || this;
}
Weekly.prototype.checkDate = function (date) {
return DateTimeUtils_1.DateTimeUtils.checkDayOfWeek(this.dayOfWeekInternal, date);
};
Weekly.prototype.checkInterval = function (date) {
return DateTimeUtils_1.DateTimeUtils.getWeeksBetween(this.start, date) % this.interval == 0;
};
Weekly.prototype.calculatePointByInterval = function (date) {
var weeksFromStart = DateTimeUtils_1.DateTimeUtils.getWeeksBetween(this.start, date);
var intervalCount = Math.floor(weeksFromStart / this.interval);
var remainder = weeksFromStart % this.interval;
var isPointOnNewWeek = remainder > 0 || date.getDay() >= this.dayOfWeekInternal;
if (isPointOnNewWeek)
intervalCount++;
var weeksToAdd = intervalCount * this.interval;
return this.calcNextPointWithWeekCount(this.start, weeksToAdd);
};
Weekly.prototype.calculateNearestPoint = function (date) {
var diff = this.dayOfWeekInternal - date.getDay();
if (diff > 0)
return DateTimeUtils_1.DateTimeUtils.addDays(new Date(date), diff);
return this.calcNextPointWithWeekCount(date, 1);
};
Weekly.prototype.calcNextPointWithWeekCount = function (date, weekCount) {
if (weekCount === void 0) { weekCount = 1; }
var daysToAdd = weekCount * 7 + this.dayOfWeekInternal - date.getDay();
return DateTimeUtils_1.DateTimeUtils.addDays(new Date(date), daysToAdd);
};
Object.defineProperty(Weekly.prototype, "dayOfWeek", {
get: function () { return this.dayOfWeekInternal; },
set: function (value) { this.dayOfWeekInternal = value; },
enumerable: false,
configurable: true
});
return Weekly;
}(RecurrenceBase_1.RecurrenceBase));
exports.Weekly = Weekly;
/***/ }),
/* 237 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Monthly = void 0;
var tslib_1 = __webpack_require__(0);
var RecurrenceBase_1 = __webpack_require__(41);
var DateTimeUtils_1 = __webpack_require__(7);
var MonthInfo_1 = __webpack_require__(238);
var Monthly = (function (_super) {
(0, tslib_1.__extends)(Monthly, _super);
function Monthly() {
return _super !== null && _super.apply(this, arguments) || this;
}
Monthly.prototype.checkDate = function (date) {
if (this._calculateByDayOfWeek)
return DateTimeUtils_1.DateTimeUtils.checkDayOfWeekOccurrenceInMonth(date, this.dayOfWeekInternal, this.dayOfWeekOccurrenceInternal);
return DateTimeUtils_1.DateTimeUtils.checkDayOfMonth(this.dayInternal, date);
};
Monthly.prototype.checkInterval = function (date) {
return DateTimeUtils_1.DateTimeUtils.getMonthsDifference(this.start, date) % this.interval == 0;
};
Monthly.prototype.calculatePointByInterval = function (date) {
var start = this.start;
var monthFromStart = DateTimeUtils_1.DateTimeUtils.getMonthsDifference(start, date);
var monthToAdd = Math.floor(monthFromStart / this.interval) * this.interval;
var info = new MonthInfo_1.MonthInfo(start.getMonth(), start.getFullYear());
info.addMonths(monthToAdd);
var point = this.getSpecDayInMonth(info.year, info.month);
if (DateTimeUtils_1.DateTimeUtils.compareDates(point, date) >= 0) {
info.addMonths(this.interval);
point = this.getSpecDayInMonth(info.year, info.month);
}
return point;
};
Monthly.prototype.calculateNearestPoint = function (date) {
var month = date.getMonth();
var year = date.getFullYear();
var point = this.getSpecDayInMonth(year, month);
if (DateTimeUtils_1.DateTimeUtils.compareDates(point, date) >= 0) {
var info = new MonthInfo_1.MonthInfo(month, year);
info.addMonths(1);
point = this.getSpecDayInMonth(info.year, info.month);
}
return point;
};
Object.defineProperty(Monthly.prototype, "day", {
get: function () { return this.dayInternal; },
set: function (value) { this.dayInternal = value; },
enumerable: false,
configurable: true
});
Object.defineProperty(Monthly.prototype, "dayOfWeek", {
get: function () { return this.dayOfWeekInternal; },
set: function (value) { this.dayOfWeekInternal = value; },
enumerable: false,
configurable: true
});
Object.defineProperty(Monthly.prototype, "dayOfWeekOccurrence", {
get: function () { return this.dayOfWeekOccurrenceInternal; },
set: function (value) { this.dayOfWeekOccurrenceInternal = value; },
enumerable: false,
configurable: true
});
Object.defineProperty(Monthly.prototype, "calculateByDayOfWeek", {
get: function () { return this._calculateByDayOfWeek; },
set: function (value) { this._calculateByDayOfWeek = value; },
enumerable: false,
configurable: true
});
return Monthly;
}(RecurrenceBase_1.RecurrenceBase));
exports.Monthly = Monthly;
/***/ }),
/* 238 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MonthInfo = void 0;
var DateTimeUtils_1 = __webpack_require__(7);
var MonthInfo = (function () {
function MonthInfo(month, year) {
this.month = month;
this.year = year;
}
MonthInfo.prototype.addMonths = function (months) {
var nextMonth = DateTimeUtils_1.DateTimeUtils.getNextMonth(this.month, months);
var yearInc = Math.floor(months / 12);
if (nextMonth < this.month)
++yearInc;
this.month = nextMonth;
this.year += yearInc;
};
return MonthInfo;
}());
exports.MonthInfo = MonthInfo;
/***/ }),
/* 239 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Yearly = void 0;
var tslib_1 = __webpack_require__(0);
var RecurrenceBase_1 = __webpack_require__(41);
var DateTimeUtils_1 = __webpack_require__(7);
var Yearly = (function (_super) {
(0, tslib_1.__extends)(Yearly, _super);
function Yearly() {
return _super !== null && _super.apply(this, arguments) || this;
}
Yearly.prototype.checkDate = function (date) {
if (!DateTimeUtils_1.DateTimeUtils.checkMonth(this.month, date))
return false;
if (this._calculateByDayOfWeek)
return DateTimeUtils_1.DateTimeUtils.checkDayOfWeekOccurrenceInMonth(date, this.dayOfWeekInternal, this.dayOfWeekOccurrenceInternal);
return DateTimeUtils_1.DateTimeUtils.checkDayOfMonth(this.dayInternal, date);
};
Yearly.prototype.checkInterval = function (date) {
return DateTimeUtils_1.DateTimeUtils.getYearsDifference(this.start, date) % this.interval == 0;
};
Yearly.prototype.calculatePointByInterval = function (date) {
var yearFromStart = DateTimeUtils_1.DateTimeUtils.getYearsDifference(this.start, date);
var yearInc = Math.floor(yearFromStart / this.interval) * this.interval;
var newYear = this.start.getFullYear() + yearInc;
var point = this.getSpecDayInMonth(newYear, this.monthInternal);
if (DateTimeUtils_1.DateTimeUtils.compareDates(point, date) >= 0) {
newYear += this.interval;
point = this.getSpecDayInMonth(newYear, this.monthInternal);
}
return point;
};
Yearly.prototype.calculateNearestPoint = function (date) {
var year = date.getFullYear();
var point = this.getSpecDayInMonth(year, this.monthInternal);
if (DateTimeUtils_1.DateTimeUtils.compareDates(point, date) >= 0)
point = this.getSpecDayInMonth(++year, this.monthInternal);
return point;
};
Object.defineProperty(Yearly.prototype, "month", {
get: function () { return this.monthInternal; },
set: function (value) { this.monthInternal = value; },
enumerable: false,
configurable: true
});
Object.defineProperty(Yearly.prototype, "day", {
get: function () { return this.dayInternal; },
set: function (value) { this.dayInternal = value; },
enumerable: false,
configurable: true
});
Object.defineProperty(Yearly.prototype, "dayOfWeek", {
get: function () { return this.dayOfWeekInternal; },
set: function (value) { this.dayOfWeekInternal = value; },
enumerable: false,
configurable: true
});
Object.defineProperty(Yearly.prototype, "dayOfWeekOccurrence", {
get: function () { return this.dayOfWeekOccurrenceInternal; },
set: function (value) { this.dayOfWeekOccurrenceInternal = value; },
enumerable: false,
configurable: true
});
Object.defineProperty(Yearly.prototype, "calculateByDayOfWeek", {
get: function () { return this._calculateByDayOfWeek; },
set: function (value) { this._calculateByDayOfWeek = value; },
enumerable: false,
configurable: true
});
return Yearly;
}(RecurrenceBase_1.RecurrenceBase));
exports.Yearly = Yearly;
/***/ }),
/* 240 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DayWorkingTimeInfo = void 0;
var TimeRange_1 = __webpack_require__(67);
var DateTimeUtils_1 = __webpack_require__(7);
var Time_1 = __webpack_require__(66);
var DayWorkingTimeInfo = (function () {
function DayWorkingTimeInfo(dayNumber, isWorkDay, intervals) {
if (dayNumber === void 0) { dayNumber = 0; }
if (isWorkDay === void 0) { isWorkDay = true; }
if (intervals === void 0) { intervals = null; }
this._workingIntervals = new Array();
this.dayNumber = dayNumber;
this.isWorkDay = isWorkDay;
this.addWorkingIntervals(intervals);
}
DayWorkingTimeInfo.prototype.addWorkingIntervals = function (intervals) {
if (!intervals)
return;
this._workingIntervals = this._workingIntervals.concat(intervals.filter(function (r) { return !!r; }));
this.rearrangeWorkingIntervals();
};
DayWorkingTimeInfo.prototype.rearrangeWorkingIntervals = function () {
for (var i = 0; i < this._workingIntervals.length; i++)
this.concatWithIntersectedRanges(this._workingIntervals[i]);
this.sortIntervals();
};
DayWorkingTimeInfo.prototype.concatWithIntersectedRanges = function (range) {
var _this = this;
var intersectedRanges = this.getIntersectedIntervals(range);
intersectedRanges.forEach(function (r) {
range.concatWith(r);
_this.removeInterval(r);
});
};
DayWorkingTimeInfo.prototype.getIntersectedIntervals = function (range) {
return this._workingIntervals.filter(function (r) { return r.hasIntersect(range) && r !== range; });
};
DayWorkingTimeInfo.prototype.sortIntervals = function () {
this._workingIntervals.sort(function (r1, r2) { return DateTimeUtils_1.DateTimeUtils.caclTimeDifference(r2.start, r1.start); });
};
DayWorkingTimeInfo.prototype.removeInterval = function (element) {
var index = this._workingIntervals.indexOf(element);
if (index > -1 && index < this._workingIntervals.length)
this._workingIntervals.splice(index, 1);
};
DayWorkingTimeInfo.prototype.clearIntervals = function () {
this._workingIntervals.splice(0, this._workingIntervals.length);
};
Object.defineProperty(DayWorkingTimeInfo.prototype, "workingIntervals", {
get: function () { return this._workingIntervals.slice(); },
enumerable: false,
configurable: true
});
Object.defineProperty(DayWorkingTimeInfo.prototype, "noWorkingIntervals", {
get: function () {
var res = new Array();
if (this.isWorkDay && this._workingIntervals.length === 0)
return res;
var starts = this._workingIntervals.map(function (r) { return r.end; });
starts.splice(0, 0, new Time_1.Time());
var ends = this._workingIntervals.map(function (r) { return r.start; });
ends.push(DateTimeUtils_1.DateTimeUtils.getLastTimeOfDay());
for (var i = 0; i < starts.length; i++) {
var start = starts[i];
var end = ends[i];
if (!DateTimeUtils_1.DateTimeUtils.areTimesEqual(start, end))
res.push(new TimeRange_1.TimeRange(start, end));
}
return res;
},
enumerable: false,
configurable: true
});
Object.defineProperty(DayWorkingTimeInfo.prototype, "isWorkDay", {
get: function () { return this._isWorkDay; },
set: function (value) {
this._isWorkDay = value;
if (!value)
this.clearIntervals();
},
enumerable: false,
configurable: true
});
return DayWorkingTimeInfo;
}());
exports.DayWorkingTimeInfo = DayWorkingTimeInfo;
/***/ }),
/* 241 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GanttViewApi = void 0;
var GanttViewApi = (function () {
function GanttViewApi(ganttView) {
this.maxZoom = 3;
this._ganttView = ganttView;
}
Object.defineProperty(GanttViewApi.prototype, "currentZoom", {
get: function () {
return this._ganttView.currentZoom;
},
set: function (value) {
this._ganttView.currentZoom = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GanttViewApi.prototype, "renderHelper", {
get: function () {
return this._ganttView.renderHelper;
},
enumerable: false,
configurable: true
});
GanttViewApi.prototype.getTaskAreaContainerWidth = function () {
return this.renderHelper.getTaskAreaContainerWidth();
};
GanttViewApi.prototype.updateTickSizeWidth = function () {
this._ganttView.updateTickSizeWidth();
};
Object.defineProperty(GanttViewApi.prototype, "settings", {
get: function () {
return this._ganttView.settings;
},
enumerable: false,
configurable: true
});
GanttViewApi.prototype.resetAndUpdate = function () {
this._ganttView.resetAndUpdate();
};
GanttViewApi.prototype.scrollToDateCore = function (date, addLeftPos) {
this._ganttView.scrollToDateCore(date, addLeftPos);
};
Object.defineProperty(GanttViewApi.prototype, "ganttOwner", {
get: function () {
return this._ganttView.ganttOwner;
},
enumerable: false,
configurable: true
});
GanttViewApi.prototype.scrollLeftByViewType = function () {
this._ganttView.scrollLeftByViewType();
};
Object.defineProperty(GanttViewApi.prototype, "dataRange", {
get: function () {
return this._ganttView.dataRange;
},
enumerable: false,
configurable: true
});
GanttViewApi.prototype.calculateAutoViewType = function (startDate, endDate) {
return this._ganttView.calculateAutoViewType(startDate, endDate);
};
GanttViewApi.prototype.zoomIn = function (leftPos) {
if (leftPos === void 0) { leftPos = this.getTaskAreaContainerWidth() / 2; }
var targetDate = this.renderHelper.getTargetDateByPos(leftPos);
var viewTypeRangeStart = this.settings.viewTypeRange.min;
if (this.currentZoom < this.maxZoom) {
this.currentZoom++;
this.updateTickSizeWidth();
this.resetAndUpdate();
}
else if (this.settings.viewType > viewTypeRangeStart) {
this.currentZoom = 1;
this.setViewType(this.settings.viewType - 1, false);
}
this.scrollToDateCore(targetDate, -leftPos);
};
GanttViewApi.prototype.zoomOut = function (leftPos) {
if (leftPos === void 0) { leftPos = this.renderHelper.getTaskAreaContainerWidth() / 2; }
var targetDate = this.renderHelper.getTargetDateByPos(leftPos);
var viewTypeRangeEnd = this.settings.viewTypeRange.max;
if (this.currentZoom > 1) {
this.currentZoom--;
this.updateTickSizeWidth();
this.resetAndUpdate();
}
else if (this.settings.viewType < viewTypeRangeEnd) {
this.currentZoom = this.maxZoom;
this.setViewType(this.settings.viewType + 1, false);
}
this.scrollToDateCore(targetDate, -leftPos);
};
GanttViewApi.prototype.setViewType = function (viewType, autoPositioning) {
if (autoPositioning === void 0) { autoPositioning = true; }
if (viewType == undefined)
viewType = this.calculateAutoViewType(this.dataRange.start, this.dataRange.end);
if (this.settings.viewType !== viewType) {
this.settings.viewType = viewType;
this.updateTickSizeWidth();
this.resetAndUpdate();
if (autoPositioning)
this.scrollLeftByViewType();
if (this.ganttOwner.UpdateGanttViewType)
this.ganttOwner.UpdateGanttViewType(viewType);
}
};
GanttViewApi.prototype.setViewTypeRange = function (min, max) {
if (min !== undefined)
this.settings.viewTypeRange.min = Math.min(min, max);
if (max !== undefined)
this.settings.viewTypeRange.max = Math.max(min, max);
var viewTypeRangeMin = this.settings.viewTypeRange.min;
var viewTypeRangeMax = this.settings.viewTypeRange.max;
var viewType = this.settings.viewType;
if (viewTypeRangeMin > viewType)
this.setViewType(viewTypeRangeMin);
else if (viewTypeRangeMax < viewType)
this.setViewType(viewTypeRangeMax);
};
return GanttViewApi;
}());
exports.GanttViewApi = GanttViewApi;
/***/ })
/******/ ]);
});
|
"use strict";
var attachComments = require("./attachComments");
var convertComments = require("./convertComments");
var toTokens = require("./toTokens");
var toAST = require("./toAST");
module.exports = function(ast, traverse, tt, code) {
// remove EOF token, eslint doesn't use this for anything and it interferes
// with some rules see https://github.com/babel/babel-eslint/issues/2
// todo: find a more elegant way to do this
ast.tokens.pop();
// convert tokens
ast.tokens = toTokens(ast.tokens, tt, code);
// add comments
convertComments(ast.comments);
// transform esprima and acorn divergent nodes
toAST(ast, traverse, code);
// ast.program.tokens = ast.tokens;
// ast.program.comments = ast.comments;
// ast = ast.program;
// remove File
ast.type = "Program";
ast.sourceType = ast.program.sourceType;
ast.directives = ast.program.directives;
ast.body = ast.program.body;
delete ast.program;
attachComments(ast, ast.comments, ast.tokens);
};
|
// @flow
const foo: $TEMPORARY$object<{| x?: number, y: number |}> = { y: 0 };
const bar: $TEMPORARY$object<{| [string]: number |}> = {foo: 3};
|
<<<<<<< HEAD
const Discord = require("discord.js");
exports.run = (client, message, args) => {
if (!message.mentions.users.first()) return message.edit('Failed to blocked a bitch, check your codes.');
message.mentions.users.first().block().then(() => {
message.edit("Bitch has bee blocked!");
})
};
=======
const Discord = require("discord.js");
exports.run = (client, message, args) => {
if (!message.mentions.users.first()) return message.edit('Failed to blocked a bitch, check your codes.');
message.mentions.users.first().block().then(() => {
message.edit("Bitch has bee blocked!");
})
};
>>>>>>> 68ae12d4ee819ce73c724b65761a3ab583bfc44a
|
import React from 'react';
import set from 'lodash/set';
import has from 'lodash/has';
import controlTypes from '../../../../CustomMetadataForm/controlTypes';
import renderConstraintForm from './renderConstraintForm';
import getPropKeys from './getPropKeys';
import getControlType from './getControlType';
import Row from '../../../../form/Grid/Row';
import LeftColumn from '../../../../form/Grid/LeftColumn';
import RightColumn from '../../../../form/Grid/RightColumn';
import ComboBox from '../../../../form/ComboBox';
import Label from '../../../../form/Label';
/*
* Rendering the selection & constraintform for nested objects
*
* The props should look like this:
* constraints: {
* props: {
* a: …
* }
* }
* parsedMetadata: {
* value: {
* a: …
* }
* }
*/
const ConstraintsForm = (props) => {
// retriev all propKeys from the parsed & custom metadata
const propKeys = getPropKeys(props.constraints, props.parsedMetadata);
const nestedLevel = props.nestedLevel + 1;
return (
<div>
{
propKeys.map((propKey) => {
const controlType = getControlType(
props.constraints,
props.parsedMetadata,
propKey
);
const propType = has(props.parsedMetadata, ['value', propKey, 'name']) ?
props.parsedMetadata.value[propKey].name :
'Not defined';
// updating the complete props object with only the controlType
// of the desired property changed and the constraints to be reset
const onChange = (event) => {
// take existing constraints.props
const newCustomMetadata = has(props, ['constraints', 'props']) ?
{ ...props.constraints.props } :
{};
// set an empty object for the wanted key to
// which also removes inner constraints in case they exist
set(newCustomMetadata, [propKey], {});
newCustomMetadata[propKey].controlType = event.value;
// give back the props list
props.onUpdate({ props: newCustomMetadata });
};
return (
<Row>
<LeftColumn nestedLevel={nestedLevel}>
<Label
type={propType}
propKey={propKey}
/>
</LeftColumn>
<RightColumn>
<ComboBox
value={controlType}
onChange={onChange}
options={controlTypes.map((type) => ({ value: type }))}
/>
</RightColumn>
{renderConstraintForm(
propKey,
controlType,
props.onUpdate,
props.constraints,
props.parsedMetadata,
nestedLevel
)}
</Row>
);
})
}
</div>
);
};
export default ConstraintsForm;
|
/* */
require("../../modules/es7.reflect.has-own-metadata");
module.exports = require("../../modules/_core").Reflect.hasOwnMetadata;
|
define(["foo"], function (_foo) {
"use strict";
(0, _foo.named)();
});
|
'use strict';
let request = require('superagent-bluebird-promise');
var xchange = function (base, currencies, options) {
if (!Array.isArray(currencies) || currencies.length == 0)
return Promise.reject(new Error('currencies must not be empty'));
let pairs = currencies
.map(c => '"' + base + c + '"')
.join(',');
let q = {
format: 'json',
q: options.yql.replace('{0}', pairs),
env: options.env
};
return request
.get(options.api)
.query(q)
.then(res => {
let fx = {
source: 'Yahoo eXchange',
base: base,
date: res.body.query.created,
rates: {}
};
res.body.query.results.rate.forEach(r => {
let symbol = r.id.substring(base.length);
let rate = Number.parseFloat(r.Rate);
if (isNaN(rate))
throw new Error(`missing exchange rate for '${base}-${symbol}'`);
fx.rates[symbol] = rate;
});
if (currencies.length != Object.keys(fx.rates).length)
return Promise.reject(new Error('missing exchange rate for some currencies'));
return fx;
})
.catch(Promise.reject);
};
xchange.details = {
name: [{tag: 'en', text: 'forex rates from Yahoo Financial XChange'}],
use: 'fxrates',
enabled: true,
home: 'https://developer.yahoo.com/yql/console/?q=show tables&env=store://datatables.org/alltableswithkeys#h=desc+yahoo.finance.xchange',
options: {
api: 'http://query.yahooapis.com/v1/public/yql',
yql: 'select * from yahoo.finance.xchange where pair in ({0})',
env: 'store://datatables.org/alltableswithkeys'
},
};
module.exports = xchange;
|
/*
* File: app/model/modTipoTransmision.js
*
* This file was generated by Sencha Architect version 4.1.2.
* http://www.sencha.com/products/architect/
*
* This file requires use of the Ext JS 5.1.x library, under independent license.
* License of Sencha Architect does not include license for Ext JS 5.1.x. For more
* details see http://www.sencha.com/license or contact license@sencha.com.
*
* This file will be auto-generated each and everytime you save your project.
*
* Do NOT hand edit this file.
*/
Ext.define('hwtProUnidades.model.modTipoTransmision', {
extend: 'Ext.data.Model',
requires: [
'Ext.data.field.Field'
],
fields: [
{
name: 'codigo'
},
{
name: 'descripcion'
}
]
});
|
var WebSqlDB = function(successCallback, errorCallback) {
this.initializeDatabase = function(successCallback, errorCallback) {
// This here refers to this instance of the webSqlDb
var self = this;
// Open/create the database
this.db = window.openDatabase("ToDoDB", "1.0", "Todo Demo DB", 200000);
// WebSQL databases are tranaction based so all db querying must be done within a transaction
this.db.transaction(
function(tx) {
self.createTable(tx);
self.addSampleData(tx);
},
function(error) {
console.log('Transaction error: ' + error);
if (errorCallback) errorCallback();
},
function() {
console.log('DEBUG - 5. initializeDatabase complete');
if (successCallback) successCallback();
}
)
}
this.createTable = function(tx) {
// This can be added removed/when testing
//tx.executeSql('DROP TABLE IF EXISTS todo');
var sql = "CREATE TABLE IF NOT EXISTS todo ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title, " +
"description, " +
"status)";
tx.executeSql(sql, null,
function() { // Success callback
console.log('DEBUG - 3. DB Tables created succesfully');
},
function(tx, error) { // Error callback
alert('Create table error: ' + error.message);
});
}
this.addSampleData = function(tx, todos) {
// Array of objects
var todos = [
{"id": 1, "title": "Go to the shop", "description": "Get milk and bread", "status": 0},
{"id": 2, "title": "Post office", "description": "Collect mail", "status": 0},
{"id": 3, "title": "Email Dad", "description": "About birthday", "status": 0},
{"id": 4, "title": "Haircut", "description": "Well overdue", "status": 1}
];
var l = todos.length;
var sql = "INSERT OR REPLACE INTO todo " +
"(id, title, description, status) " +
"VALUES (?, ?, ?, ?)";
var t;
// Loop through sample data array and insert into db
for (var i = 0; i < l; i++) {
t = todos[i];
tx.executeSql(sql, [t.id, t.title, t.description, t.status],
function() { // Success callback
console.log('DEBUG - 4. Sample data DB insert success');
},
function(tx, error) { // Error callback
alert('INSERT error: ' + error.message);
});
}
}
this.findAll = function(callback) {
this.db.transaction(
function(tx) {
var sql = "SELECT * FROM todo";
tx.executeSql(sql, [], function(tx, results) {
var len = results.rows.length,
todos = [],
i = 0;
// Semicolon at the start is to skip the initialisation of vars as we already initalise i above.
for (; i < len; i = i + 1) {
todos[i] = results.rows.item(i);
}
// Passes a array with values back to calling function
callback(todos);
});
},
function(error) {
alert("Transaction Error findAll: " + error.message);
}
);
}
this.findById = function(id, callback) {
this.db.transaction(
function(tx) {
var sql = "SELECT * FROM todo WHERE id=?";
tx.executeSql(sql, [id], function(tx, results) {
// This callback returns the first results.rows.item if rows.length is 1 or return null
callback(results.rows.length === 1 ? results.rows.item(0) : null);
});
},
function(error) {
alert("Transaction Error: " + error.message);
}
);
}
this.markCompleted = function(id, callback) {
this.db.transaction(
function (tx) {
var sql = "UPDATE todo SET status=1 WHERE id=?";
tx.executeSql(sql, [id], function(tx, result) {
// If results rows return true
callback(result.rowsAffected === 1 ? true : false);
});
}
);
}
this.markOutstanding = function(id, callback) {
this.db.transaction(
function (tx) {
var sql = "UPDATE todo SET status=0 WHERE id=?";
tx.executeSql(sql, [id], function(tx, result) {
// If results rows return true
callback(result.rowsAffected === 1 ? true : false);
});
}
);
}
this.insert = function(json, callback) {
// Converts a JavaScript Object Notation (JSON) string into an object.
var parsedJson = JSON.parse(json),
status = 0;
// Kept for for debuging
//console.log("DEBUG - Inserting the following json ");
//console.log(parsedJson);
this.db.transaction(
function (tx) {
var sql = "INSERT INTO todo (title, description, status) VALUES (?, ?, ?)";
tx.executeSql(sql, [parsedJson.title, parsedJson.description, status], function(tx, result) {
// If results rows
callback(result.rowsAffected === 1 ? true : false);
});
}
);
}
this.update = function(json, callback) {
// Converts a JavaScript Object Notation (JSON) string into an object.
var parsedJson = JSON.parse(json);
this.db.transaction(
function (tx) {
var sql = "UPDATE todo SET title=?, description=? WHERE id=?";
tx.executeSql(sql, [parsedJson.title, parsedJson.description, parsedJson.id], function(tx, result) {
// If results rows
callback(result.rowsAffected === 1 ? true : false);
// Kept for debugging
//console.log("Rows effected = " + result.rowsAffected);
});
}
);
}
this.delete = function(json, callback) {
// Converts a JavaScript Object Notation (JSON) string into an object.
var parsedJson = JSON.parse(json);
this.db.transaction(
function (tx) {
var sql = "DELETE FROM todo WHERE id=?";
tx.executeSql(sql, [parsedJson.id], function(tx, result) {
// If results rows
callback(result.rowsAffected === 1 ? true : false);
//console.log("Rows effected = " + result.rowsAffected);
});
}
);
}
this.initializeDatabase(successCallback, errorCallback);
}
|
/**
* 401 (Unauthorized) Response
*
* Similar to 403 Forbidden.
* Specifically for use when authentication is possible but has failed or not yet been provided.
* Error code response for missing or invalid authentication token.
*/
module.exports = function (data, code, message, root) {
// TODO: make transform camelCase to snake_case
var response = _.assign({
code: code || 'E_UNAUTHORIZED',
message: message || 'Missing or invalid authentication token',
data: data || {}
}, root);
this.res.status(401);
this.res.jsonx(response);
};
|
'use strict';
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var precss = require('precss');
var autoprefixer = require('autoprefixer');
module.exports = {
entry: {
bundle: __dirname + '/public/index.js',
shimsbundle: __dirname + '/public/shims.js'
},
output: {
path: __dirname + '/dist',
filename: '[name].js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.(eot|woff|woff2|ttf|svg|png|jpg)$/,
loader: 'url-loader?limit=30000&name=[name]-[hash].[ext]'
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader")
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader?minimize&-autoprefixer!postcss-loader!sass")
}
]
},
//为了添加css3 各个浏览器的前缀 postcss-cssnext 为了解决,webpack.config build的时候不添加前缀问题
//解决此问题的相关链接
//https://github.com/AngularClass/angular2-webpack-starter/wiki/How-to-include-PostCSS
//https://github.com/AngularClass/angular2-webpack-starter/issues/644
postcss: [
require('postcss-cssnext')({
browsers: ['> 0%']
})
],
plugins: [
new ExtractTextPlugin("styles.css", {
allChunks: true
})
],
resolve: {
extensions: ['', '.js', '.jsx', '.json']
}
};
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var GoHourglass = function GoHourglass(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm27.3 20c4.6-3.3 7.7-9.4 7.7-15 0-2.8-6.7-5-15-5s-15 2.2-15 5c0 5.6 3.1 11.7 7.7 15-4.6 3.3-7.7 9.4-7.7 15 0 2.8 6.7 5 15 5s15-2.2 15-5c0-5.6-3.1-11.7-7.7-15z m-7.3-17.5c5.5 0 10 1.1 10 2.5s-4.5 2.5-10 2.5-10-1.1-10-2.5 4.5-2.5 10-2.5z m-2.5 27.6c-6 0.3-9.3 1.5-9.9 3.2 0.6-4.5 2.9-7.4 5.5-9.8 2.9-2.7 4.4-2.4 4.4-4v10.6z m-4.1-13.8c-2.7-2.1-4.8-5-5.6-8.4 2.8 1.3 7.2 2.1 12.2 2.1s9.4-0.8 12.1-2.1c-0.7 3.4-2.8 6.3-5.5 8.4-0.9-0.6-2.7-1.3-6.6-1.3s-5.7 0.7-6.6 1.3z m9.1 13.8v-10.7c0 1.7 1.5 1.4 4.4 4 2.6 2.5 4.9 5.4 5.5 9.8-0.6-1.6-3.9-2.9-9.9-3.2z' })
)
);
};
exports.default = GoHourglass;
module.exports = exports['default'];
|
jest.mock('pkginfo', () => () => ({ version: '1.0.0' }));
const parseArgs = require('../src/parseArgs');
describe('parseArgs', () => {
it('should have correct defaults', () => {
expect(parseArgs(['node', 'micro-analytics'])).toMatchSnapshot();
});
it('should throw on non existing adapter', () => {
expect(() => {
parseArgs(['node', 'micro-analytics', '-a', 'not-a-real-adapter']);
}).toThrowErrorMatchingSnapshot();
});
it('should use DB_ADAPTER environment variable as default if set', () => {
process.env.DB_ADAPTER = 'memory';
expect(parseArgs(['node', 'micro-analytics']).adapter).toEqual('memory');
delete process.env.DB_ADAPTER;
});
it('should use PORT environment variable as default if set', () => {
process.env.PORT = '3000';
expect(parseArgs(['node', 'micro-analytics']).port).toEqual(3000);
delete process.env.PORT;
});
it('should use HOST environment variable as default if set', () => {
process.env.HOST = 'localhost';
expect(parseArgs(['node', 'micro-analytics']).host).toEqual('localhost');
delete process.env.HOST;
});
it('should use get adapter option when using -a', () => {
process.env.DB_ADAPTER = 'redis';
const args = ['node', 'micro-analytics', '-a', 'flat-file-db'];
expect(Object.keys(parseArgs(args))).toContain('dbName');
delete process.env.DB_ADAPTER;
});
it('should use get adapter option when using --adapter', () => {
process.env.DB_ADAPTER = 'redis';
const args = ['node', 'micro-analytics', '--adapter', 'flat-file-db'];
expect(Object.keys(parseArgs(args))).toContain('dbName');
delete process.env.DB_ADAPTER;
});
it('should use get adapter option when using --adapter=', () => {
process.env.DB_ADAPTER = 'redis';
const args = ['node', 'micro-analytics', '--adapter=flat-file-db'];
expect(Object.keys(parseArgs(args))).toContain('dbName');
delete process.env.DB_ADAPTER;
});
});
|
//>>built
define(["../_base"],function(c){var a=c.constants,b={"false":1,"int":1,"float":1,"while":1,"private":1,"char":1,"catch":1,"abstract":1,assert:1,"const":1,"byte":1,"for":1,"final":1,"finally":1,"implements":1,"import":1,"extends":1,"long":1,"throw":1,"instanceof":2,"static":1,"protected":1,"boolean":1,"interface":2,"native":1,"if":1,"public":1,"do":1,"return":1,"goto":1,"package":2,"void":2,"else":1,"break":1,"new":1,strictfp:1,"super":1,"true":1,"class":1,"synchronized":1,"case":1,"short":1,"throws":1,
"transient":1,"double":1,"volatile":1,"try":1,"this":1,"switch":1,"continue":1,def:2};c.languages.groovy={defaultMode:{lexems:[a.UNDERSCORE_IDENT_RE],illegal:"\x3c/",contains:["comment","string","number","function","block"],keywords:b},modes:[a.C_LINE_COMMENT_MODE,a.C_BLOCK_COMMENT_MODE,a.C_NUMBER_MODE,{className:"string",begin:'"""',end:'"""',contains:["escape"],relevance:0},a.QUOTE_STRING_MODE,a.BACKSLASH_ESCAPE,{className:"string",begin:"'''",end:"'''",contains:["escape"],relevance:0},a.APOS_STRING_MODE,
{className:"function",begin:"\\(",end:"\\)",contains:["comment","number","string","function","block"],keywords:b},{lexems:[a.UNDERSCORE_IDENT_RE],className:"block",begin:"\\{",end:"\\}",contains:["comment","string","number","function","block"],keywords:b}],GROOVY_KEYWORDS:b};return c.languages.groovy});
|
{
"name": "kiwappQRCode.js",
"url": "https://github.com/kiwapp/kiwappQRCode.git"
}
|
var menuWidth = 260;
function showDynamicModal(heading, content) {
var m = $('#dynamicModal');
m.find('h4').text(heading);
m.find('pre').text(content);
m.openModal({ in_duration: 200 });
}
$('.details-container').click(function(evt) {
var t = $(evt.target);
if (t.is('.showStatusMessage') || t.is('i')) {
if (t.is('i')) {
t = t.parent();
}
showDynamicModal(t.closest('tr').find('.name').text() + ' StatusMessage', t.next().text());
}
if (t.is('.showDescription')) {
showDynamicModal(t.text() + ' Description', t.next().text());
}
});
/* toggle dashboard on 'Enable Dashboard' click */
$('#enableDashboard').click(function() {
$('.suite-list, .suite-details').toggleClass('v-spacer');
$(this).toggleClass('enabled').children('i').toggleClass('active');
$('.dashboard').toggleClass('hide');
});
/* show suite data on click */
$('.suite').click(function() {
var t = $(this);
$('.suite').removeClass('active');
$('.suite-name-displayed, .details-container').html('');
t.toggleClass('active');
var html = t.find('.suite-content').html();
$('.suite-name-displayed').text(t.find('.suite-name').text());
$('.details-container').append(html);
});
$('#slide-out .report-item > a').filter(function(){
return this.href.match(/[^\/]+$/)[0] == document.location.pathname.match(/[^\/]+$/)[0];
}).parent().addClass('active');
/* filters -> by suite status */
$('#suite-toggle li').click(function() {
var t = $(this);
if (!t.hasClass('clear')) {
resetFilters();
var status = t.text().toLowerCase();
$('#suites .suite').addClass('hide');
$('#suites .suite.' + status).removeClass('hide');
selectVisSuite()
}
});
/* filters -> by test status */
$('#tests-toggle li').click(function() {
var t = $(this);
if (!t.hasClass('clear')) {
resetFilters();
var opt = t.text().toLowerCase();
$('.suite table tr.test-status:not(.' + opt + '), .details-container tr.test-status:not(.' + opt).addClass('hide');
$('.suite table tr.test-status.' + opt + ', .details-container tr.test-status.' + opt).removeClass('hide');
hideEmptySuites();
selectVisSuite()
}
});
/* filters -> by category */
$('#category-toggle li').click(function() {
var t = $(this);
if (!t.hasClass('clear')) {
resetFilters();
filterByCategory(t.text());
selectVisSuite()
}
});
$('.clear').click(function() {
resetFilters(); selectVisSuite()
});
function filterByCategory(cat) {
resetFilters();
$('td.test-features').each(function() {
if (!($(this).hasClass(cat))) {
$(this).closest('tr').addClass('hide');
}
});
hideEmptySuites();
}
function hideEmptySuites() {
$('.suite').each(function() {
var t = $(this);
if (t.find('tr.test-status').length == t.find('tr.test-status.hide').length) {
t.addClass('hide');
}
});
}
function resetFilters() {
$('.suite, tr.test-status').removeClass('hide');
$('.suite-toggle li:first-child, .tests-toggle li:first-child, .feature-toggle li:first-child').click();
}
function selectVisSuite() {
$('.suite:visible').get(0).click();
}
function clickListItem(listClass, index) {
$('#' + listClass).find('li').get(index).click();
}
$(document).ready(function() {
/* init */
$('select').material_select();
$('.modal-trigger').leanModal();
$('.tooltipped').tooltip({delay: 10});
/* for a single report item, hide sidenav */
if ($('.report-item').length <= 1) {
$('#slide-out').addClass('hide');
pinWidth = '56.5%';
$('.pin').css('width', pinWidth);
$('.main-wrap, nav').css('padding-left', '20px');
}
var passedPercentage = Math.round(((passed / total) * 100)) + '%';
$('.pass-percentage').text(passedPercentage);
$('.dashboard .determinate').attr('style', 'width:' + passedPercentage);
suitesChart(); testsChart();
$('ul.doughnut-legend').addClass('right');
resetFilters();
$('.suite:first-child').click();
});
var options = {
segmentShowStroke : false,
percentageInnerCutout : 55,
animationSteps : 1,
legendTemplate : '<ul class=\'<%=name.toLowerCase()%>-legend\'><% for (var i=0; i<segments.length; i++){%><li><span style=\'background-color:<%=segments[i].fillColor%>\'></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>'
};
/* report -> suites chart */
function suitesChart() {
if (!$('#suite-analysis').length) {
return false;
}
var passed = $('.suite-result.passed').length;
var failed = $('.suite-result.failed').length;
var others = $('.suite-result.error, .suite-result.inconclusive, .suite-result.skipped').length;
$('.suite-pass-count').text(passed);
$('.suite-fail-count').text(failed);
$('.suite-others-count').text(others);
var data = [
{ value: passed, color: '#00af00', highlight: '#32bf32', label: 'Pass' },
{ value: failed, color:'#F7464A', highlight: '#FF5A5E', label: 'Fail' },
{ value: $('.suite-result.error').length, color:'#ff6347', highlight: '#ff826b', label: 'Error' },
{ value: $('.suite-result.inconclusive').length, color: '#FDB45C', highlight: '#FFC870', label: 'Warning' },
{ value: $('.suite-result.skipped').length, color: '#1e90ff', highlight: '#4aa6ff', label: 'Skip' }
];
var ctx = $('#suite-analysis').get(0).getContext('2d');
var suiteChart = new Chart(ctx).Doughnut(data, options);
drawLegend(suiteChart, 'suite-analysis');
}
/* test case counts */
var total = $('.test-name').length;
var passed = $('td.passed').length;
var failed = $('td.failed').length;
var inconclusive = $('td.inconclusive').length;
var errors = $('td.error').length;
var skipped = $('td.skipped').length;
/* report -> tests chart */
function testsChart() {
if (!$('#test-analysis').length) {
return false;
}
var data = {};
if ($('body.summary').length > 0) {
total = parseInt($('#total-tests').text());
passed = parseInt($('#total-passed').text());
failed = parseInt($('#total-failed').text());
others = parseInt($('#total-others').text());
data = [
{ value: passed, color: '#00af00', highlight: '#32bf32', label: 'Pass' },
{ value: failed, color:'#F7464A', highlight: '#FF5A5E', label: 'Fail' },
{ value: others, color: '#1e90ff', highlight: '#4aa6ff', label: 'Others' }
];
$('.test-others-count').text(others);
}
else {
data = [
{ value: passed, color: '#00af00', highlight: '#32bf32', label: 'Pass' },
{ value: failed, color:'#F7464A', highlight: '#FF5A5E', label: 'Fail' },
{ value: errors, color:'#ff6347', highlight: '#ff826b', label: 'Error' },
{ value: inconclusive, color: '#FDB45C', highlight: '#FFC870', label: 'Warning' },
{ value: skipped, color: '#1e90ff', highlight: '#4aa6ff', label: 'Skip' }
];
$('.test-others-count').text(errors + inconclusive + skipped);
}
$('.test-pass-count').text(passed);
$('.test-fail-count').text(failed);
var ctx = $('#test-analysis').get(0).getContext('2d');
testChart = new Chart(ctx).Doughnut(data, options);
drawLegend(testChart, 'test-analysis');
}
/* draw legend for test and step charts [DASHBOARD] */
function drawLegend(chart, id) {
var helpers = Chart.helpers;
var legendHolder = document.getElementById(id);
legendHolder.innerHTML = chart.generateLegend();
helpers.each(legendHolder.firstChild.childNodes, function(legendNode, index) {
helpers.addEvent(legendNode, 'mouseover', function() {
var activeSegment = chart.segments[index];
activeSegment.save();
activeSegment.fillColor = activeSegment.highlightColor;
chart.showTooltip([activeSegment]);
activeSegment.restore();
});
});
Chart.helpers.addEvent(legendHolder.firstChild, 'mouseout', function() {
chart.draw();
});
$('#' + id).after(legendHolder.firstChild);
}
|
const FilesLoader = Jymfony.Component.Validator.Mapping.Loader.FilesLoader;
const YamlFileLoader = Jymfony.Component.Validator.Mapping.Loader.YamlFileLoader;
/**
* Loads validation metadata from a list of YAML files.
*
* @see FilesLoader
*
* @memberOf Jymfony.Component.Validator.Mapping.Loader
*/
export default class YamlFilesLoader extends FilesLoader {
/**
* @inheritdoc
*/
_getFileLoaderInstance(file) {
return new YamlFileLoader(file);
}
}
|
describe('dev-theme', function() {
beforeEach(function() {
browser().navigateTo(mainUrl);
});
it('should have bs3 theme classes', function() {
var s = '[ng-controller="DevTheme"] ';
var a = s + 'a#e-attrs ';
// click on body
element(a).click();
expect(element(a).css('display')).toBe('none');
expect(element(s+'form .editable-buttons button[type="submit"]').attr('class')).toBe("btn btn-primary");
expect(element(s+'form[editable-form="$form"]').count()).toBe(1);
using(s).input('$parent.$data').enter('username2');
element('body').click();
expect(element(a).css('display')).not().toBe('none');
expect(element(a).text()).toMatch('awesome user');
expect(element(s+'form').count()).toBe(0);
});
it('should have default theme classes', function() {
var s = '[ng-controller="DevTheme"] ';
var a = s + 'a.cancel ';
expect(element(a).text()).toMatch('awesome user');
element(a).click();
expect(element(s+'form .editable-buttons button[type="submit"]').attr('class')).toBe(undefined);
});
it('should have bs2 icons', function() {
var s = '[ng-controller="DevTheme"] ';
var a = s + 'a.bs2-test ';
expect(element(a).text()).toMatch('awesome user');
element(a).click();
expect(element(s+'form .editable-buttons button[type="submit"] span').attr('class')).toBe('icon-ok icon-white')
});
it('should have font-awesome icons', function() {
var s = '[ng-controller="DevTheme"] ';
var a = s + 'a.fa-test ';
expect(element(a).text()).toMatch('awesome user');
element(a).click();
expect(element(s+'form .editable-buttons button[type="submit"] span').attr('class')).toBe('fa fa-check')
});
it('should have bs4 icons', function() {
var s = '[ng-controller="DevTheme"] ';
var a = s + 'a.bs4-test ';
expect(element(a).text()).toMatch('awesome user');
element(a).click();
expect(element(s+'form .editable-buttons button[type="submit"] span').attr('class')).toBe('fa fa-check')
});
});
|
var core = module.exports = { version: '2.6.2' };
if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef
|
var update = require("react/lib/update");
function DB(initialData) {
this.data = initialData || {};
}
module.exports = DB;
DB.prototype.get = function(id, createDefaultData) {
var d = this.data["_" + id];
if(!d) {
return this.data["_" + id] = createDefaultData;
}
return d;
};
DB.prototype.update = function(id, upd) {
return this.data["_" + id] = update(this.data["_" + id], upd);
};
DB.prototype.set = function(id, data) {
return this.data["_" + id] = data;
};
|
'use strict';
// Product Model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProductSchema = new Schema({
code: {
type: String,
required: true,
trim: true
},
name : String,
description : String,
tokens : Number,
created_at: Date,
updated_at: Date,
});
ProductSchema.pre('save', function(next){
var now = new Date();
this.updated_at = now;
if ( !this.created_at )
this.created_at = now;
next();
});
module.exports = mongoose.model('Product', ProductSchema);
|
/* Estonian initialisation for the jQuery UI date picker plugin. */
/* Written by Mart Sõmermaa (mrts.pydev at gmail com). */
(function (factory) {
// AMD. Register as an anonymous module.
module.exports = factory(require('../datepicker'));;
}(function (datepicker) {
datepicker.regional['et'] = {
closeText: 'Sulge',
prevText: 'Eelnev',
nextText: 'J\xE4rgnev',
currentText: 'T\xE4na',
monthNames: [
'Jaanuar',
'Veebruar',
'M\xE4rts',
'Aprill',
'Mai',
'Juuni',
'Juuli',
'August',
'September',
'Oktoober',
'November',
'Detsember'
],
monthNamesShort: [
'Jaan',
'Veebr',
'M\xE4rts',
'Apr',
'Mai',
'Juuni',
'Juuli',
'Aug',
'Sept',
'Okt',
'Nov',
'Dets'
],
dayNames: [
'P\xFChap\xE4ev',
'Esmasp\xE4ev',
'Teisip\xE4ev',
'Kolmap\xE4ev',
'Neljap\xE4ev',
'Reede',
'Laup\xE4ev'
],
dayNamesShort: [
'P\xFChap',
'Esmasp',
'Teisip',
'Kolmap',
'Neljap',
'Reede',
'Laup'
],
dayNamesMin: [
'P',
'E',
'T',
'K',
'N',
'R',
'L'
],
weekHeader: 'n\xE4d',
dateFormat: 'dd.mm.yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''
};
datepicker.setDefaults(datepicker.regional['et']);
return datepicker.regional['et'];
}));
|
var snare = require('../');
var d = snare();
return function (t) {
return d(t % (1/2));
};
|
'use strict';
/**
* @ngdoc function
* @name googleLogin.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the googleMain
*/
angular.module('googleLogin')
.controller('MainCtrl', ['$location', '$scope', 'AuthenticationService', 'SafeApply',
function (location, scope, authenticationService, safeApply) {
scope.loading = true;
scope.email;
scope.name;
scope.picture;
scope.init = function () {
authenticationService.checkAuth().then(getUser, goToLogin);
}
function getUser() {
authenticationService.getUser().then(showUserDetails, error);
}
function showUserDetails(result) {
scope.email = result.email;
scope.name = result.name;
scope.picture = result.picture;
}
function error(result) {
console.log(error);
}
function goToLogin() {
safeApply.execute(location.path('/login'));
}
scope.init();
}
]);
|
'use strict';
module.exports = function (grunt) {
var _ = require('lodash');
var fs = require('fs');
var defaultConfig = require('./default-config.js');
var localConfig;
var stat;
try {
stat = fs.statSync('./local-config.js');
} catch(e) {
localConfig = {};
}
if (stat) {
try {
localConfig = require('./local-config.js');
} catch(e) {
throw("error reading './local-config.js': " + e);
}
}
var exec = require('sync-exec');
var commitHash = exec('git log --pretty=format:"%h" -n 1');
var config = _.merge(defaultConfig, localConfig);
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks('grunt-ng-constant');
// Load grunt tasks automatically, when needed
require('jit-grunt')(grunt, {
express: 'grunt-express-server',
useminPrepare: 'grunt-usemin',
ngtemplates: 'grunt-angular-templates',
cdnify: 'grunt-google-cdn',
protractor: 'grunt-protractor-runner',
injector: 'grunt-asset-injector',
buildcontrol: 'grunt-build-control'
});
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Required for the translations //
var potfiles = [
'client/index.html',
'client/components/**/*.html',
'client/components/**/*.js',
'client/app/main/*.js',
];
var languages = [
'en_GB',
'de_DE',
'fr_FR',
'ro',
'it'
];
// Define the configuration for all the tasks
grunt.initConfig({
ngconstant: {
options: {
space: ' ',
wrap: '"use strict";\n\n {%= __ngModule %}',
name: 'config',
dest: '<%= yeoman.client %>/scripts/config.js',
},
test: {
constants: {
API_END_POINT: 'http://api.ctapp.test:8080/api/v1',
API_END_POINT_V2: 'https://api.ctapp.io/api/v2',
API_URL: 'http://api.ctapp.test:8080',
STRIPE_KEY: 'pk_test_E3rGjKckx4EUL65pXgv6zUed',
AUTH_URL: 'http://dashboard.ctapp.test:8080',
SLACK_TOKEN: '3540010629.12007999527',
CHIMP_TOKEN: '531543883634',
INTERCOM: 'xxx',
PUSHER: 'xxx',
DEBUG: true,
COLOURS: '#009688 #FF5722 #03A9F4 #607D8B #F44336 #00BCD4',
COMMITHASH: commitHash.stdout,
THEMES: []
}
},
development: {
constants: config.frontend.constants
},
beta: {
constants: {
API_END_POINT: 'https://beta.ctapp.io/api/v1',
API_END_POINT_V2: 'https://ldn-01.ctapp.io/api/v1',
API_URL: 'https://beta.ctapp.io',
STRIPE_KEY: 'pk_live_Fe0qoaafcT68z8OjFYJwg1vC',
AUTH_URL: 'https://id.ctapp.io',
SLACK_TOKEN: '3540010629.11828901815',
CHIMP_TOKEN: '279197455989',
PUSHER: 'f5c774e098156e548079',
INTERCOM: 'zklfhs87',
DEBUG: true,
COLOURS: '#009688 #FF5722 #03A9F4 #607D8B #F44336 #00BCD4',
COMMITHASH: commitHash.stdout,
THEMES: [
"pink",
"orange",
"deep-orange",
"blue",
"blue-grey",
"light-blue",
"red",
"green",
"light-green",
"lime",
"yellow",
"teal",
"brown",
"purple",
"deep-purple",
"cyan",
"yellow",
"amber",
"indigo",
"brown",
"grey",
]
}
},
production: {
constants: {
API_END_POINT: 'https://api.ctapp.io/api/v1',
API_END_POINT_V2: 'https://ldn-01.ctapp.io/api/v1',
API_URL: 'https://api.ctapp.io',
STRIPE_KEY: 'pk_live_Fe0qoaafcT68z8OjFYJwg1vC',
AUTH_URL: 'https://id.ctapp.io',
SLACK_TOKEN: '3540010629.11828901815',
CHIMP_TOKEN: '279197455989',
PUSHER: 'f5c774e098156e548079',
INTERCOM: 'zklfhs87',
DEBUG: true,
COLOURS: '#009688 #FF5722 #03A9F4 #607D8B #F44336 #00BCD4',
COMMITHASH: commitHash.stdout,
THEMES: [
"pink",
"orange",
"deep-orange",
"blue",
"blue-grey",
"light-blue",
"red",
"green",
"light-green",
"lime",
"yellow",
"teal",
"brown",
"purple",
"deep-purple",
"cyan",
"yellow",
"amber",
"indigo",
"brown",
"grey",
]
}
}
},
// Project settings
pkg: grunt.file.readJSON('package.json'),
yeoman: {
// configurable paths
client: require('./bower.json').appPath || 'client',
dist: 'dist'
},
express: {
options: {
port: process.env.PORT || 9090
},
dev: {
options: {
script: 'server/app.js',
debug: true
}
},
prod: {
options: {
script: 'dist/server/app.js'
}
}
},
open: {
server: {
url: 'http://localhost:<%= express.options.port %>'
}
},
watch: {
injectJS: {
files: [
'<%= yeoman.client %>/{app,components}/**/*.js',
'!<%= yeoman.client %>/{app,components}/**/*.spec.js',
'!<%= yeoman.client %>/{app,components}/**/*.mock.js',
'!<%= yeoman.client %>/app/app.js'],
tasks: ['injector:scripts']
},
injectCss: {
files: [
'<%= yeoman.client %>/{app,components}/**/*.css'],
tasks: ['injector:css']
},
injectSass: {
files: [
'<%= yeoman.client %>/{app,components}/**/*.{scss,sass}'],
tasks: ['injector:sass']
},
sass: {
files: [
'<%= yeoman.client %>/{app,components}/**/*.{scss,sass}'],
tasks: ['sass', 'autoprefixer']
},
mochaTest: {
files: ['server/**/*.spec.js'],
tasks: ['env:test', 'mochaTest']
},
jsTest: {
files: [
'<%= yeoman.client %>/{app,components}/**/*.spec.js',
'<%= yeoman.client %>/{app,components}/**/*.mock.js'
],
tasks: ['newer:jshint:all', 'karma']
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
files: [
'{.tmp,<%= yeoman.client %>}/{app,components}/**/*.css',
'{.tmp,<%= yeoman.client %>}/{app,components}/**/*.html',
'{.tmp,<%= yeoman.client %>}/{app,components}/**/*.js',
'!{.tmp,<%= yeoman.client %>}{app,components}/**/*.spec.js',
'!{.tmp,<%= yeoman.client %>}/{app,components}/**/*.mock.js',
'<%= yeoman.client %>/assets/images/{,*//*}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.client %>/assets/js/{,*//*}*.{js}',
'<%= yeoman.client %>/assets/css/{,*//*}*.{js}'
],
options: {
livereload: true
}
},
express: {
files: [
'server/**/*.{js,json}'
],
tasks: ['express:dev', 'wait'],
options: {
livereload: true,
nospawn: true //Without this option specified express won't be reloaded
}
}
},
// Required for the translations //
nggettext_extract: {
pot: {
files: {
'po/cucumber-frontend.pot': potfiles
}
}
},
msgInitMerge: {
target_pot: {
src: ['po/cucumber-frontend.pot'],
options: {
locales: languages,
poFilesPath: 'po/<%= locale%>.po',
}
}
},
nggettext_compile: {
options: {
format: 'json'
},
all: {
files: [
{
expand: true,
dot: true,
cwd: "po",
dest: '<%= yeoman.dist %>/server/translations',
src: ["*.po"],
ext: ".json"
}
]
}
},
potomo: {
all: {
files: [
{
expand: true,
cwd: 'po',
src: ['*.po'],
dest: 'po',
ext: '.mo',
nonull: true
}
]
}
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '<%= yeoman.client %>/.jshintrc',
reporter: require('jshint-stylish')
},
server: {
options: {
jshintrc: 'server/.jshintrc'
},
src: [
'server/**/*.js',
'!server/**/*.spec.js',
'!<%= yeoman.client %>/components/js/*'
]
},
serverTest: {
options: {
jshintrc: 'server/.jshintrc-spec'
},
src: ['server/**/*.spec.js']
},
all: [
'<%= yeoman.client %>/{app,components}/**/*.js',
'!<%= yeoman.client %>/{app,components}/**/*.spec.js',
'!<%= yeoman.client %>/{app,components}/**/*.mock.js'
],
test: {
src: [
'<%= yeoman.client %>/{app,components}/**/*.spec.js',
'<%= yeoman.client %>/{app,components}/**/*.mock.js'
]
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/*',
'!<%= yeoman.dist %>/.git*',
'!<%= yeoman.dist %>/.openshift',
'!<%= yeoman.dist %>/Procfile'
]
}]
},
server: '.tmp'
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['last 1 version']
},
dist: {
files: [{
expand: true,
cwd: '.tmp/',
src: '{,*/}*.css',
dest: '.tmp/'
}]
}
},
// Debugging with node inspector
'node-inspector': {
custom: {
options: {
'web-host': 'localhost'
}
}
},
// Use nodemon to run server in debug mode with an initial breakpoint
nodemon: {
debug: {
script: 'server/app.js',
options: {
nodeArgs: ['--debug-brk'],
env: {
PORT: process.env.PORT || 9000
},
callback: function (nodemon) {
nodemon.on('log', function (event) {
console.log(event.colour);
});
// opens browser on initial server start
nodemon.on('config:update', function () {
setTimeout(function () {
require('open')('http://localhost:8080/debug?port=5858');
}, 500);
});
}
}
}
},
// Automatically inject Bower components into the app
wiredep: {
target: {
src: '<%= yeoman.client %>/index.html',
ignorePath: '<%= yeoman.client %>/',
exclude: ['exporting.js', '/foundation.js/', '/foundation.css/', /bootstrap-sass-official/, /bootstrap.js/, '/json3/', '/es5-shim/']
}
},
// Renames files for browser caching purposes
rev: {
dist: {
files: {
src: [
// '<%= yeoman.dist %>/public/{,*/}*.js',
'<%= yeoman.dist %>/public/app/{,*/}*.js',
'<%= yeoman.dist %>/public/assets/{,*/}*.js',
'<%= yeoman.dist %>/public/{,*/}*.css',
// '<%= yeoman.dist %>/public/assets/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist %>/public/assets/fonts/*'
]
}
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
html: ['<%= yeoman.client %>/index.html'],
options: {
dest: '<%= yeoman.dist %>/public'
}
},
// Performs rewrites based on rev and the useminPrepare configuration
usemin: {
html: ['<%= yeoman.dist %>/public/{,*/}*.html'],
css: ['<%= yeoman.dist %>/public/{,*/}*.css'],
js: [
// '<%= yeoman.dist %>/public/{,*/}*.js'
'<%= yeoman.dist %>/public/app/{,*/}*.js',
'<%= yeoman.dist %>/public/assets/{,*/}*.js'
],
options: {
assetsDirs: [
'<%= yeoman.dist %>/public',
'<%= yeoman.dist %>/public/assets/images'
],
// This is so we update image references in our ng-templates
patterns: {
js: [
[/(assets\/images\/.*?\.(?:gif|jpeg|jpg|png|webp|svg))/gm, 'Update the JS to reference our revved images']
]
}
}
},
// The following *-min tasks produce minified files in the dist folder
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.client %>/assets/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/public/assets/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.client %>/assets/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/public/assets/images'
}]
}
},
// Allow the use of non-minsafe AngularJS files. Automatically makes it
// minsafe compatible so Uglify does not destroy the ng references
ngAnnotate: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat',
src: '*/**.js',
dest: '.tmp/concat'
}]
}
},
// Package all the html partials into a single javascript payload
ngtemplates: {
options: {
// This should be the name of your apps angular module
module: 'myApp',
htmlmin: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
removeAttributeQuotes: true,
removeEmptyAttributes: true,
removeRedundantAttributes: false,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true
},
usemin: 'app/app.js'
},
main: {
cwd: '<%= yeoman.client %>',
src: ['{app,components}/**/*.html'],
dest: '.tmp/templates.js'
},
tmp: {
cwd: '.tmp',
src: ['{app,components}/**/*.html'],
dest: '.tmp/tmp-templates.js'
}
},
// Replace Google CDN references
cdnify: {
dist: {
html: ['<%= yeoman.dist %>/public/*.html']
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.client %>',
dest: '<%= yeoman.dist %>/public',
src: [
'*.{ico,png,txt}',
'.htaccess',
'bower_components/**/*',
'assets/images/{,*/}*.{webp}',
'assets/fonts/**/*',
'index.html'
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/public/assets/images',
src: ['generated/*']
}, {
expand: true,
dest: '<%= yeoman.dist %>',
src: [
'package.json',
'server/**/*'
]
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.client %>',
dest: '.tmp/',
src: ['{app,components}/**/*.css']
}
},
buildcontrol: {
options: {
dir: 'dist',
commit: true,
push: true,
connectCommits: false,
message: 'Built %sourceName% from commit %sourceCommit% on branch %sourceBranch%'
},
beta: {
options: {
remote: 'git@heroku.com:secure-mesa-9387.git', // alpha....
branch: 'master',
force: true
}
},
dev: {
options: {
remote: 'git@heroku.com:thawing-basin-34731.git', // dev egg testing
branch: 'master'
}
},
master: {
options: {
remote: 'git@heroku.com:sheltered-bayou-9283.git', // basically for resellers
branch: 'master'
}
},
// not in use anymore
usa: {
options: {
remote: 'git@heroku.com:limitless-brook-11104.git', // the main repo
branch: 'master'
}
}
},
concurrent: {
server: [
'sass',
],
test: [
'sass',
],
debug: {
tasks: [
'nodemon',
'node-inspector'
],
options: {
logConcurrentOutput: true
}
},
dist: [
// 'sass',
'imagemin',
'svgmin'
]
},
// Test settings
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true,
browsers: ['PhantomJS2'],
browserNoActivityTimeout: 30000
}
},
mochaTest: {
options: {
reporter: 'spec'
},
src: ['server/**/*.spec.js']
},
protractor: {
options: {
configFile: 'protractor.conf.js'
},
chrome: {
options: {
args: {
browser: 'chrome'
}
}
}
},
env: {
test: {
NODE_ENV: 'test'
},
prod: {
NODE_ENV: 'production'
},
all: localConfig
},
sass: {
server: {
options: {
// includePaths: ['bower_components/foundation/scss'],
loadPath: [
'<%= yeoman.client %>/bower_components/foundation/scss',
'<%= yeoman.client %>/bower_components',
'<%= yeoman.client %>/app',
'<%= yeoman.client %>/components'
],
compass: false
},
files: _.merge({
'.tmp/app/app.css' : '<%= yeoman.client %>/app/app.scss'
}, _.isEmpty(localConfig) ? {} : config.sass.server.files)
}
},
injector: {
// Inject application script files into index.html (doesn't include bower)
scripts: {
options: {
transform: function(filePath) {
filePath = filePath.replace('/client/', '');
filePath = filePath.replace('/.tmp/', '');
return '<script src="' + filePath + '"></script>';
},
starttag: '<!-- injector:js -->',
endtag: '<!-- endinjector -->'
},
files: {
'<%= yeoman.client %>/index.html': [
['{.tmp,<%= yeoman.client %>}/{app,components,scripts}/**/*.js',
'!{.tmp,<%= yeoman.client %>}/app/app.js',
'!{.tmp,<%= yeoman.client %>}/{app,components}/**/*.spec.js',
'!{.tmp,<%= yeoman.client %>}/{app,components}/**/*.mock.js']
]
}
},
sass: {
options: {
transform: function(filePath) {
filePath = filePath.replace('/client/app/', '');
filePath = filePath.replace('/client/components/', '');
return '@import \'' + filePath + '\';';
},
starttag: '// injector',
endtag: '// endinjector'
},
files: {
'<%= yeoman.client %>/app/app.scss': [
'<%= yeoman.client %>/{app,components}/**/*.{scss,sass}',
'!<%= yeoman.client %>/app/app.{scss,sass}'
]
}
},
// Inject component css into index.html
css: {
options: {
transform: function(filePath) {
filePath = filePath.replace('/client/', '');
filePath = filePath.replace('/.tmp/', '');
return '<link rel="stylesheet" href="' + filePath + '">';
},
starttag: '<!-- injector:css -->',
endtag: '<!-- endinjector -->'
},
files: {
'<%= yeoman.client %>/index.html': [
'<%= yeoman.client %>/{app,components}/**/*.css'
]
}
}
},
});
// Used for delaying livereload until after server has restarted
grunt.registerTask('wait', function () {
grunt.log.ok('Waiting for server reload...');
var done = this.async();
setTimeout(function () {
grunt.log.writeln('Done waiting!');
done();
}, 1500);
});
grunt.registerTask('express-keepalive', 'Keep grunt running', function() {
this.async();
});
// This is not being used, if dormant, we should remove completely
grunt.registerTask('configServer', function(target) {
var output = "// Generated! Do not edit!\n"
+ "'use strict';module.exports = ";
output += JSON.stringify(config.server.env);
output += ';';
grunt.file.write('./server/config/local-config.js', output,
{ encoding: 'utf-8' });
});
grunt.registerTask('serve', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'env:all', 'env:prod', 'express:prod', 'wait', 'open', 'express-keepalive']);
}
if (target === 'debug') {
return grunt.task.run([
'clean:server',
'env:all',
'concurrent:server',
'wiredep',
'autoprefixer',
'concurrent:debug'
]);
}
grunt.task.run([
'clean:server',
'configServer',
'ngconstant:development',
'env:all',
'concurrent:server',
'wiredep',
'autoprefixer',
'express:dev',
'wait',
'open',
'watch'
]);
});
// grunt.registerTask('test', ['karma:travis']);
grunt.registerTask('build-beta', [
'clean:dist',
'ngconstant:beta',
'concurrent:dist',
'wiredep',
'useminPrepare',
'autoprefixer',
'ngtemplates',
'concat',
'ngAnnotate',
'copy:dist',
// 'all-po',
'cdnify',
'cssmin',
'uglify',
'rev',
'usemin'
]);
grunt.registerTask('build', [
'clean:dist',
'configServer',
'ngconstant:production',
'concurrent:dist',
'wiredep',
'useminPrepare',
'autoprefixer',
'ngtemplates',
'concat',
'ngAnnotate',
'copy:dist',
// 'all-po',
'cdnify',
'cssmin',
'uglify',
'rev',
'usemin'
]);
grunt.registerTask('po/POTFILES',
'Collect files containing translatable strings',
function() {
grunt.log.debug('Collecting files with translatable messages');
var output = '',
found = grunt.file.expand(potfiles);
found.forEach(function(filename) {
output += '../' + filename + '\n';
});
try {
grunt.file.write('po/POTFILES', output, {encoding: 'utf-8'});
} catch(e) {
console.log(e);
grunt.log.error(e.message);
}
});
grunt.registerTask('pot', [
'nggettext_extract'
]);
grunt.registerTask('update-po', [
'msgInitMerge'
]);
grunt.registerTask('install-po', [
'potomo',
'nggettext_compile'
]);
grunt.registerTask('all-po', [
'po/POTFILES',
'pot',
'update-po',
'install-po'
]);
grunt.loadNpmTasks('grunt-msg-init-merge');
grunt.loadNpmTasks('grunt-potomo');
grunt.loadNpmTasks('grunt-angular-gettext');
grunt.registerTask('server', function () {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run(['serve']);
});
grunt.registerTask('test', function(target) {
if (target === 'server') {
return grunt.task.run([
'env:all',
'env:test',
'mochaTest'
]);
}
else if (target === 'client') {
return grunt.task.run([
'clean:server',
'env:all',
'concurrent:test',
// 'injector:sass',
'autoprefixer',
'karma'
]);
}
else if (target === 'e2e') {
return grunt.task.run([
'clean:server',
'env:all',
'env:test',
'concurrent:test',
// 'injector:sass',
'wiredep',
'autoprefixer',
'express:dev',
'protractor'
]);
}
else grunt.task.run([
'ngconstant:test',
'test:server',
'test:client'
]);
});
// grunt.loadNpmTasks('grunt-sass');
// grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};
|
$.lc.setRequestedOrientation(0);
$.cacheImg('porker', 'img/cards4.png');
var pai = {
cards : [],
backcard : NormalPorker.back,
mycards : [],
position : 0,
isdizhu : false,
me : $.lc.self(), //自己参数
left : $.lc.getBackward(), //左侧玩家
right : $.lc.getForward(),
shangjiachupai : [],
zijichupai : [],
mycardindex : 0,
dizhu : {},
}, game = {
xipai : function() {
for (var card in NormalPorker.data ) {
if (card.num === 1) {
card.num = 14;
}
if (card.num === 2) {
card.num = 15;
}
card.dx = 200;
card.dy = 50;
card.dh = card.sh;
card.dw = card.sw;
card.name = card.color + "_" + card.type + "_" + card.num;
}
pai.cards = $.mess(NormalPorker);
pai.mycards = $.minePorker(pai.cards, pai.position, 3, 51);
pai.backcard.dh = pai.backcard.sh;
pai.backcard.dw = pai.backcard.sw;
},
fapai : function() {
//画中心牌
var centercard = {
dx : 200,
dy : 50,
};
$.extend(centercard, pai.backcard);
$('$desk').entity('back-0', centercard).res('porker');
game.fapaiAnimation(0, 0);
},
fapaiAnimation : function(position, index) {
if (position > 2) {
position = 0;
}
if (index < pai.cards.length - 3) {
if (position === pai.position) {
var card = pai.mycards[pai.mycardindex];
$('$desk').entity(card.name, card).res('porker').bind('touchstart', function(x, y) {
if (this.dy === 240) {
this.dy = 200;
} else {
this.dy = 240;
}
$('$desk').update();
}, false).animation().to({
dx : 30 + pai.mycardindex * 25,
dy : 240
}, 300).onComplete(function() {
game.fapaiAnimation(position++, index++);
}).start();
pai.mycardindex++;
}
if (position === pai.left.position) {
var card = {
name : "back-left-" + index,
dx : 0,
dy : 0,
};
$.extend(card, pai.backcard);
$('$desk').entity(card.name, card).res('porker').translate(200, 50).rotate(90).animation().to({
translateX : 80,
translateY : 50,
}, 300).onComplete(function() {
$('$desk').entity(card.name).remove();
game.fapaiAnimation(position++, index++);
}).start();
}
if (position === pai.right.position) {
var card = {
name : "back-right-" + index,
dx : 0,
dy : 0,
};
$.extend(card, pai.backcard);
$('$desk').entity(card.name, card).res('porker').translate(200, 90).rotate(-90).animation().to({
translateX : 350,
translateY : 90,
}, 300).onComplete(function() {
$('$desk').entity(card.name).remove();
game.fapaiAnimation(position++, index++);
}).start();
}
} else {
//发牌结束,开始抢地主
game.paixu();
game.liangdipai();
if (pai.position === 0) {
game.qiangdizhu();
}
}
},
paixu : function() {
$.porkerDesc(pai.mycards);
$('$desk@back-0').remove();
for (var i = 0; i < pai.mycards.length; i++) {
var card = pai.mycards[i];
card.dx = 30 + i * 25;
$('$desk').entity(card.name).up();
}
},
liangdipai : function() {
//亮底牌
for (var i = pai.cards.length - 3; i < pai.cards.length; i++) {
var card = pai.cards[i];
card.dx = 80 + 30 * (pai.cards.length - i);
card.dy = 60;
$('$desk').entity("dipai_" + card.name, card).res('porker');
}
$('$desk').update();
},
qiangdizhu : function() {
$('#jiaofen').show();
},
jiaofen : function(f) {
pai.fen = f;
if (f === 3 || pai.position === 2) {
//直接就是地主了
$.lc.notify('all', {
eventTag : 'onDizhuOK',
dizhu : me,
fen : pai.fen,
});
game.nadipai();
} else {
$.notify('all', {
eventTag : 'onQiangdizhu',
from : me,
fen : pai.fen,
});
}
$('#jiaofen').hide();
},
nadipai : function() {
for (var i = pai.cards.length - 3; i < pai.cards.length; i++) {
var card = {};
$.extend(card, pai.cards[i]);
card.dx = 30 + pai.mycards.length * 25;
card.dy = 60;
pai.mycards.push(card);
$('$desk').entity(card.name, card).res('porker');
}
game.paixu();
$('#chupai').show();
},
buchu : function() {
$('#chupai').hide();
$.notify('all', {
eventTag : 'onChupai',
from : pai.me,
});
},
chupai : function() {
game.clearShangJiaPai();
game.clearZiJiChuPai();
for (var i = 0; i < pai.mycards.length; i++) {
var card = pai.mycards[i];
if (card.dy == 200) {
pai.mycards.splice(i, 1);
pai.zijichupai.push(card);
}
}
if (chupaiArr.length > 0) {
$.notify('all', {
eventTag : 'onChupai',
from : pai.me,
chupai : pai.zijichupai,
});
} else {
alert("选择要出的牌");
}
for (var i = 0; i < pai.zijichupai.length; i++) {
var card = pai.zijichupai[i];
card.dx = 150;
card.dy = 180;
$('#desk').entity(card.name).animation().to({
dx : 150,
dy : 180
}, 200).start();
}
$('#chupai').hide();
},
tishi : function() {
alert("this is not work");
},
clearShangJiaPai : function() {
//清除上一家的牌
for (var i = 0; i < pai.shangjiachupai.length; i++) {
$('$desk@' + pai.shangjiachupai[i].name).remove();
}
},
clearZiJiChuPai : function() {
//清除上一家的牌
for (var i = 0; i < pai.zijichupai.length; i++) {
$('$desk@' + pai.zijichupai[i].name).remove();
}
pai.zijichupai = [];
}
};
function onready() {
if (pai.position === 0) {
game.xipai();
$.lc.notify('all', {
eventTag : 'onFapai',
from : pai.me,
cards : pai.cards,
});
game.fapai();
}
}
$.addRemoteEventListener('onFapai', function(data) {
pai.cards = data.cards;
if (pai.right.position > pai.me.position) {
pai.position = 1;
pai.left.position = 0;
pai.right.position = 2;
} else {
pai.position = 2;
pai.left.position = 1;
pai.right.position = 0;
}
//发牌前先洗牌
pai.mycards = $.minePorker(pai.cards, pai.position, 3, 51);
//领取自己的牌
game.fapai();
});
$.addRemoteEventListener('onDizhuOK', function(data) {
pai.dizhu = data.dizhu;
$('#log').html("onDizhuOK,data:" + JSON.stringify(data));
});
$.addRemoteEventListener('onQiangdizhu', function(data) {
var num = data.fen;
for (var i = 0; i < num; i++) {
$('#fen' + i).hide();
}
if (data.from.position == pai.me.position - 1) {
$('#jiaofen').show();
}
});
$.addRemoteEventListener('onChupai', function(data) {
pai.shangjiachupai = data.chupai;
if (data.from.position === pai.me.position - 1) {
$('#chupai').show();
}
alert(JSON.stringify(data));
});
$(function() {
$("#test").canvas('desk');
$.lc.ready();
});
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M4 15h16v-2H4v2zm0 4h16v-2H4v2zm0-8h16V9H4v2zm0-6v2h16V5H4z" />
, 'ViewHeadlineOutlined');
|
// Your @RESOURCE@ with some dummy attributes..
@APP@.@CRESOURCE@ = Ember.Object.extend({
stringAttr : '',
referenceAttr : null,
integerAttr: 0,
booleanAttr: false,
clone : function(target) {
this.set('stringAttr',target.stringAttr);
this.set('referenceAttr',target.referenceAttr);
this.set('integerAttr',target.integerAttr);
this.set('booleanAttr',target.booleanAttr);
},
verifyStringAttr : function() {
return (/test/).test(this.stringAttr)===false;
},
save : function() {
var self = this;
return jQuery.ajax({
url: '/@RESOURCE@s' + (this._id !== undefined ? '/'+this._id : ''),
data: {@RESOURCE@ : {
stringAttr : this.stringAttr,
referenceAttr : this.referenceAttr === null ? null : this.referenceAttr.id,
booleanAttr : this.booleanAttr,
integerAttr : this.integerAttr
}},
dataType: 'json',
type: (this._id === undefined ? 'POST' : 'PUT')
}).done( function(obj) {
if (obj) {
if (self._id === undefined)
self._id = obj._id;
}
});
},
destroy : function() {
return jQuery.ajax({
url: '/@RESOURCE@s/' + this._id,
dataType: 'json',
type: 'DELETE'
});
}
});
|
'use strict';
import gulp from 'gulp';
import plugins from 'gulp-load-plugins';
import yargs from 'yargs';
import fs from 'fs';
import panini from 'panini';
import yaml from 'js-yaml';
import async from 'async';
import path from 'path';
// Load all Gulp plugins into one variable
const $ = plugins();
const { COMPATIBILITY, PORT, UNCSS_OPTIONS, PATHS } = loadConfig();
// Check for --production flag
const PRODUCTION = !!(yargs.argv.production);
function loadConfig() {
let ymlFile = fs.readFileSync('config.yml', 'utf8');
return yaml.load(ymlFile);
}
function kitYaml(kits, prefix, datafile, cb) {
async.eachOf(kits, (kit, name, callback) => {
var obj = {total: kit.total, blocks: kit.blocks};
obj.filename = name + '.html'
obj.datafile = datafile;
obj.datakey = name;
obj.blocks = kit.blocks
var str = "---\n" + yaml.safeDump(obj) + "---\n"
fs.writeFile(PATHS.build + "/" + prefix + obj.filename, str, callback)
}, cb)
}
// Resets Panini so that we can assemble using different layouts for the iframes and building block pages
function getNewPanini(options) {
var p = new panini.Panini(options);
p.loadBuiltinHelpers();
p.refresh();
return p.render()
}
function defaultTemplate(filename, blockname) {
var text= '<div class="{{#if block.containerClass}}{{block.containerClass}}{{else}}row column container-padded{{/if}}">{{> ' + blockname + '}}</div>'
var src = require('stream').Readable({ objectMode: true })
src._read = function () {
this.push(new $.util.File({
cwd: "",
base: "",
path: filename,
contents: new Buffer(text)
}))
this.push(null)
}
return src
}
// Create building block layouts
function buildingBlockFrameLayouts() {
return gulp.src(['src/building-blocks/*', '!src/building-blocks/*.scss'])
.pipe($.foreach(function(stream, file) {
var fileName = file.path.substr(file.path.lastIndexOf(path.sep) + 1);
var layout = file.path + "/layout.html";
if (fs.existsSync(layout)) {
return gulp.src(layout)
.pipe($.rename(function(path) {
path.basename = fileName;
}))
.pipe(gulp.dest(PATHS.build + '/blocks/'));
} else {
return defaultTemplate(fileName + '.html', fileName)
.pipe(gulp.dest(PATHS.build + '/blocks/'));
}
}));
}
// Create a building block
function buildingBlockIframe() {
return gulp.src(PATHS.build + '/blocks/*.{html,hbs,handlebars}')
.pipe(getNewPanini({
root: PATHS.build,
layouts: 'src/layouts/building-blocks/iframe/',
partials: 'src/building-blocks/*',
data: ['src/data/', PATHS.build + '/data'],
helpers: 'src/panini-helpers/'
}))
.pipe($.rename(function (path) {
path.basename += "-iframe";
}))
.pipe($.if(PRODUCTION, $.revTimestamp()))
.pipe(gulp.dest(PATHS.dist + "/blocks/"));
}
// Compiles the building block pages
function buildingBlockPage() {
return gulp.src(PATHS.build + '/blocks/*.{html,hbs,handlebars}')
.pipe(getNewPanini({
root: PATHS.build,
layouts: 'src/layouts/building-blocks/page/',
partials: 'src/partials',
data: ['src/data/', PATHS.build + '/data'],
helpers: 'src/panini-helpers/'
}))
.pipe($.if(PRODUCTION, $.revTimestamp()))
.pipe(gulp.dest(PATHS.dist + "/blocks/"));
}
function kitsStarters(cb) {
var kits = JSON.parse(fs.readFileSync(PATHS.build + '/data/kits.json', 'utf8'));
fs.mkdir(PATHS.build + '/kits', () => {kitYaml(kits, 'kits/', 'kits.json', cb)})
}
// Compiles the building block pages
function kitsPages() {
return gulp.src(PATHS.build + '/kits/*.{html,hbs,handlebars}')
.pipe(getNewPanini({
root: PATHS.build,
layouts: 'src/layouts/kits/page/',
partials: 'src/partials',
data: ['src/data/', PATHS.build + '/data'],
helpers: 'src/panini-helpers/'
}))
.pipe($.if(PRODUCTION, $.revTimestamp()))
.pipe(gulp.dest(PATHS.dist + "/kits/"));
}
gulp.task('kits-pages', gulp.series(kitsStarters, kitsPages));
gulp.task('building-block-pages', gulp.series(buildingBlockFrameLayouts, buildingBlockIframe, buildingBlockPage));
|
/*
Logfella
Copyright (c) 2015 - 2019 Cédric Ronvel
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
"use strict" ;
const CommonTransport = require( 'logfella-common-transport' ) ;
const Promise = require( 'seventh' ) ;
function ConsoleTransport( logger , config = {} ) {
CommonTransport.call( this , logger , config ) ;
this.color = config.color === undefined ? true : !! config.color ;
this.indent = config.indent === undefined ? true : !! config.indent ;
this.symbol = !! ( config.symbol && this.color ) ;
this.includeIdMeta = !! config.includeIdMeta ;
this.includeCommonMeta = config.includeCommonMeta === undefined ? true : !! config.includeCommonMeta ;
this.includeUserMeta = config.includeUserMeta === undefined ? true : !! config.includeUserMeta ;
this.output = config.output ;
this.output =
this.output === 'stderr' ? process.stderr :
//this.output === 'stdout' ? process.stdout :
process.stdout ;
}
module.exports = ConsoleTransport ;
ConsoleTransport.prototype = Object.create( CommonTransport.prototype ) ;
ConsoleTransport.prototype.constructor = ConsoleTransport ;
ConsoleTransport.prototype.transport = function( data , cache ) {
// TTY are synchronous
if ( this.output.isTTY ) {
this.output.write( this.messageFormatter( data , cache ) + '\n' ) ;
return Promise.resolved ;
}
// Otherwise it is asynchronous
return new Promise( resolve => {
// We don't care about failure at all
this.output.write( this.messageFormatter( data , cache ) + '\n' , () => resolve() ) ;
} ) ;
} ;
|
/*jshint -W106*/
'use strict';
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/weather', function (err, db) {
if (err) {
throw err;
}
db.collection('data')
.find({})
.sort([
['State', 1],
['Temperature', -1]
])
.toArray(function (err, docs) {
var state = '';
var month_highs = [];
for (var i = 0; i < docs.length; i++) {
//We are transitioning to a new state
if (state !== docs[i].State) {
month_highs.push(docs[i]);
}
state = docs[i].State;
}
var numCallbacks = 0;
for (i = 0; i < month_highs.length; i++) {
db.collection('data').update(month_highs[i], {
'$set': {
'month_high': true
}
},
function (err, updated) {
if (err) {
throw err;
}
console.log('Updated: ' + updated + 'document month high');
if (++numCallbacks === month_highs.length) {
return db.close();
}
});
}
});
});
|
#!/usr/local/bin/node
var fs = require('fs');
var util = require('util');
// Default config values
var rc = require('rc')('fh-amqp-js', {
maxReconnectAttempts: 10
});
var fhamqpjs = require('./lib/amqpjs.js');
function usage() {
console.log("Usage: fh-amqp-js pub <exchange> <topic> <message> --clusterNodes=[<amqp-url>,*]\n"
+ "fh-amqp-js sub <exchange> <topic> --clusterNodes=[<amqp-url>,*]\n");
process.exit(1);
};
var cmd = rc._[0];
if (!cmd) usage();
if (cmd !== 'pub' && cmd !== 'sub') usage();
if (cmd === 'pub') {
if (rc._.length !== 4) usage();
var amqpManager = new fhamqpjs.AMQPManager(rc);
amqpManager.on("error", function(err){
fatal(err);
});
amqpManager.connectToCluster();
amqpManager.on("connection", function(){
amqpManager.publishTopic(rc._[1], rc._[2], JSON.parse(rc._[3]), function(err){
if(err) fatal(err);
amqpManager.disconnect();
});
});
}
if (cmd === 'sub') {
if (rc._.length < 2) usage();
var amqpManager = new fhamqpjs.AMQPManager(rc);
amqpManager.on("error", function(err){
fatal(err);
});
amqpManager.connectToCluster();
amqpManager.on("connection", function(){
var opts = {
autoDelete: true,
durable: false
};
var q = "fh-amqp-js-cli-" + new Date().getTime();
amqpManager.subscribeToTopic(rc._[1], q, rc._[2], subscribeFunc, opts, function(err){
if(err) fatal(err);
});
});
function subscribeFunc (json, headers, deliveryInfo) {
console.log(json);
};
}
function fatal(msg) {
console.error(msg);
process.exit(1);
};
|
/*!
* jQuery Form Plugin
* version: 2.86 (08-OCT-2011)
* @requires jQuery v1.3.2 or later
*
* Examples and documentation at: http://malsup.com/jquery/form/
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
; (function ($) {
/*
Usage Note:
-----------
Do not use both ajaxSubmit and ajaxForm on the same form. These
functions are intended to be exclusive. Use ajaxSubmit if you want
to bind your own submit handler to the form. For example,
$(document).ready(function() {
$('#myForm').bind('submit', function(e) {
e.preventDefault(); // <-- important
$(this).ajaxSubmit({
target: '#output'
});
});
});
Use ajaxForm when you want the plugin to manage all the event binding
for you. For example,
$(document).ready(function() {
$('#myForm').ajaxForm({
target: '#output'
});
});
When using ajaxForm, the ajaxSubmit function will be invoked for you
at the appropriate time.
*/
/**
* ajaxSubmit() provides a mechanism for immediately submitting
* an HTML form using AJAX.
*/
$.fn.ajaxSubmit = function (options) {
// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
var method, action, url, $form = this;
if (typeof options == 'function') {
options = { success: options };
}
method = this.attr('method');
action = this.attr('action');
url = (typeof action === 'string') ? $.trim(action) : '';
url = url || window.location.href || '';
if (url) {
// clean url (don't include hash vaue)
url = (url.match(/^([^#]+)/) || [])[1];
}
options = $.extend(true, {
url: url,
success: $.ajaxSettings.success,
type: method || 'GET',
iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
}, options);
// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinyMCE or FCKEditor
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
// provide opportunity to alter form data before it is serialized
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var traditional = options.traditional;
if (traditional === undefined) {
traditional = $.ajaxSettings.traditional;
}
var qx, n, v, a = this.formToArray(options.semantic);
if (options.data) {
options.extraData = options.data;
qx = $.param(options.data, traditional);
}
// give pre-submit callback an opportunity to abort the submit
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
// fire vetoable 'validate' event
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a, traditional);
if (qx)
q = (q ? (q + '&' + qx) : qx);
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null; // data is null for 'get'
}
else {
options.data = q; // data is the query string for 'post'
}
var callbacks = [];
if (options.resetForm) {
callbacks.push(function () { $form.resetForm(); });
}
if (options.clearForm) {
callbacks.push(function () { $form.clearForm(); });
}
// perform a load on the target only if dataType is not provided
if (!options.dataType && options.target) {
var oldSuccess = options.success || function () { };
callbacks.push(function (data) {
var fn = options.replaceTarget ? 'replaceWith' : 'html';
$(options.target)[fn](data).each(oldSuccess, arguments);
});
}
else if (options.success) {
callbacks.push(options.success);
}
options.success = function (data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
var context = options.context || options; // jQuery 1.4+ supports scope context
for (var i = 0, max = callbacks.length; i < max; i++) {
callbacks[i].apply(context, [data, status, xhr || $form, $form]);
}
};
// are there files to upload?
var fileInputs = $('input:file', this).length > 0;
var mp = 'multipart/form-data';
var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
// options.iframe allows user to force iframe mode
// 06-NOV-09: now defaulting to iframe mode if file input is detected
if (options.iframe !== false && (fileInputs || options.iframe || multipart)) {
// hack to fix Safari hang (thanks to Tim Molendijk for this)
// see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
if (options.closeKeepAlive) {
$.get(options.closeKeepAlive, function () { fileUpload(a); });
}
else {
fileUpload(a);
}
}
else {
// IE7 massage (see issue 57)
if ($.browser.msie && method == 'get' && typeof options.type === "undefined") {
var ieMeth = $form[0].getAttribute('method');
if (typeof ieMeth === 'string')
options.type = ieMeth;
}
$.ajax(options);
}
// fire 'notify' event
this.trigger('form-submit-notify', [this, options]);
return this;
// private function for handling file uploads (hat tip to YAHOO!)
function fileUpload(a) {
var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;
var useProp = !!$.fn.prop;
if (a) {
if (useProp) {
// ensure that every serialized input is still enabled
for (i = 0; i < a.length; i++) {
el = $(form[a[i].name]);
el.prop('disabled', false);
}
} else {
for (i = 0; i < a.length; i++) {
el = $(form[a[i].name]);
el.removeAttr('disabled');
}
};
}
if ($(':input[name=submit],:input[id=submit]', form).length) {
// if there is an input with a name or id of 'submit' then we won't be
// able to invoke the submit fn on the form (at least not x-browser)
alert('Error: Form elements must not have name or id of "submit".');
return;
}
s = $.extend(true, {}, $.ajaxSettings, options);
s.context = s.context || s;
id = 'jqFormIO' + (new Date().getTime());
if (s.iframeTarget) {
$io = $(s.iframeTarget);
n = $io.attr('name');
if (n == null)
$io.attr('name', id);
else
id = n;
}
else {
$io = $('<iframe name="' + id + '" src="' + s.iframeSrc + '" />');
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
}
io = $io[0];
xhr = { // mock object
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function () { },
getResponseHeader: function () { },
setRequestHeader: function () { },
abort: function (status) {
var e = (status === 'timeout' ? 'timeout' : 'aborted');
log('aborting upload... ' + e);
this.aborted = 1;
$io.attr('src', s.iframeSrc); // abort op in progress
xhr.error = e;
s.error && s.error.call(s.context, xhr, e, status);
g && $.event.trigger("ajaxError", [xhr, s, e]);
s.complete && s.complete.call(s.context, xhr, e);
}
};
g = s.global;
// trigger ajax global events so that activity/block indicators work like normal
if (g && !$.active++) {
$.event.trigger("ajaxStart");
}
if (g) {
$.event.trigger("ajaxSend", [xhr, s]);
}
if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
if (s.global) {
$.active--;
}
return;
}
if (xhr.aborted) {
return;
}
// add submitting element to data if we know it
sub = form.clk;
if (sub) {
n = sub.name;
if (n && !sub.disabled) {
s.extraData = s.extraData || {};
s.extraData[n] = sub.value;
if (sub.type == "image") {
s.extraData[n + '.x'] = form.clk_x;
s.extraData[n + '.y'] = form.clk_y;
}
}
}
var CLIENT_TIMEOUT_ABORT = 1;
var SERVER_ABORT = 2;
function getDoc(frame) {
var doc = frame.contentWindow ? frame.contentWindow.document : frame.contentDocument ? frame.contentDocument : frame.document;
return doc;
}
// take a breath so that pending repaints get some cpu time before the upload starts
function doSubmit() {
// make sure form attrs are set
var t = $form.attr('target'), a = $form.attr('action');
// update form attrs in IE friendly way
form.setAttribute('target', id);
if (!method) {
form.setAttribute('method', 'POST');
}
if (a != s.url) {
form.setAttribute('action', s.url);
}
// ie borks in some cases when setting encoding
if (!s.skipEncodingOverride && (!method || /post/i.test(method))) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
// support timout
if (s.timeout) {
timeoutHandle = setTimeout(function () { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
}
// look for server aborts
function checkState() {
try {
var state = getDoc(io).readyState;
log('state = ' + state);
if (state.toLowerCase() == 'uninitialized')
setTimeout(checkState, 50);
}
catch (e) {
log('Server abort: ', e, ' (', e.name, ')');
cb(SERVER_ABORT);
timeoutHandle && clearTimeout(timeoutHandle);
timeoutHandle = undefined;
}
}
// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (s.extraData) {
for (var n in s.extraData) {
extraInputs.push(
$('<input type="hidden" name="' + n + '" />').attr('value', s.extraData[n])
.appendTo(form)[0]);
}
}
if (!s.iframeTarget) {
// add iframe to doc and submit the form
$io.appendTo('body');
io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
}
setTimeout(checkState, 15);
form.submit();
}
finally {
// reset attrs and remove "extra" input elements
form.setAttribute('action', a);
if (t) {
form.setAttribute('target', t);
} else {
$form.removeAttr('target');
}
$(extraInputs).remove();
}
}
if (s.forceSync) {
doSubmit();
}
else {
setTimeout(doSubmit, 10); // this lets dom updates render
}
var data, doc, domCheckCount = 50, callbackProcessed;
function cb(e) {
if (xhr.aborted || callbackProcessed) {
return;
}
try {
doc = getDoc(io);
}
catch (ex) {
log('cannot access response document: ', ex);
e = SERVER_ABORT;
}
if (e === CLIENT_TIMEOUT_ABORT && xhr) {
xhr.abort('timeout');
return;
}
else if (e == SERVER_ABORT && xhr) {
xhr.abort('server abort');
return;
}
if (!doc || doc.location.href == s.iframeSrc) {
// response not received yet
if (!timedOut)
return;
}
io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
var status = 'success', errMsg;
try {
if (timedOut) {
throw 'timeout';
}
var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
log('isXml=' + isXml);
if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) {
if (--domCheckCount) {
// in some browsers (Opera) the iframe DOM is not always traversable when
// the onload callback fires, so we loop a bit to accommodate
log('requeing onLoad callback, DOM not available');
setTimeout(cb, 250);
return;
}
// let this fall through because server response could be an empty document
//log('Could not access iframe DOM after mutiple tries.');
//throw 'DOMException: not available';
}
//log('response detected');
var docRoot = doc.body ? doc.body : doc.documentElement;
xhr.responseText = docRoot ? docRoot.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
if (isXml)
s.dataType = 'xml';
xhr.getResponseHeader = function (header) {
var headers = { 'content-type': s.dataType };
return headers[header];
};
// support for XHR 'status' & 'statusText' emulation :
if (docRoot) {
xhr.status = Number(docRoot.getAttribute('status')) || xhr.status;
xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
}
var dt = (s.dataType || '').toLowerCase();
var scr = /(json|script|text)/.test(dt);
if (scr || s.textarea) {
// see if user embedded response in textarea
var ta = doc.getElementsByTagName('textarea')[0];
if (ta) {
xhr.responseText = ta.value;
// support for XHR 'status' & 'statusText' emulation :
xhr.status = Number(ta.getAttribute('status')) || xhr.status;
xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
}
else if (scr) {
// account for browsers injecting pre around json response
var pre = doc.getElementsByTagName('pre')[0];
var b = doc.getElementsByTagName('body')[0];
if (pre) {
xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;
}
else if (b) {
xhr.responseText = b.textContent ? b.textContent : b.innerText;
}
}
}
else if (dt == 'xml' && !xhr.responseXML && xhr.responseText != null) {
xhr.responseXML = toXml(xhr.responseText);
}
try {
data = httpData(xhr, dt, s);
}
catch (e) {
status = 'parsererror';
xhr.error = errMsg = (e || status);
}
}
catch (e) {
log('error caught: ', e);
status = 'error';
xhr.error = errMsg = (e || status);
}
if (xhr.aborted) {
log('upload aborted');
status = null;
}
if (xhr.status) { // we've set xhr.status
status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
}
// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
if (status === 'success') {
s.success && s.success.call(s.context, data, 'success', xhr);
g && $.event.trigger("ajaxSuccess", [xhr, s]);
}
else if (status) {
if (errMsg == undefined)
errMsg = xhr.statusText;
s.error && s.error.call(s.context, xhr, status, errMsg);
g && $.event.trigger("ajaxError", [xhr, s, errMsg]);
}
g && $.event.trigger("ajaxComplete", [xhr, s]);
if (g && ! --$.active) {
$.event.trigger("ajaxStop");
}
s.complete && s.complete.call(s.context, xhr, status);
callbackProcessed = true;
if (s.timeout)
clearTimeout(timeoutHandle);
// clean up
setTimeout(function () {
if (!s.iframeTarget)
$io.remove();
xhr.responseXML = null;
}, 100);
}
var toXml = $.parseXML || function (s, doc) { // use parseXML if available (jQuery 1.5+)
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else {
doc = (new DOMParser()).parseFromString(s, 'text/xml');
}
return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
};
var parseJSON = $.parseJSON || function (s) {
return window['eval']('(' + s + ')');
};
var httpData = function (xhr, type, s) { // mostly lifted from jq1.4.4
var ct = xhr.getResponseHeader('content-type') || '',
xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if (xml && data.documentElement.nodeName === 'parsererror') {
$.error && $.error('parsererror');
}
if (s && s.dataFilter) {
data = s.dataFilter(data, type);
}
if (typeof data === 'string') {
if (type === 'json' || !type && ct.indexOf('json') >= 0) {
data = parseJSON(data);
} else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
$.globalEval(data);
}
}
return data;
};
}
};
/**
* ajaxForm() provides a mechanism for fully automating form submission.
*
* The advantages of using this method instead of ajaxSubmit() are:
*
* 1: This method will include coordinates for <input type="image" /> elements (if the element
* is used to submit the form).
* 2. This method will include the submit element's name/value data (for the element that was
* used to submit the form).
* 3. This method binds the submit() method to the form for you.
*
* The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
* passes the options argument along after properly binding events for submit elements and
* the form itself.
*/
$.fn.ajaxForm = function (options) {
// in jQuery 1.3+ we can fix mistakes with the ready state
if (this.length === 0) {
var o = { s: this.selector, c: this.context };
if (!$.isReady && o.s) {
log('DOM not ready, queuing ajaxForm');
$(function () {
$(o.s, o.c).ajaxForm(options);
});
return this;
}
// is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
return this;
}
return this.ajaxFormUnbind().bind('submit.form-plugin', function (e) {
if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
e.preventDefault();
$(this).ajaxSubmit(options);
}
}).bind('click.form-plugin', function (e) {
var target = e.target;
var $el = $(target);
if (!($el.is(":submit,input:image"))) {
// is this a child element of the submit el? (ex: a span within a button)
var t = $el.closest(':submit');
if (t.length == 0) {
return;
}
target = t[0];
}
var form = this;
form.clk = target;
if (target.type == 'image') {
if (e.offsetX != undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
var offset = $el.offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - target.offsetLeft;
form.clk_y = e.pageY - target.offsetTop;
}
}
// clear form vars
setTimeout(function () { form.clk = form.clk_x = form.clk_y = null; }, 100);
});
};
// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function () {
return this.unbind('submit.form-plugin click.form-plugin');
};
/**
* formToArray() gathers form element data into an array of objects that can
* be passed to any of the following ajax functions: $.get, $.post, or load.
* Each object in the array has both a 'name' and 'value' property. An example of
* an array for a simple login form might be:
*
* [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
*
* It is this array that is passed to pre-submit callback functions provided to the
* ajaxSubmit() and ajaxForm() methods.
*/
$.fn.formToArray = function (semantic) {
var a = [];
if (this.length === 0) {
return a;
}
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) {
return a;
}
var i, j, n, v, el, max, jmax;
for (i = 0, max = els.length; i < max; i++) {
el = els[i];
n = el.name;
if (!n) {
continue;
}
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if (!el.disabled && form.clk == el) {
a.push({ name: n, value: $(el).val() });
a.push({ name: n + '.x', value: form.clk_x }, { name: n + '.y', value: form.clk_y });
}
continue;
}
v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
for (j = 0, jmax = v.length; j < jmax; j++) {
a.push({ name: n, value: v[j] });
}
}
else if (v !== null && typeof v != 'undefined') {
a.push({ name: n, value: v });
}
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle it here
var $input = $(form.clk), input = $input[0];
n = input.name;
if (n && !input.disabled && input.type == 'image') {
a.push({ name: n, value: $input.val() });
a.push({ name: n + '.x', value: form.clk_x }, { name: n + '.y', value: form.clk_y });
}
}
return a;
};
/**
* Serializes form data into a 'submittable' string. This method will return a string
* in the format: name1=value1&name2=value2
*/
$.fn.formSerialize = function (semantic) {
//hand off to jQuery.param for proper encoding
return $.param(this.formToArray(semantic));
};
/**
* Serializes all field elements in the jQuery object into a query string.
* This method will return a string in the format: name1=value1&name2=value2
*/
$.fn.fieldSerialize = function (successful) {
var a = [];
this.each(function () {
var n = this.name;
if (!n) {
return;
}
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i = 0, max = v.length; i < max; i++) {
a.push({ name: n, value: v[i] });
}
}
else if (v !== null && typeof v != 'undefined') {
a.push({ name: this.name, value: v });
}
});
//hand off to jQuery.param for proper encoding
return $.param(a);
};
/**
* Returns the value(s) of the element in the matched set. For example, consider the following form:
*
* <form><fieldset>
* <input name="A" type="text" />
* <input name="A" type="text" />
* <input name="B" type="checkbox" value="B1" />
* <input name="B" type="checkbox" value="B2"/>
* <input name="C" type="radio" value="C1" />
* <input name="C" type="radio" value="C2" />
* </fieldset></form>
*
* var v = $(':text').fieldValue();
* // if no values are entered into the text inputs
* v == ['','']
* // if values entered into the text inputs are 'foo' and 'bar'
* v == ['foo','bar']
*
* var v = $(':checkbox').fieldValue();
* // if neither checkbox is checked
* v === undefined
* // if both checkboxes are checked
* v == ['B1', 'B2']
*
* var v = $(':radio').fieldValue();
* // if neither radio is checked
* v === undefined
* // if first radio is checked
* v == ['C1']
*
* The successful argument controls whether or not the field element must be 'successful'
* (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
* The default value of the successful argument is true. If this value is false the value(s)
* for each element is returned.
*
* Note: This method *always* returns an array. If no valid value can be determined the
* array will be empty, otherwise it will contain one or more values.
*/
$.fn.fieldValue = function (successful) {
for (var val = [], i = 0, max = this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
continue;
}
v.constructor == Array ? $.merge(val, v) : val.push(v);
}
return val;
};
/**
* Returns the value of the field element.
*/
$.fieldValue = function (el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (successful === undefined) {
successful = true;
}
if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1)) {
return null;
}
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) {
return null;
}
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index + 1 : ops.length);
for (var i = (one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = op.value;
if (!v) { // extra pain for IE...
v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
}
if (one) {
return v;
}
a.push(v);
}
}
return a;
}
return $(el).val();
};
/**
* Clears the form data. Takes the following actions on the form's input fields:
* - input text fields will have their 'value' property set to the empty string
* - select elements will have their 'selectedIndex' property set to -1
* - checkbox and radio inputs will have their 'checked' property set to false
* - inputs of type submit, button, reset, and hidden will *not* be effected
* - button elements will *not* be effected
*/
$.fn.clearForm = function () {
return this.each(function () {
$('input,select,textarea', this).clearFields();
});
};
/**
* Clears the selected form elements.
*/
$.fn.clearFields = $.fn.clearInputs = function () {
var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
return this.each(function () {
var t = this.type, tag = this.tagName.toLowerCase();
if (re.test(t) || tag == 'textarea') {
this.value = '';
}
else if (t == 'checkbox' || t == 'radio') {
this.checked = false;
}
else if (tag == 'select') {
this.selectedIndex = -1;
}
});
};
/**
* Resets the form data. Causes all form elements to be reset to their original value.
*/
$.fn.resetForm = function () {
return this.each(function () {
// guard against an input with the name of 'reset'
// note that IE reports the reset function as an 'object'
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
this.reset();
}
});
};
/**
* Enables or disables any matching elements.
*/
$.fn.enable = function (b) {
if (b === undefined) {
b = true;
}
return this.each(function () {
this.disabled = !b;
});
};
/**
* Checks/unchecks any matching checkboxes or radio buttons and
* selects/deselects and matching option elements.
*/
$.fn.selected = function (select) {
if (select === undefined) {
select = true;
}
return this.each(function () {
var t = this.type;
if (t == 'checkbox' || t == 'radio') {
this.checked = select;
}
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
});
};
// expose debug var
$.fn.ajaxSubmit.debug = false;
// helper fn for console logging
function log() {
if (!$.fn.ajaxSubmit.debug)
return;
var msg = '[jquery.form] ' + Array.prototype.join.call(arguments, '');
if (window.console && window.console.log) {
window.console.log(msg);
}
else if (window.opera && window.opera.postError) {
window.opera.postError(msg);
}
};
})(jQuery);
|
import mq from 'mithril-query';
import m from 'mithril';
import subscriptionStatusIcon from '../../src/c/subscription-status-icon';
import dashboardSubscriptionCard from '../../src/c/dashboard-subscription-card';
import moment from 'moment';
describe('ShowDateFromSubscriptionTransition', () => {
let $subscription, $output, $subscription2, $output2;
beforeAll(() => {
$subscription = SubscriptionMockery()[1];
$output = mq(m(subscriptionStatusIcon, {subscription:$subscription}));
$subscription2 = SubscriptionMockery()[2];
$output2 = mq(m(dashboardSubscriptionCard, {subscription: $subscription2, user: {name: 'Test Name', profile_img_thumbnail: 'none'}}));
});
it('Should show subscription transition date', () => {
let dateString = moment($subscription.transition_date).format('DD/MM/YYYY');
expect($output.contains(dateString)).toBeTrue();
});
it ('Should show subscription last payment data date', () => {
let lastPaymentDate = moment($subscription2.last_payment_data_created_at).format('DD/MM/YYYY');
expect($output2.contains(lastPaymentDate)).toBeTrue();
});
});
|
//! moment-timezone.js
//! version : 0.4.1
//! author : Tim Wood
//! license : MIT
//! github.com/moment/moment-timezone
(function (root, factory) {
"use strict";
/*global define*/
if (typeof define === 'function' && define.amd) {
define(['moment'], factory); // AMD
} else if (typeof exports === 'object') {
module.exports = factory(require('moment')); // Node
} else {
factory(root.moment); // Browser
}
}(this, function (moment) {
"use strict";
// Do not load moment-timezone a second time.
if (moment.tz !== undefined) {
logError('Moment Timezone ' + moment.tz.version + ' was already loaded ' + (moment.tz.dataVersion ? 'with data from ' : 'without any data') + moment.tz.dataVersion);
return moment;
}
var VERSION = "0.4.1",
zones = {},
links = {},
names = {},
momentVersion = moment.version.split('.'),
major = +momentVersion[0],
minor = +momentVersion[1];
// Moment.js version check
if (major < 2 || (major === 2 && minor < 6)) {
logError('Moment Timezone requires Moment.js >= 2.6.0. You are using Moment.js ' + moment.version + '. See momentjs.com');
}
/************************************
Unpacking
************************************/
function charCodeToInt(charCode) {
if (charCode > 96) {
return charCode - 87;
} else if (charCode > 64) {
return charCode - 29;
}
return charCode - 48;
}
function unpackBase60(string) {
var i = 0,
parts = string.split('.'),
whole = parts[0],
fractional = parts[1] || '',
multiplier = 1,
num,
out = 0,
sign = 1;
// handle negative numbers
if (string.charCodeAt(0) === 45) {
i = 1;
sign = -1;
}
// handle digits before the decimal
for (i; i < whole.length; i++) {
num = charCodeToInt(whole.charCodeAt(i));
out = 60 * out + num;
}
// handle digits after the decimal
for (i = 0; i < fractional.length; i++) {
multiplier = multiplier / 60;
num = charCodeToInt(fractional.charCodeAt(i));
out += num * multiplier;
}
return out * sign;
}
function arrayToInt (array) {
for (var i = 0; i < array.length; i++) {
array[i] = unpackBase60(array[i]);
}
}
function intToUntil (array, length) {
for (var i = 0; i < length; i++) {
array[i] = Math.round((array[i - 1] || 0) + (array[i] * 60000)); // minutes to milliseconds
}
array[length - 1] = Infinity;
}
function mapIndices (source, indices) {
var out = [], i;
for (i = 0; i < indices.length; i++) {
out[i] = source[indices[i]];
}
return out;
}
function unpack (string) {
var data = string.split('|'),
offsets = data[2].split(' '),
indices = data[3].split(''),
untils = data[4].split(' ');
arrayToInt(offsets);
arrayToInt(indices);
arrayToInt(untils);
intToUntil(untils, indices.length);
return {
name : data[0],
abbrs : mapIndices(data[1].split(' '), indices),
offsets : mapIndices(offsets, indices),
untils : untils
};
}
/************************************
Zone object
************************************/
function Zone (packedString) {
if (packedString) {
this._set(unpack(packedString));
}
}
Zone.prototype = {
_set : function (unpacked) {
this.name = unpacked.name;
this.abbrs = unpacked.abbrs;
this.untils = unpacked.untils;
this.offsets = unpacked.offsets;
},
_index : function (timestamp) {
var target = +timestamp,
untils = this.untils,
i;
for (i = 0; i < untils.length; i++) {
if (target < untils[i]) {
return i;
}
}
},
parse : function (timestamp) {
var target = +timestamp,
offsets = this.offsets,
untils = this.untils,
max = untils.length - 1,
offset, offsetNext, offsetPrev, i;
for (i = 0; i < max; i++) {
offset = offsets[i];
offsetNext = offsets[i + 1];
offsetPrev = offsets[i ? i - 1 : i];
if (offset < offsetNext && tz.moveAmbiguousForward) {
offset = offsetNext;
} else if (offset > offsetPrev && tz.moveInvalidForward) {
offset = offsetPrev;
}
if (target < untils[i] - (offset * 60000)) {
return offsets[i];
}
}
return offsets[max];
},
abbr : function (mom) {
return this.abbrs[this._index(mom)];
},
offset : function (mom) {
return this.offsets[this._index(mom)];
}
};
/************************************
Global Methods
************************************/
function normalizeName (name) {
return (name || '').toLowerCase().replace(/\//g, '_');
}
function addZone (packed) {
var i, name, normalized;
if (typeof packed === "string") {
packed = [packed];
}
for (i = 0; i < packed.length; i++) {
name = packed[i].split('|')[0];
normalized = normalizeName(name);
zones[normalized] = packed[i];
names[normalized] = name;
}
}
function getZone (name, caller) {
name = normalizeName(name);
var zone = zones[name];
var link;
if (zone instanceof Zone) {
return zone;
}
if (typeof zone === 'string') {
zone = new Zone(zone);
zones[name] = zone;
return zone;
}
// Pass getZone to prevent recursion more than 1 level deep
if (links[name] && caller !== getZone && (link = getZone(links[name], getZone))) {
zone = zones[name] = new Zone();
zone._set(link);
zone.name = names[name];
return zone;
}
return null;
}
function getNames () {
var i, out = [];
for (i in names) {
if (names.hasOwnProperty(i) && (zones[i] || zones[links[i]]) && names[i]) {
out.push(names[i]);
}
}
return out.sort();
}
function addLink (aliases) {
var i, alias, normal0, normal1;
if (typeof aliases === "string") {
aliases = [aliases];
}
for (i = 0; i < aliases.length; i++) {
alias = aliases[i].split('|');
normal0 = normalizeName(alias[0]);
normal1 = normalizeName(alias[1]);
links[normal0] = normal1;
names[normal0] = alias[0];
links[normal1] = normal0;
names[normal1] = alias[1];
}
}
function loadData (data) {
addZone(data.zones);
addLink(data.links);
tz.dataVersion = data.version;
}
function zoneExists (name) {
if (!zoneExists.didShowError) {
zoneExists.didShowError = true;
logError("moment.tz.zoneExists('" + name + "') has been deprecated in favor of !moment.tz.zone('" + name + "')");
}
return !!getZone(name);
}
function needsOffset (m) {
return !!(m._a && (m._tzm === undefined));
}
function logError (message) {
if (typeof console !== 'undefined' && typeof console.error === 'function') {
console.error(message);
}
}
/************************************
moment.tz namespace
************************************/
function tz (input) {
var args = Array.prototype.slice.call(arguments, 0, -1),
name = arguments[arguments.length - 1],
zone = getZone(name),
out = moment.utc.apply(null, args);
if (zone && !moment.isMoment(input) && needsOffset(out)) {
out.add(zone.parse(out), 'minutes');
}
out.tz(name);
return out;
}
tz.version = VERSION;
tz.dataVersion = '';
tz._zones = zones;
tz._links = links;
tz._names = names;
tz.add = addZone;
tz.link = addLink;
tz.load = loadData;
tz.zone = getZone;
tz.zoneExists = zoneExists; // deprecated in 0.1.0
tz.names = getNames;
tz.Zone = Zone;
tz.unpack = unpack;
tz.unpackBase60 = unpackBase60;
tz.needsOffset = needsOffset;
tz.moveInvalidForward = true;
tz.moveAmbiguousForward = false;
/************************************
Interface with Moment.js
************************************/
var fn = moment.fn;
moment.tz = tz;
moment.defaultZone = null;
moment.updateOffset = function (mom, keepTime) {
var zone = moment.defaultZone,
offset;
if (mom._z === undefined) {
if (zone && needsOffset(mom) && !mom._isUTC) {
mom._d = moment.utc(mom._a)._d;
mom.utc().add(zone.parse(mom), 'minutes');
}
mom._z = zone;
}
if (mom._z) {
offset = mom._z.offset(mom);
if (Math.abs(offset) < 16) {
offset = offset / 60;
}
if (mom.utcOffset !== undefined) {
mom.utcOffset(-offset, keepTime);
} else {
mom.zone(offset, keepTime);
}
}
};
fn.tz = function (name) {
if (name) {
this._z = getZone(name);
if (this._z) {
moment.updateOffset(this);
} else {
logError("Moment Timezone has no data for " + name + ". See http://momentjs.com/timezone/docs/#/data-loading/.");
}
return this;
}
if (this._z) { return this._z.name; }
};
function abbrWrap (old) {
return function () {
if (this._z) { return this._z.abbr(this); }
return old.call(this);
};
}
function resetZoneWrap (old) {
return function () {
this._z = null;
return old.apply(this, arguments);
};
}
fn.zoneName = abbrWrap(fn.zoneName);
fn.zoneAbbr = abbrWrap(fn.zoneAbbr);
fn.utc = resetZoneWrap(fn.utc);
moment.tz.setDefault = function(name) {
if (major < 2 || (major === 2 && minor < 9)) {
logError('Moment Timezone setDefault() requires Moment.js >= 2.9.0. You are using Moment.js ' + moment.version + '.');
}
moment.defaultZone = name ? getZone(name) : null;
return moment;
};
// Cloning a moment should include the _z property.
var momentProperties = moment.momentProperties;
if (Object.prototype.toString.call(momentProperties) === '[object Array]') {
// moment 2.8.1+
momentProperties.push('_z');
momentProperties.push('_a');
} else if (momentProperties) {
// moment 2.7.0
momentProperties._z = null;
}
// INJECT DATA
return moment;
}));
|
/**
* Created by uzysjung on 15. 7. 9..
*/
var Tvconfig = {
register: require('tv'),
options: {
authenticateEndpoint:'simple',
} //authentication using hapi-auth-basic
};
module.exports = function(server) {
return new Promise(function(resolve,reject) {
server.register(Tvconfig, function(err){
if(err) {
server.log(['error', 'plugin'], 'plugin: TV register error');
reject(err);
} else {
server.log(['info', 'plugin'], 'plugin: TV registered');
resolve();
}
});
});
};
|
angular.module('pager', ['ui.router', 'ui.bootstrap', 'angular-loading-bar', 'LocalStorageModule', , 'ngAnimate', 'ngFacebook'])
.config(function($stateProvider, $urlRouterProvider, $locationProvider, $facebookProvider, localStorageServiceProvider) {
// Setup Facebook API
$facebookProvider.setAppId('1429537494015773');
$facebookProvider.setPermissions("manage_pages");
// Setup local storage
localStorageServiceProvider.setPrefix('pager');
$stateProvider
.state('app', {
abstract: true,
templateUrl: 'public/views/layout.html'
})
.state('home', {
url: '/',
title: 'Home',
templateUrl: 'public/views/index.html',
controller: 'HomeCtrl'
})
.state('app.pages', {
url: '/pages',
title: 'Pages',
views: {
'header': {
templateUrl: 'public/views/header.html',
controller: 'HeaderCtrl'
},
'content': {
templateUrl: 'public/views/pages.html',
controller: 'PagesCtrl'
},
}
})
.state('app.edit', {
url: '/pages/:id',
title: 'Edit Page',
params: { id: null },
views: {
'header': {
templateUrl: 'public/views/header.html',
controller: 'HeaderCtrl'
},
'content': {
templateUrl: 'public/views/edit.html',
controller: 'EditCtrl'
},
}
})
.state('app.site', {
url: '/sites/:id',
params: { id: null },
views: {
'content': {
templateUrl: 'public/views/site/index.html',
controller: 'SiteHomeCtrl'
},
}
})
.state('app.site-about', {
url: '/sites/:id/about',
params: { id: null },
views: {
'header': {
templateUrl: 'public/views/site/header.html',
controller: 'SiteHeaderCtrl'
},
'content': {
templateUrl: 'public/views/site/about.html',
controller: 'SiteAboutCtrl'
},
}
})
.state('app.site-news', {
url: '/sites/:id/news',
params: { id: null },
views: {
'header': {
templateUrl: 'public/views/site/header.html',
controller: 'SiteHeaderCtrl'
},
'content': {
templateUrl: 'public/views/site/news.html',
controller: 'SiteNewsCtrl'
},
}
})
.state('app.site-events', {
url: '/sites/:id/events',
params: { id: null },
views: {
'header': {
templateUrl: 'public/views/site/header.html',
controller: 'SiteHeaderCtrl'
},
'content': {
templateUrl: 'public/views/site/events.html',
controller: 'SiteEventsCtrl'
},
}
})
.state('app.site-gallery', {
url: '/sites/:id/gallery',
params: { id: null },
views: {
'header': {
templateUrl: 'public/views/site/header.html',
controller: 'SiteHeaderCtrl'
},
'content': {
templateUrl: 'public/views/site/gallery.html',
controller: 'SiteGalleryCtrl'
},
}
});
$urlRouterProvider.otherwise('/');
})
.run(function($rootScope) {
// Load the facebook SDK asynchronously
(function(){
// If we've already installed the SDK, we're done
if (document.getElementById('facebook-jssdk')) {return;}
// Get the first script element, which we'll use to find the parent node
var firstScriptElement = document.getElementsByTagName('script')[0];
// Create a new script element and set its id
var facebookJS = document.createElement('script');
facebookJS.id = 'facebook-jssdk';
// Set the new script's source to the source of the Facebook JS SDK
facebookJS.src = '//connect.facebook.net/en_US/all.js';
// Insert the Facebook JS SDK into the DOM
firstScriptElement.parentNode.insertBefore(facebookJS, firstScriptElement);
}());
});
|
import baseInRange from './_baseInRange';
import toNumber from './toNumber';
/**
* Checks if `n` is between `start` and up to, but not including, `end`. If
* `end` is not specified, it's set to `start` with `start` then set to `0`.
* If `start` is greater than `end` the params are swapped to support
* negative ranges.
*
* @static
* @memberOf _
* @since 3.3.0
* @category Number
* @param {number} number The number to check.
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @returns {boolean} Returns `true` if `number` is in the range, else `false`.
* @see _.range, _.rangeRight
* @example
*
* _.inRange(3, 2, 4);
* // => true
*
* _.inRange(4, 8);
* // => true
*
* _.inRange(4, 2);
* // => false
*
* _.inRange(2, 2);
* // => false
*
* _.inRange(1.2, 2);
* // => true
*
* _.inRange(5.2, 4);
* // => false
*
* _.inRange(-3, -2, -6);
* // => true
*/
function inRange(number, start, end) {
start = toNumber(start) || 0;
if (end === undefined) {
end = start;
start = 0;
} else {
end = toNumber(end) || 0;
}
number = toNumber(number);
return baseInRange(number, start, end);
}
export default inRange;
|
import cx from 'classnames'
import _ from 'lodash'
import PropTypes from 'prop-types'
import React, { Component } from 'react'
import {
createShorthandFactory,
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
import Button from '../../elements/Button'
/**
* A modal can contain a row of actions.
*/
export default class ModalActions extends Component {
static propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Elements to render as Modal action buttons. */
actions: customPropTypes.every([
customPropTypes.disallow(['children']),
PropTypes.arrayOf(customPropTypes.itemShorthand),
]),
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/**
* onClick handler for an action. Mutually exclusive with children.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All item props.
*/
onActionClick: customPropTypes.every([
customPropTypes.disallow(['children']),
PropTypes.func,
]),
}
static _meta = {
name: 'ModalActions',
type: META.TYPES.MODULE,
parent: 'Modal',
}
handleButtonOverrides = predefinedProps => ({
onClick: (e, buttonProps) => {
_.invoke(predefinedProps, 'onClick', e, buttonProps)
_.invoke(this.props, 'onActionClick', e, buttonProps)
},
})
render() {
const { actions, children, className } = this.props
const classes = cx('actions', className)
const rest = getUnhandledProps(ModalActions, this.props)
const ElementType = getElementType(ModalActions, this.props)
if (!_.isNil(children)) return <ElementType {...rest} className={classes}>{children}</ElementType>
return (
<ElementType {...rest} className={classes}>
{_.map(actions, action => Button.create(action, { overrideProps: this.handleButtonOverrides }))}
</ElementType>
)
}
}
ModalActions.create = createShorthandFactory(ModalActions, actions => ({ actions }))
|
/**
* Module requirements.
*/
var path = require('path');
/**
* Initialize directory stack with current working directory.
*/
var dirs = [process.cwd()];
Object.defineProperties(process, {
/**
* Pushes a directory on to the stack and changes the current working
* directory to the pushed directory. Alternately takes a number argument
* representing the index of the directory in the stack to switch to --
* this new directory is then moved to the top of the stack.
* @param {string} input The directory
* @param {number} input The index of the stack to change the current working
* directory to.
* @return {Array} The current directory stack.
* @throws {Error} Throws an {Error} if the operation fails for any reason.
*/
pushdir: {
value: function (input) {
var type = typeof input;
if (type === 'string') {
if (input[0] !== '/') {
input = path.join(process.cwd(), input);
}
process.chdir(input);
dirs.push(input);
} else if (type === 'number') {
if (input >= dirs.length || input < 0) {
throw new Error('Cannot switch to directoy index outside the range of the stack.');
}
input = Math.floor(input);
var dir = dirs.splice(input, 1)[0];
process.chdir(dir);
dirs.push(dir);
} else {
throw new Error('Illegal argument. Please use a string or a number.');
}
return dirs;
}
},
/**
* Pops the top directory off the stack and then changes the current working
* directory to the directory now on top of the stack. Alternately takes a
* number indicating the index of the directory in the stack to remove --
* the current working directory will not change in this case.
* @param {number} input Optional index indicating which directory to remove
* from the stack.
* @return {Array} The current directory stack.
* @throws {Error} Throws an {Error} if the operation fails for any reason.
*/
popdir: {
value: function (input) {
if (dirs.length === 1) {
throw new Error('Cannot pop from directory stack if it will become empty');
}
var type = typeof input;
if (type === 'undefined') {
dirs.pop();
process.chdir(dirs[dirs.length - 1]);
} else if (type === 'number') {
if (input >= dirs.length || input < 0) {
throw new Error('Cannot pop directory index outside the range of the stack.');
}
input = Math.floor(input);
dirs.splice(input, 1);
} else {
throw new Error('Illegal argument. Please use either a number or no arguments.');
}
return dirs;
}
},
/**
* Returns the current directory stack. It is possible (though not
* recommended) to mutate the stack as it is not a copy that is returned and
* the stack is a standard JavaScript {Array}.
* @param {boolean} reset Optional boolean value indicating to re-initialize
* the stack with the current working directory.
* @return {Array} The current directory stack.
*/
dirs: {
value: function (reset) {
if (reset) {
dirs = [process.cwd()];
}
return dirs;
}
}
});
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M4 5c0-1.1.9-2 2-2s2 .9 2 2-.9 2-2 2-2-.9-2-2zm4.78 3.58C7.93 8.21 6.99 8 6 8s-1.93.21-2.78.58C2.48 8.9 2 9.62 2 10.43V11h8v-.57c0-.81-.48-1.53-1.22-1.85zM18 7c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm2.78 1.58C19.93 8.21 18.99 8 18 8c-.99 0-1.93.21-2.78.58-.74.32-1.22 1.04-1.22 1.85V11h8v-.57c0-.81-.48-1.53-1.22-1.85zM22 17l-4-4v3H6v-3l-4 4 4 4v-3h12v3l4-4z"
}), 'SocialDistanceTwoTone');
exports.default = _default;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.