text
stringlengths
2
1.05M
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. goog.provide('goog.arrayTest'); goog.setTestOnly('goog.arrayTest'); goog.require('goog.array'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.jsunit'); goog.require('goog.testing.recordFunction'); function testArrayLast() { assertEquals(goog.array.last([1, 2, 3]), 3); assertEquals(goog.array.last([1]), 1); assertUndefined(goog.array.last([])); } function testArrayLastWhenDeleted() { var a = [1, 2, 3]; delete a[2]; assertUndefined(goog.array.last(a)); } function testArrayIndexOf() { assertEquals(goog.array.indexOf([0, 1, 2, 3], 1), 1); assertEquals(goog.array.indexOf([0, 1, 1, 1], 1), 1); assertEquals(goog.array.indexOf([0, 1, 2, 3], 4), -1); assertEquals(goog.array.indexOf([0, 1, 2, 3], 1, 1), 1); assertEquals(goog.array.indexOf([0, 1, 2, 3], 1, 2), -1); assertEquals(goog.array.indexOf([0, 1, 2, 3], 1, -3), 1); assertEquals(goog.array.indexOf([0, 1, 2, 3], 1, -2), -1); } function testArrayIndexOfOmitsDeleted() { var a = [0, 1, 2, 3]; delete a[1]; delete a[3]; assertEquals(goog.array.indexOf(a, undefined), -1); } function testArrayIndexOfString() { assertEquals(goog.array.indexOf('abcd', 'd'), 3); assertEquals(goog.array.indexOf('abbb', 'b', 2), 2); assertEquals(goog.array.indexOf('abcd', 'e'), -1); assertEquals(goog.array.indexOf('abcd', 'cd'), -1); assertEquals(goog.array.indexOf('0123', 1), -1); } function testArrayLastIndexOf() { assertEquals(goog.array.lastIndexOf([0, 1, 2, 3], 1), 1); assertEquals(goog.array.lastIndexOf([0, 1, 1, 1], 1), 3); assertEquals(goog.array.lastIndexOf([0, 1, 1, 1], 1, 2), 2); } function testArrayLastIndexOfOmitsDeleted() { var a = [0, 1, 2, 3]; delete a[1]; delete a[3]; assertEquals(goog.array.lastIndexOf(a, undefined), -1); } function testArrayLastIndexOfString() { assertEquals(goog.array.lastIndexOf('abcd', 'b'), 1); assertEquals(goog.array.lastIndexOf('abbb', 'b'), 3); assertEquals(goog.array.lastIndexOf('abbb', 'b', 2), 2); assertEquals(goog.array.lastIndexOf('abcd', 'cd'), -1); assertEquals(goog.array.lastIndexOf('0123', 1), -1); } function testArrayForEachBasic() { var s = ''; var a = ['a', 'b', 'c', 'd']; goog.array.forEach(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('Index is not a number', 'number', typeof index); s += val + index; }); assertEquals('a0b1c2d3', s); } function testArrayForEachWithEmptyArray() { var a = new Array(100); goog.array.forEach(a, function(val, index, a2) { fail('The function should not be called since no values were assigned.'); }); } function testArrayForEachWithOnlySomeValuesAsigned() { var count = 0; var a = new Array(1000); a[100] = undefined; goog.array.forEach(a, function(val, index, a2) { assertEquals(100, index); count++; }); assertEquals( 'Should only call function when a value of array was assigned.', 1, count); } function testArrayForEachWithArrayLikeObject() { var counter = goog.testing.recordFunction(); var a = {'length': 1, '0': 0, '100': 100, '101': 102}; goog.array.forEach(a, counter); assertEquals( 'Number of calls should not exceed the value of its length', 1, counter.getCallCount()); } function testArrayForEachOmitsDeleted() { var s = ''; var a = ['a', 'b', 'c', 'd']; delete a[1]; delete a[3]; goog.array.forEach(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('number', typeof index); s += val + index; }); assertEquals('a0c2', s); } function testArrayForEachScope() { var scope = {}; var a = ['a', 'b', 'c', 'd']; goog.array.forEach(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('number', typeof index); assertEquals(this, scope); }, scope); } function testArrayForEachRight() { var s = ''; var a = ['a', 'b', 'c', 'd']; goog.array.forEachRight(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('number', typeof index); s += val + String(index); }); assertEquals('d3c2b1a0', s); } function testArrayForEachRightOmitsDeleted() { var s = ''; var a = ['a', 'b', 'c', 'd']; delete a[1]; delete a[3]; goog.array.forEachRight(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('number', typeof index); assertEquals('string', typeof val); s += val + String(index); }); assertEquals('c2a0', s); } function testArrayFilter() { var a = [0, 1, 2, 3]; a = goog.array.filter(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val > 1; }); assertArrayEquals([2, 3], a); } function testArrayFilterOmitsDeleted() { var a = [0, 1, 2, 3]; delete a[1]; delete a[3]; a = goog.array.filter(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('number', typeof val); assertEquals('index is not a number', 'number', typeof index); return val > 1; }); assertArrayEquals([2], a); } function testArrayFilterPreservesValues() { var a = [0, 1, 2, 3]; a = goog.array.filter(a, function(val, index, a2) { assertEquals(a, a2); // sometimes functions might be evil and do something like this, but we // should still use the original values when returning the filtered array a2[index] = a2[index] - 1; return a2[index] >= 1; }); assertArrayEquals([2, 3], a); } function testArrayMap() { var a = [0, 1, 2, 3]; var result = goog.array.map(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val * val; }); assertArrayEquals([0, 1, 4, 9], result); } function testArrayMapOmitsDeleted() { var a = [0, 1, 2, 3]; delete a[1]; delete a[3]; var result = goog.array.map(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('number', typeof val); assertEquals('index is not a number', 'number', typeof index); return val * val; }); var expected = [0, 1, 4, 9]; delete expected[1]; delete expected[3]; assertArrayEquals(expected, result); assertFalse('1' in result); assertFalse('3' in result); } function testArrayReduce() { var a = [0, 1, 2, 3]; assertEquals(6, goog.array.reduce(a, function(rval, val, i, arr) { assertEquals('number', typeof i); assertEquals(a, arr); return rval + val; }, 0)); var scope = { last: 0, testFn: function(r, v, i, arr) { assertEquals('number', typeof i); assertEquals(a, arr); var l = this.last; this.last = r + v; return this.last + l; } }; assertEquals(10, goog.array.reduce(a, scope.testFn, 0, scope)); } function testArrayReduceOmitDeleted() { var a = [0, 1, 2, 3]; delete a[1]; delete a[3]; assertEquals(2, goog.array.reduce(a, function(rval, val, i, arr) { assertEquals('number', typeof i); assertEquals(a, arr); return rval + val; }, 0)); var scope = { last: 0, testFn: function(r, v, i, arr) { assertEquals('number', typeof i); assertEquals(a, arr); var l = this.last; this.last = r + v; return this.last + l; } }; assertEquals(2, goog.array.reduce(a, scope.testFn, 0, scope)); } function testArrayReduceRight() { var a = [0, 1, 2, 3, 4]; assertEquals('43210', goog.array.reduceRight(a, function(rval, val, i, arr) { assertEquals('number', typeof i); assertEquals(a, arr); return rval + val; }, '')); var scope = { last: '', testFn: function(r, v, i, arr) { assertEquals('number', typeof i); assertEquals(a, arr); var l = this.last; this.last = v; return r + v + l; } }; a = ['a', 'b', 'c']; assertEquals('_cbcab', goog.array.reduceRight(a, scope.testFn, '_', scope)); } function testArrayReduceRightOmitsDeleted() { var a = [0, 1, 2, 3, 4]; delete a[1]; delete a[4]; assertEquals('320', goog.array.reduceRight(a, function(rval, val, i, arr) { assertEquals('number', typeof i); assertEquals(a, arr); return rval + val; }, '')); scope = { last: '', testFn: function(r, v, i, arr) { assertEquals('number', typeof i); assertEquals(a, arr); var l = this.last; this.last = v; return r + v + l; } }; a = ['a', 'b', 'c', 'd']; delete a[1]; delete a[3]; assertEquals('_cac', goog.array.reduceRight(a, scope.testFn, '_', scope)); } function testArrayFind() { var a = [0, 1, 2, 3]; var b = goog.array.find(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val > 1; }); assertEquals(2, b); b = goog.array.find(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val > 100; }); assertNull(b); a = 'abCD'; b = goog.array.find(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val >= 'A' && val <= 'Z'; }); assertEquals('C', b); a = 'abcd'; b = goog.array.find(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val >= 'A' && val <= 'Z'; }); assertNull(b); } function testArrayFindOmitsDeleted() { var a = [0, 1, 2, 3]; delete a[1]; delete a[3]; var b = goog.array.find(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val > 1; }); assertEquals(2, b); b = goog.array.find(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val > 100; }); assertNull(b); } function testArrayFindIndex() { var a = [0, 1, 2, 3]; var b = goog.array.findIndex(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val > 1; }); assertEquals(2, b); b = goog.array.findIndex(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val > 100; }); assertEquals(-1, b); a = 'abCD'; b = goog.array.findIndex(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val >= 'A' && val <= 'Z'; }); assertEquals(2, b); a = 'abcd'; b = goog.array.findIndex(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val >= 'A' && val <= 'Z'; }); assertEquals(-1, b); } function testArrayFindIndexOmitsDeleted() { var a = [0, 1, 2, 3]; delete a[1]; delete a[3]; var b = goog.array.findIndex(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val > 1; }); assertEquals(2, b); b = goog.array.findIndex(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val > 100; }); assertEquals(-1, b); } function testArrayFindRight() { var a = [0, 1, 2, 3]; var b = goog.array.findRight(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val < 3; }); assertEquals(2, b); b = goog.array.findRight(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val > 100; }); assertNull(b); } function testArrayFindRightOmitsDeleted() { var a = [0, 1, 2, 3]; delete a[1]; delete a[3]; var b = goog.array.findRight(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val < 3; }); assertEquals(2, b); b = goog.array.findRight(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val > 100; }); assertNull(b); } function testArrayFindIndexRight() { var a = [0, 1, 2, 3]; var b = goog.array.findIndexRight(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val < 3; }); assertEquals(2, b); b = goog.array.findIndexRight(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val > 100; }); assertEquals(-1, b); a = 'abCD'; b = goog.array.findIndexRight(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val >= 'a' && val <= 'z'; }); assertEquals(1, b); a = 'abcd'; b = goog.array.findIndexRight(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val >= 'A' && val <= 'Z'; }); assertEquals(-1, b); } function testArrayFindIndexRightOmitsDeleted() { var a = [0, 1, 2, 3]; delete a[1]; delete a[3]; var b = goog.array.findIndexRight(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val < 3; }); assertEquals(2, b); b = goog.array.findIndexRight(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val > 100; }); assertEquals(-1, b); } function testArraySome() { var a = [0, 1, 2, 3]; var b = goog.array.some(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val > 1; }); assertTrue(b); b = goog.array.some(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val > 100; }); assertFalse(b); } function testArraySomeOmitsDeleted() { var a = [0, 1, 2, 3]; delete a[1]; delete a[3]; var b = goog.array.some(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('number', typeof val); assertEquals('index is not a number', 'number', typeof index); return val > 1; }); assertTrue(b); b = goog.array.some(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('number', typeof val); assertEquals('index is not a number', 'number', typeof index); return val > 100; }); assertFalse(b); } function testArrayEvery() { var a = [0, 1, 2, 3]; var b = goog.array.every(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val >= 0; }); assertTrue(b); b = goog.array.every(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val > 1; }); assertFalse(b); } function testArrayEveryOmitsDeleted() { var a = [0, 1, 2, 3]; delete a[1]; delete a[3]; var b = goog.array.every(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('number', typeof val); assertEquals('index is not a number', 'number', typeof index); return val >= 0; }); assertTrue(b); b = goog.array.every(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('number', typeof val); assertEquals('index is not a number', 'number', typeof index); return val > 1; }); assertFalse(b); } function testArrayCount() { var a = [0, 1, 2, 3, 4]; var context = {}; assertEquals(3, goog.array.count(a, function(element, index, array) { assertTrue(goog.isNumber(index)); assertEquals(a, array); assertEquals(context, this); return element % 2 == 0; }, context)); delete a[2]; assertEquals('deleted element is ignored', 4, goog.array.count(a, function() { return true; })); } function testArrayContains() { var a = [0, 1, 2, 3]; assertTrue('contain, Should contain 3', goog.array.contains(a, 3)); assertFalse('contain, Should not contain 4', goog.array.contains(a, 4)); var s = 'abcd'; assertTrue('contain, Should contain d', goog.array.contains(s, 'd')); assertFalse('contain, Should not contain e', goog.array.contains(s, 'e')); } function testArrayContainsOmitsDeleted() { var a = [0, 1, 2, 3]; delete a[1]; delete a[3]; assertFalse( 'should not contain undefined', goog.array.contains(a, undefined)); } function testArrayInsert() { var a = [0, 1, 2, 3]; goog.array.insert(a, 4); assertEquals('insert, Should append 4', a[4], 4); goog.array.insert(a, 3); assertEquals('insert, Should not append 3', a.length, 5); assertNotEquals('insert, Should not append 3', a[a.length - 1], 3); } function testArrayInsertAt() { var a = [0, 1, 2, 3]; goog.array.insertAt(a, 4, 2); assertArrayEquals('insertAt, insert in middle', [0, 1, 4, 2, 3], a); goog.array.insertAt(a, 5, 10); assertArrayEquals( 'insertAt, too large value should append', [0, 1, 4, 2, 3, 5], a); goog.array.insertAt(a, 6); assertArrayEquals( 'insertAt, null/undefined value should insert at 0', [6, 0, 1, 4, 2, 3, 5], a); goog.array.insertAt(a, 7, -2); assertArrayEquals( 'insertAt, negative values start from end', [6, 0, 1, 4, 2, 7, 3, 5], a); } function testArrayInsertArrayAt() { var a = [2, 5]; goog.array.insertArrayAt(a, [3, 4], 1); assertArrayEquals('insertArrayAt, insert in middle', [2, 3, 4, 5], a); goog.array.insertArrayAt(a, [0, 1], 0); assertArrayEquals( 'insertArrayAt, insert at beginning', [0, 1, 2, 3, 4, 5], a); goog.array.insertArrayAt(a, [6, 7], 6); assertArrayEquals( 'insertArrayAt, insert at end', [0, 1, 2, 3, 4, 5, 6, 7], a); goog.array.insertArrayAt(a, ['x'], 4); assertArrayEquals( 'insertArrayAt, insert one element', [0, 1, 2, 3, 'x', 4, 5, 6, 7], a); goog.array.insertArrayAt(a, [], 4); assertArrayEquals( 'insertArrayAt, insert 0 elements', [0, 1, 2, 3, 'x', 4, 5, 6, 7], a); goog.array.insertArrayAt(a, ['y', 'z']); assertArrayEquals( 'insertArrayAt, undefined value should insert at 0', ['y', 'z', 0, 1, 2, 3, 'x', 4, 5, 6, 7], a); goog.array.insertArrayAt(a, ['a'], null); assertArrayEquals( 'insertArrayAt, null value should insert at 0', ['a', 'y', 'z', 0, 1, 2, 3, 'x', 4, 5, 6, 7], a); goog.array.insertArrayAt(a, ['b'], 100); assertArrayEquals( 'insertArrayAt, too large value should append', ['a', 'y', 'z', 0, 1, 2, 3, 'x', 4, 5, 6, 7, 'b'], a); goog.array.insertArrayAt(a, ['c', 'd'], -2); assertArrayEquals( 'insertArrayAt, negative values start from end', ['a', 'y', 'z', 0, 1, 2, 3, 'x', 4, 5, 6, 'c', 'd', 7, 'b'], a); } function testArrayInsertBefore() { var a = ['a', 'b', 'c', 'd']; goog.array.insertBefore(a, 'e', 'b'); assertArrayEquals( 'insertBefore, with existing element', ['a', 'e', 'b', 'c', 'd'], a); goog.array.insertBefore(a, 'f', 'x'); assertArrayEquals( 'insertBefore, with non existing element', ['a', 'e', 'b', 'c', 'd', 'f'], a); } function testArrayRemove() { var a = ['a', 'b', 'c', 'd']; goog.array.remove(a, 'c'); assertArrayEquals('remove, remove existing element', ['a', 'b', 'd'], a); goog.array.remove(a, 'x'); assertArrayEquals('remove, remove non existing element', ['a', 'b', 'd'], a); } function testArrayRemoveLast() { var a = ['c', 'a', 'b', 'c', 'd', 'a']; goog.array.removeLast(a, 'c'); var temp = ['c', 'a', 'b', 'd', 'a']; assertArrayEquals('remove, remove existing element', temp, a); goog.array.removeLast(a, 'a'); temp = ['c', 'a', 'b', 'd']; assertArrayEquals('remove, remove existing element', temp, a); goog.array.removeLast(a, 'y'); temp = ['c', 'a', 'b', 'd']; assertArrayEquals('remove, remove non existing element', temp, a); } function testArrayRemoveAt() { var a = [0, 1, 2, 3]; goog.array.removeAt(a, 2); assertArrayEquals('removeAt, remove existing index', [0, 1, 3], a); a = [0, 1, 2, 3]; goog.array.removeAt(a, 10); assertArrayEquals('removeAt, remove non existing index', [0, 1, 2, 3], a); a = [0, 1, 2, 3]; goog.array.removeAt(a, -2); assertArrayEquals('removeAt, remove with negative index', [0, 1, 3], a); } function testArrayRemoveIf() { var a = [0, 1, 2, 3]; var b = goog.array.removeIf(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val > 1; }); assertArrayEquals('removeIf, remove existing element', [0, 1, 3], a); a = [0, 1, 2, 3]; var b = goog.array.removeIf(a, function(val, index, a2) { assertEquals(a, a2); assertEquals('index is not a number', 'number', typeof index); return val > 100; }); assertArrayEquals('removeIf, remove non-existing element', [0, 1, 2, 3], a); } function testArrayClone() { var a = [0, 1, 2, 3]; var a2 = goog.array.clone(a); assertArrayEquals('clone, should be equal', a, a2); var b = {0: 0, 1: 1, 2: 2, 3: 3, length: 4}; var b2 = goog.array.clone(b); for (var i = 0; i < b.length; i++) { assertEquals('clone, should be equal', b[i], b2[i]); } } function testToArray() { var a = [0, 1, 2, 3]; var a2 = goog.array.toArray(a); assertArrayEquals('toArray, should be equal', a, a2); var b = {0: 0, 1: 1, 2: 2, 3: 3, length: 4}; var b2 = goog.array.toArray(b); for (var i = 0; i < b.length; i++) { assertEquals('toArray, should be equal', b[i], b2[i]); } } function testToArrayOnNonArrayLike() { var nonArrayLike = {}; assertArrayEquals( 'toArray on non ArrayLike should return an empty array', [], goog.array.toArray(nonArrayLike)); var nonArrayLike2 = {length: 'hello world'}; assertArrayEquals( 'toArray on non ArrayLike should return an empty array', [], goog.array.toArray(nonArrayLike2)); } function testExtend() { var a = [0, 1]; goog.array.extend(a, [2, 3]); var a2 = [0, 1, 2, 3]; assertArrayEquals('extend, should be equal', a, a2); var b = [0, 1]; goog.array.extend(b, 2); var b2 = [0, 1, 2]; assertArrayEquals('extend, should be equal', b, b2); a = [0, 1]; goog.array.extend(a, [2, 3], [4, 5]); a2 = [0, 1, 2, 3, 4, 5]; assertArrayEquals('extend, should be equal', a, a2); b = [0, 1]; goog.array.extend(b, 2, 3); b2 = [0, 1, 2, 3]; assertArrayEquals('extend, should be equal', b, b2); var c = [0, 1]; goog.array.extend(c, 2, [3, 4], 5, [6]); var c2 = [0, 1, 2, 3, 4, 5, 6]; assertArrayEquals('extend, should be equal', c, c2); var d = [0, 1]; var arrayLikeObject = {0: 2, 1: 3, length: 2}; goog.array.extend(d, arrayLikeObject); var d2 = [0, 1, 2, 3]; assertArrayEquals('extend, should be equal', d, d2); var e = [0, 1]; var emptyArrayLikeObject = {length: 0}; goog.array.extend(e, emptyArrayLikeObject); assertArrayEquals('extend, should be equal', e, e); var f = [0, 1]; var length3ArrayLikeObject = {0: 2, 1: 4, 2: 8, length: 3}; goog.array.extend(f, length3ArrayLikeObject, length3ArrayLikeObject); var f2 = [0, 1, 2, 4, 8, 2, 4, 8]; assertArrayEquals('extend, should be equal', f2, f); var result = []; var i = 1000000; var bigArray = Array(i); while (i--) { bigArray[i] = i; } goog.array.extend(result, bigArray); assertArrayEquals(bigArray, result); } function testExtendWithArguments() { function f() { return arguments; } var a = [0]; var a2 = [0, 1, 2, 3, 4, 5]; goog.array.extend(a, f(1, 2, 3), f(4, 5)); assertArrayEquals('extend, should be equal', a, a2); } function testExtendWithQuerySelector() { var a = [0]; var d = goog.dom.getElementsByTagNameAndClass(goog.dom.TagName.DIV, 'foo'); goog.array.extend(a, d); assertEquals(2, a.length); } function testArraySplice() { var a = [0, 1, 2, 3]; goog.array.splice(a, 1, 0, 4); assertArrayEquals([0, 4, 1, 2, 3], a); goog.array.splice(a, 1, 1, 5); assertArrayEquals([0, 5, 1, 2, 3], a); goog.array.splice(a, 1, 1); assertArrayEquals([0, 1, 2, 3], a); // var args goog.array.splice(a, 1, 1, 4, 5, 6); assertArrayEquals([0, 4, 5, 6, 2, 3], a); } function testArraySlice() { var a = [0, 1, 2, 3]; a = goog.array.slice(a, 1, 3); assertArrayEquals([1, 2], a); a = [0, 1, 2, 3]; a = goog.array.slice(a, 1, 6); assertArrayEquals('slice, with too large end', [1, 2, 3], a); a = [0, 1, 2, 3]; a = goog.array.slice(a, 1, -1); assertArrayEquals('slice, with negative end', [1, 2], a); a = [0, 1, 2, 3]; a = goog.array.slice(a, -2, 3); assertArrayEquals('slice, with negative start', [2], a); } function assertRemovedDuplicates(expected, original) { var tempArr = goog.array.clone(original); goog.array.removeDuplicates(tempArr); assertArrayEquals(expected, tempArr); } function testRemoveDuplicates() { assertRemovedDuplicates([1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]); assertRemovedDuplicates( [9, 4, 2, 1, 3, 6, 0, -9], [9, 4, 2, 4, 4, 2, 9, 1, 3, 6, 0, -9]); assertRemovedDuplicates( ['four', 'one', 'two', 'three', 'THREE'], ['four', 'one', 'two', 'one', 'three', 'THREE', 'four', 'two']); assertRemovedDuplicates([], []); assertRemovedDuplicates( ['abc', 'hasOwnProperty', 'toString'], ['abc', 'hasOwnProperty', 'toString', 'abc']); var o1 = {}, o2 = {}, o3 = {}, o4 = {}; assertRemovedDuplicates([o1, o2, o3, o4], [o1, o1, o2, o3, o2, o4]); // Mixed object types. assertRemovedDuplicates([1, '1', 2, '2'], [1, '1', 2, '2']); assertRemovedDuplicates( [true, 'true', false, 'false'], [true, 'true', false, 'false']); assertRemovedDuplicates(['foo'], [String('foo'), 'foo']); assertRemovedDuplicates([12], [Number(12), 12]); var obj = {}; var uid = goog.getUid(obj); assertRemovedDuplicates([obj, uid], [obj, uid]); } function testRemoveDuplicates_customHashFn() { var object1 = {key: 'foo'}; var object2 = {key: 'bar'}; var dupeObject = {key: 'foo'}; var array = [object1, object2, dupeObject, 'bar']; var hashFn = function(object) { return goog.isObject(object) ? object.key : (typeof object).charAt(0) + object; }; goog.array.removeDuplicates(array, /* opt_rv */ undefined, hashFn); assertArrayEquals([object1, object2, 'bar'], array); } function testBinaryInsertRemove() { var makeChecker = function(array, fn, opt_compareFn) { return function(value, expectResult, expectArray) { var result = fn(array, value, opt_compareFn); assertEquals(expectResult, result); assertArrayEquals(expectArray, array); } }; var a = []; var check = makeChecker(a, goog.array.binaryInsert); check(3, true, [3]); check(3, false, [3]); check(1, true, [1, 3]); check(5, true, [1, 3, 5]); check(2, true, [1, 2, 3, 5]); check(2, false, [1, 2, 3, 5]); check = makeChecker(a, goog.array.binaryRemove); check(0, false, [1, 2, 3, 5]); check(3, true, [1, 2, 5]); check(1, true, [2, 5]); check(5, true, [2]); check(2, true, []); check(2, false, []); // test with custom comparison function, which reverse orders numbers var revNumCompare = function(a, b) { return b - a; }; check = makeChecker(a, goog.array.binaryInsert, revNumCompare); check(3, true, [3]); check(3, false, [3]); check(1, true, [3, 1]); check(5, true, [5, 3, 1]); check(2, true, [5, 3, 2, 1]); check(2, false, [5, 3, 2, 1]); check = makeChecker(a, goog.array.binaryRemove, revNumCompare); check(0, false, [5, 3, 2, 1]); check(3, true, [5, 2, 1]); check(1, true, [5, 2]); check(5, true, [2]); check(2, true, []); check(2, false, []); } function testBinarySearch() { var insertionPoint = function(position) { return -(position + 1) }; var pos; // test default comparison on array of String(s) var a = [ '1000', '9', 'AB', 'ABC', 'ABCABC', 'ABD', 'ABDA', 'B', 'B', 'B', 'C', 'CA', 'CC', 'ZZZ', 'ab', 'abc', 'abcabc', 'abd', 'abda', 'b', 'c', 'ca', 'cc', 'zzz' ]; assertEquals( '\'1000\' should be found at index 0', 0, goog.array.binarySearch(a, '1000')); assertEquals( '\'zzz\' should be found at index ' + (a.length - 1), a.length - 1, goog.array.binarySearch(a, 'zzz')); assertEquals( '\'C\' should be found at index 10', 10, goog.array.binarySearch(a, 'C')); pos = goog.array.binarySearch(a, 'B'); assertTrue( '\'B\' should be found at index 7 || 8 || 9', pos == 7 || pos == 8 || pos == 9); pos = goog.array.binarySearch(a, '100'); assertTrue('\'100\' should not be found', pos < 0); assertEquals( '\'100\' should have an insertion point of 0', 0, insertionPoint(pos)); pos = goog.array.binarySearch(a, 'zzz0'); assertTrue('\'zzz0\' should not be found', pos < 0); assertEquals( '\'zzz0\' should have an insertion point of ' + (a.length), a.length, insertionPoint(pos)); pos = goog.array.binarySearch(a, 'BA'); assertTrue('\'BA\' should not be found', pos < 0); assertEquals( '\'BA\' should have an insertion point of 10', 10, insertionPoint(pos)); // test 0 length array with default comparison var b = []; pos = goog.array.binarySearch(b, 'a'); assertTrue('\'a\' should not be found', pos < 0); assertEquals( '\'a\' should have an insertion point of 0', 0, insertionPoint(pos)); // test single element array with default lexiographical comparison var c = ['only item']; assertEquals( '\'only item\' should be found at index 0', 0, goog.array.binarySearch(c, 'only item')); pos = goog.array.binarySearch(c, 'a'); assertTrue('\'a\' should not be found', pos < 0); assertEquals( '\'a\' should have an insertion point of 0', 0, insertionPoint(pos)); pos = goog.array.binarySearch(c, 'z'); assertTrue('\'z\' should not be found', pos < 0); assertEquals( '\'z\' should have an insertion point of 1', 1, insertionPoint(pos)); // test default comparison on array of Number(s) var d = [ -897123.9, -321434.58758, -1321.3124, -324, -9, -3, 0, 0, 0, 0.31255, 5, 142.88888708, 334, 342, 453, 54254 ]; assertEquals( '-897123.9 should be found at index 0', 0, goog.array.binarySearch(d, -897123.9)); assertEquals( '54254 should be found at index ' + (a.length - 1), d.length - 1, goog.array.binarySearch(d, 54254)); assertEquals( '-3 should be found at index 5', 5, goog.array.binarySearch(d, -3)); pos = goog.array.binarySearch(d, 0); assertTrue( '0 should be found at index 6 || 7 || 8', pos == 6 || pos == 7 || pos == 8); pos = goog.array.binarySearch(d, -900000); assertTrue('-900000 should not be found', pos < 0); assertEquals( '-900000 should have an insertion point of 0', 0, insertionPoint(pos)); pos = goog.array.binarySearch(d, 54255); assertTrue('54255 should not be found', pos < 0); assertEquals( '54255 should have an insertion point of ' + (d.length), d.length, insertionPoint(pos)); pos = goog.array.binarySearch(d, 1.1); assertTrue('1.1 should not be found', pos < 0); assertEquals( '1.1 should have an insertion point of 10', 10, insertionPoint(pos)); // test with custom comparison function, which reverse orders numbers var revNumCompare = function(a, b) { return b - a; }; var e = [ 54254, 453, 342, 334, 142.88888708, 5, 0.31255, 0, 0, 0, -3, -9, -324, -1321.3124, -321434.58758, -897123.9 ]; assertEquals( '54254 should be found at index 0', 0, goog.array.binarySearch(e, 54254, revNumCompare)); assertEquals( '-897123.9 should be found at index ' + (e.length - 1), e.length - 1, goog.array.binarySearch(e, -897123.9, revNumCompare)); assertEquals( '-3 should be found at index 10', 10, goog.array.binarySearch(e, -3, revNumCompare)); pos = goog.array.binarySearch(e, 0, revNumCompare); assertTrue( '0 should be found at index 7 || 8 || 9', pos == 7 || pos == 8 || pos == 9); pos = goog.array.binarySearch(e, 54254.1, revNumCompare); assertTrue('54254.1 should not be found', pos < 0); assertEquals( '54254.1 should have an insertion point of 0', 0, insertionPoint(pos)); pos = goog.array.binarySearch(e, -897124, revNumCompare); assertTrue('-897124 should not be found', pos < 0); assertEquals( '-897124 should have an insertion point of ' + (e.length), e.length, insertionPoint(pos)); pos = goog.array.binarySearch(e, 1.1, revNumCompare); assertTrue('1.1 should not be found', pos < 0); assertEquals( '1.1 should have an insertion point of 6', 6, insertionPoint(pos)); // test 0 length array with custom comparison function var f = []; pos = goog.array.binarySearch(f, 0, revNumCompare); assertTrue('0 should not be found', pos < 0); assertEquals('0 should have an insertion point of 0', 0, insertionPoint(pos)); // test single element array with custom comparison function var g = [1]; assertEquals( '1 should be found at index 0', 0, goog.array.binarySearch(g, 1, revNumCompare)); pos = goog.array.binarySearch(g, 2, revNumCompare); assertTrue('2 should not be found', pos < 0); assertEquals('2 should have an insertion point of 0', 0, insertionPoint(pos)); pos = goog.array.binarySearch(g, 0, revNumCompare); assertTrue('0 should not be found', pos < 0); assertEquals('0 should have an insertion point of 1', 1, insertionPoint(pos)); assertEquals( 'binarySearch should find the index of the first 0', 0, goog.array.binarySearch([0, 0, 1], 0)); assertEquals( 'binarySearch should find the index of the first 1', 1, goog.array.binarySearch([0, 1, 1], 1)); } function testBinarySearchPerformance() { // Ensure that Array#slice, Function#apply and Function#call are not called // from within binarySearch, since they have performance implications in IE. var propertyReplacer = new goog.testing.PropertyReplacer(); propertyReplacer.replace(Array.prototype, 'slice', function() { fail('Should not call Array#slice from binary search.'); }); propertyReplacer.replace(Function.prototype, 'apply', function() { fail('Should not call Function#apply from binary search.'); }); propertyReplacer.replace(Function.prototype, 'call', function() { fail('Should not call Function#call from binary search.'); }); try { var array = [1, 5, 7, 11, 13, 16, 19, 24, 28, 31, 33, 36, 40, 50, 52, 55]; // Test with the default comparison function. goog.array.binarySearch(array, 48); // Test with a custom comparison function. goog.array.binarySearch( array, 13, function(a, b) { return a > b ? 1 : a < b ? -1 : 0; }); } finally { // The test runner uses Function.prototype.apply to call tearDown in the // global context so it has to be reset here. propertyReplacer.reset(); } } function testBinarySelect() { var insertionPoint = function(position) { return -(position + 1) }; var numbers = [ -897123.9, -321434.58758, -1321.3124, -324, -9, -3, 0, 0, 0, 0.31255, 5, 142.88888708, 334, 342, 453, 54254 ]; var objects = goog.array.map(numbers, function(n) { return {n: n}; }); function makeEvaluator(target) { return function(obj, i, arr) { assertEquals(objects, arr); assertEquals(obj, arr[i]); return target - obj.n; }; } assertEquals( '{n:-897123.9} should be found at index 0', 0, goog.array.binarySelect(objects, makeEvaluator(-897123.9))); assertEquals( '{n:54254} should be found at index ' + (objects.length - 1), objects.length - 1, goog.array.binarySelect(objects, makeEvaluator(54254))); assertEquals( '{n:-3} should be found at index 5', 5, goog.array.binarySelect(objects, makeEvaluator(-3))); pos = goog.array.binarySelect(objects, makeEvaluator(0)); assertTrue( '{n:0} should be found at index 6 || 7 || 8', pos == 6 || pos == 7 || pos == 8); pos = goog.array.binarySelect(objects, makeEvaluator(-900000)); assertTrue('{n:-900000} should not be found', pos < 0); assertEquals( '{n:-900000} should have an insertion point of 0', 0, insertionPoint(pos)); pos = goog.array.binarySelect(objects, makeEvaluator('54255')); assertTrue('{n:54255} should not be found', pos < 0); assertEquals( '{n:54255} should have an insertion point of ' + (objects.length), objects.length, insertionPoint(pos)); pos = goog.array.binarySelect(objects, makeEvaluator(1.1)); assertTrue('{n:1.1} should not be found', pos < 0); assertEquals( '{n:1.1} should have an insertion point of 10', 10, insertionPoint(pos)); } function testArrayEquals() { // Test argument types. assertFalse('array == not array', goog.array.equals([], null)); assertFalse('not array == array', goog.array.equals(null, [])); assertFalse('not array == not array', goog.array.equals(null, null)); // Test with default comparison function. assertTrue('[] == []', goog.array.equals([], [])); assertTrue('[1] == [1]', goog.array.equals([1], [1])); assertTrue('["1"] == ["1"]', goog.array.equals(['1'], ['1'])); assertFalse('[1] == ["1"]', goog.array.equals([1], ['1'])); assertTrue('[null] == [null]', goog.array.equals([null], [null])); assertFalse('[null] == [undefined]', goog.array.equals([null], [undefined])); assertTrue('[1, 2] == [1, 2]', goog.array.equals([1, 2], [1, 2])); assertFalse('[1, 2] == [2, 1]', goog.array.equals([1, 2], [2, 1])); assertFalse('[1, 2] == [1]', goog.array.equals([1, 2], [1])); assertFalse('[1] == [1, 2]', goog.array.equals([1], [1, 2])); assertFalse('[{}] == [{}]', goog.array.equals([{}], [{}])); // Test with custom comparison function. var cmp = function(a, b) { return typeof a == typeof b; }; assertTrue('[] cmp []', goog.array.equals([], [], cmp)); assertTrue('[1] cmp [1]', goog.array.equals([1], [1], cmp)); assertTrue('[1] cmp [2]', goog.array.equals([1], [2], cmp)); assertTrue('["1"] cmp ["1"]', goog.array.equals(['1'], ['1'], cmp)); assertTrue('["1"] cmp ["2"]', goog.array.equals(['1'], ['2'], cmp)); assertFalse('[1] cmp ["1"]', goog.array.equals([1], ['1'], cmp)); assertTrue('[1, 2] cmp [3, 4]', goog.array.equals([1, 2], [3, 4], cmp)); assertFalse('[1] cmp [2, 3]', goog.array.equals([1], [2, 3], cmp)); assertTrue('[{}] cmp [{}]', goog.array.equals([{}], [{}], cmp)); assertTrue('[{}] cmp [{a: 1}]', goog.array.equals([{}], [{a: 1}], cmp)); // Test with array-like objects. assertTrue('[5] == obj [5]', goog.array.equals([5], {0: 5, length: 1})); assertTrue('obj [5] == [5]', goog.array.equals({0: 5, length: 1}, [5])); assertTrue( '["x"] == obj ["x"]', goog.array.equals(['x'], {0: 'x', length: 1})); assertTrue( 'obj ["x"] == ["x"]', goog.array.equals({0: 'x', length: 1}, ['x'])); assertTrue( '[5] == {0: 5, 1: 6, length: 1}', goog.array.equals([5], {0: 5, 1: 6, length: 1})); assertTrue( '{0: 5, 1: 6, length: 1} == [5]', goog.array.equals({0: 5, 1: 6, length: 1}, [5])); assertFalse( '[5, 6] == {0: 5, 1: 6, length: 1}', goog.array.equals([5, 6], {0: 5, 1: 6, length: 1})); assertFalse( '{0: 5, 1: 6, length: 1}, [5, 6]', goog.array.equals({0: 5, 1: 6, length: 1}, [5, 6])); assertTrue( '[5, 6] == obj [5, 6]', goog.array.equals([5, 6], {0: 5, 1: 6, length: 2})); assertTrue( 'obj [5, 6] == [5, 6]', goog.array.equals({0: 5, 1: 6, length: 2}, [5, 6])); assertFalse( '{0: 5, 1: 6} == [5, 6]', goog.array.equals({0: 5, 1: 6}, [5, 6])); } function testArrayCompare3Basic() { assertEquals(0, goog.array.compare3([], [])); assertEquals(0, goog.array.compare3(['111', '222'], ['111', '222'])); assertEquals(-1, goog.array.compare3(['111', '222'], ['1111', ''])); assertEquals(1, goog.array.compare3(['111', '222'], ['111'])); assertEquals(1, goog.array.compare3(['11', '222', '333'], [])); assertEquals(-1, goog.array.compare3([], ['11', '222', '333'])); } function testArrayCompare3ComparatorFn() { function cmp(a, b) { return a - b; }; assertEquals(0, goog.array.compare3([], [], cmp)); assertEquals(0, goog.array.compare3([8, 4], [8, 4], cmp)); assertEquals(-1, goog.array.compare3([4, 3], [5, 0])); assertEquals(1, goog.array.compare3([6, 2], [6])); assertEquals(1, goog.array.compare3([1, 2, 3], [])); assertEquals(-1, goog.array.compare3([], [1, 2, 3])); } function testSort() { // Test sorting empty array var a = []; goog.array.sort(a); assertEquals( 'Sorted empty array is still an empty array (length 0)', 0, a.length); // Test sorting homogenous array of String(s) of length > 1 var b = [ 'JUST', '1', 'test', 'Array', 'to', 'test', 'array', 'Sort', 'about', 'NOW', '!!' ]; var bSorted = [ '!!', '1', 'Array', 'JUST', 'NOW', 'Sort', 'about', 'array', 'test', 'test', 'to' ]; goog.array.sort(b); assertArrayEquals(bSorted, b); // Test sorting already sorted array of String(s) of length > 1 goog.array.sort(b); assertArrayEquals(bSorted, b); // Test sorting homogenous array of integer Number(s) of length > 1 var c = [ 100, 1, 2000, -1, 0, 1000023, 12312512, -12331, 123, 54325, -38104783, 93708, 908, -213, -4, 5423, 0 ]; var cSorted = [ -38104783, -12331, -213, -4, -1, 0, 0, 1, 100, 123, 908, 2000, 5423, 54325, 93708, 1000023, 12312512 ]; goog.array.sort(c); assertArrayEquals(cSorted, c); // Test sorting already sorted array of integer Number(s) of length > 1 goog.array.sort(c); assertArrayEquals(cSorted, c); // Test sorting homogenous array of Number(s) of length > 1 var e = [ -1321.3124, 0.31255, 54254, 0, 142.88888708, -321434.58758, -324, 453, 334, -3, 5, -9, 342, -897123.9 ]; var eSorted = [ -897123.9, -321434.58758, -1321.3124, -324, -9, -3, 0, 0.31255, 5, 142.88888708, 334, 342, 453, 54254 ]; goog.array.sort(e); assertArrayEquals(eSorted, e); // Test sorting already sorted array of Number(s) of length > 1 goog.array.sort(e); assertArrayEquals(eSorted, e); // Test sorting array of Number(s) of length > 1, // using custom comparison function which does reverse ordering var f = [ -1321.3124, 0.31255, 54254, 0, 142.88888708, -321434.58758, -324, 453, 334, -3, 5, -9, 342, -897123.9 ]; var fSorted = [ 54254, 453, 342, 334, 142.88888708, 5, 0.31255, 0, -3, -9, -324, -1321.3124, -321434.58758, -897123.9 ]; goog.array.sort(f, function(a, b) { return b - a; }); assertArrayEquals(fSorted, f); // Test sorting already sorted array of Number(s) of length > 1 // using custom comparison function which does reverse ordering goog.array.sort(f, function(a, b) { return b - a; }); assertArrayEquals(fSorted, f); // Test sorting array of custom Object(s) of length > 1 that have // an overriden toString function ComparedObject(value) { this.value = value; }; ComparedObject.prototype.toString = function() { return this.value; }; var co1 = new ComparedObject('a'); var co2 = new ComparedObject('b'); var co3 = new ComparedObject('c'); var co4 = new ComparedObject('d'); var g = [co3, co4, co2, co1]; var gSorted = [co1, co2, co3, co4]; goog.array.sort(g); assertArrayEquals(gSorted, g); // Test sorting already sorted array of custom Object(s) of length > 1 // that have an overriden toString goog.array.sort(g); assertArrayEquals(gSorted, g); // Test sorting an array of custom Object(s) of length > 1 using // a custom comparison function var h = [co4, co2, co1, co3]; var hSorted = [co1, co2, co3, co4]; goog.array.sort(h, function(a, b) { return a.value > b.value ? 1 : a.value < b.value ? -1 : 0; }); assertArrayEquals(hSorted, h); // Test sorting already sorted array of custom Object(s) of length > 1 // using a custom comparison function goog.array.sort(h); assertArrayEquals(hSorted, h); // Test sorting arrays of length 1 var i = ['one']; var iSorted = ['one']; goog.array.sort(i); assertArrayEquals(iSorted, i); var j = [1]; var jSorted = [1]; goog.array.sort(j); assertArrayEquals(jSorted, j); var k = [1.1]; var kSorted = [1.1]; goog.array.sort(k); assertArrayEquals(kSorted, k); var l = [co3]; var lSorted = [co3]; goog.array.sort(l); assertArrayEquals(lSorted, l); var m = [co2]; var mSorted = [co2]; goog.array.sort(m, function(a, b) { return a.value > b.value ? 1 : a.value < b.value ? -1 : 0; }); assertArrayEquals(mSorted, m); } function testStableSort() { // Test array with custom comparison function var arr = [ {key: 3, val: 'a'}, {key: 2, val: 'b'}, {key: 3, val: 'c'}, {key: 4, val: 'd'}, {key: 3, val: 'e'} ]; var arrClone = goog.array.clone(arr); function comparisonFn(obj1, obj2) { return obj1.key - obj2.key; } goog.array.stableSort(arr, comparisonFn); var sortedValues = []; for (var i = 0; i < arr.length; i++) { sortedValues.push(arr[i].val); } var wantedSortedValues = ['b', 'a', 'c', 'e', 'd']; assertArrayEquals(wantedSortedValues, sortedValues); // Test array without custom comparison function var arr2 = []; for (var i = 0; i < arrClone.length; i++) { arr2.push({ val: arrClone[i].val, toString: goog.partial(function(index) { return arrClone[index].key; }, i) }); } goog.array.stableSort(arr2); var sortedValues2 = []; for (var i = 0; i < arr2.length; i++) { sortedValues2.push(arr2[i].val); } assertArrayEquals(wantedSortedValues, sortedValues2); } function testSortByKey() { function Item(value) { this.getValue = function() { return value; }; } var keyFn = function(item) { return item.getValue(); }; // Test without custom key comparison function var arr1 = [new Item(3), new Item(2), new Item(1), new Item(5), new Item(4)]; goog.array.sortByKey(arr1, keyFn); var wantedSortedValues1 = [1, 2, 3, 4, 5]; for (var i = 0; i < arr1.length; i++) { assertEquals(wantedSortedValues1[i], arr1[i].getValue()); } // Test with custom key comparison function var arr2 = [new Item(3), new Item(2), new Item(1), new Item(5), new Item(4)]; function comparisonFn(key1, key2) { return -(key1 - key2); } goog.array.sortByKey(arr2, keyFn, comparisonFn); var wantedSortedValues2 = [5, 4, 3, 2, 1]; for (var i = 0; i < arr2.length; i++) { assertEquals(wantedSortedValues2[i], arr2[i].getValue()); } } function testArrayBucketModulus() { // bucket things by modulus var a = {}; var b = []; function modFive(num) { return num % 5; } for (var i = 0; i < 20; i++) { var mod = modFive(i); a[mod] = a[mod] || []; a[mod].push(i); b.push(i); } var buckets = goog.array.bucket(b, modFive); for (var i = 0; i < 5; i++) { // The order isn't defined, but they should be the same sorted. goog.array.sort(a[i]); goog.array.sort(buckets[i]); assertArrayEquals(a[i], buckets[i]); } } function testArrayBucketEvenOdd() { var a = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // test even/odd function isEven(value, index, array) { assertEquals(value, array[index]); assertEquals('number', typeof index); assertEquals(a, array); return value % 2 == 0; } var b = goog.array.bucket(a, isEven); assertArrayEquals(b[true], [2, 4, 6, 8]); assertArrayEquals(b[false], [1, 3, 5, 7, 9]); } function testArrayBucketUsingThisObject() { var a = [1, 2, 3, 4, 5]; var obj = {specialValue: 2}; function isSpecialValue(value, index, array) { return value == this.specialValue ? 1 : 0; } var b = goog.array.bucket(a, isSpecialValue, obj); assertArrayEquals(b[0], [1, 3, 4, 5]); assertArrayEquals(b[1], [2]); } function testArrayToObject() { var a = [{name: 'a'}, {name: 'b'}, {name: 'c'}, {name: 'd'}]; function getName(value, index, array) { assertEquals(value, array[index]); assertEquals('number', typeof index); assertEquals(a, array); return value.name; } var b = goog.array.toObject(a, getName); for (var i = 0; i < a.length; i++) { assertEquals(a[i], b[a[i].name]); } } function testRange() { assertArrayEquals([], goog.array.range(0)); assertArrayEquals([], goog.array.range(5, 5, 5)); assertArrayEquals([], goog.array.range(-3, -3)); assertArrayEquals([], goog.array.range(10, undefined, -1)); assertArrayEquals([], goog.array.range(8, 0)); assertArrayEquals([], goog.array.range(-5, -10, 3)); assertArrayEquals([0], goog.array.range(1)); assertArrayEquals([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], goog.array.range(10)); assertArrayEquals([1], goog.array.range(1, 2)); assertArrayEquals([-3, -2, -1, 0, 1, 2], goog.array.range(-3, 3)); assertArrayEquals([4], goog.array.range(4, 40, 400)); assertArrayEquals([5, 8, 11, 14], goog.array.range(5, 15, 3)); assertArrayEquals([1, -1, -3], goog.array.range(1, -5, -2)); assertElementsRoughlyEqual([.2, .3, .4], goog.array.range(.2, .5, .1), 0.001); assertArrayEquals([0], goog.array.range(7, undefined, 9)); assertArrayEquals([0, 2, 4, 6], goog.array.range(8, undefined, 2)); } function testArrayRepeat() { assertArrayEquals([], goog.array.repeat(3, 0)); assertArrayEquals([], goog.array.repeat(3, -1)); assertArrayEquals([3], goog.array.repeat(3, 1)); assertArrayEquals([3, 3, 3], goog.array.repeat(3, 3)); assertArrayEquals([null, null], goog.array.repeat(null, 2)); } function testArrayFlatten() { assertArrayEquals([1, 2, 3, 4, 5], goog.array.flatten(1, 2, 3, 4, 5)); assertArrayEquals([1, 2, 3, 4, 5], goog.array.flatten(1, [2, [3, [4, 5]]])); assertArrayEquals([1, 2, 3, 4], goog.array.flatten(1, [2, [3, [4]]])); assertArrayEquals([1, 2, 3, 4], goog.array.flatten([[[1], 2], 3], 4)); assertArrayEquals([1], goog.array.flatten([[1]])); assertArrayEquals([], goog.array.flatten()); assertArrayEquals([], goog.array.flatten([])); assertArrayEquals( goog.array.repeat(3, 180002), goog.array.flatten(3, goog.array.repeat(3, 180000), 3)); assertArrayEquals( goog.array.repeat(3, 180000), goog.array.flatten([goog.array.repeat(3, 180000)])); } function testSortObjectsByKey() { var sortedArray = buildSortedObjectArray(4); var objects = [sortedArray[1], sortedArray[2], sortedArray[0], sortedArray[3]]; goog.array.sortObjectsByKey(objects, 'name'); validateObjectArray(sortedArray, objects); } function testSortObjectsByKeyWithCompareFunction() { var sortedArray = buildSortedObjectArray(4); var objects = [sortedArray[1], sortedArray[2], sortedArray[0], sortedArray[3]]; var descSortedArray = [sortedArray[3], sortedArray[2], sortedArray[1], sortedArray[0]]; function descCompare(a, b) { return a < b ? 1 : a > b ? -1 : 0; }; goog.array.sortObjectsByKey(objects, 'name', descCompare); validateObjectArray(descSortedArray, objects); } function buildSortedObjectArray(size) { var objectArray = []; for (var i = 0; i < size; i++) { objectArray.push({'name': 'name_' + i, 'id': 'id_' + (size - i)}); } return objectArray; } function validateObjectArray(expected, actual) { assertEquals(expected.length, actual.length); for (var i = 0; i < expected.length; i++) { assertEquals(expected[i].name, actual[i].name); assertEquals(expected[i].id, actual[i].id); } } function testIsSorted() { assertTrue(goog.array.isSorted([1, 2, 3])); assertTrue(goog.array.isSorted([1, 2, 2])); assertFalse(goog.array.isSorted([1, 2, 1])); assertTrue(goog.array.isSorted([1, 2, 3], null, true)); assertFalse(goog.array.isSorted([1, 2, 2], null, true)); assertFalse(goog.array.isSorted([1, 2, 1], null, true)); function compare(a, b) { return b - a; } assertFalse(goog.array.isSorted([1, 2, 3], compare)); assertTrue(goog.array.isSorted([3, 2, 2], compare)); } function assertRotated(expect, array, rotate) { assertArrayEquals(expect, goog.array.rotate(array, rotate)); } function testRotate() { assertRotated([], [], 3); assertRotated([1], [1], 3); assertRotated([1, 2, 3, 4, 0], [0, 1, 2, 3, 4], -6); assertRotated([0, 1, 2, 3, 4], [0, 1, 2, 3, 4], -5); assertRotated([4, 0, 1, 2, 3], [0, 1, 2, 3, 4], -4); assertRotated([3, 4, 0, 1, 2], [0, 1, 2, 3, 4], -3); assertRotated([2, 3, 4, 0, 1], [0, 1, 2, 3, 4], -2); assertRotated([1, 2, 3, 4, 0], [0, 1, 2, 3, 4], -1); assertRotated([0, 1, 2, 3, 4], [0, 1, 2, 3, 4], 0); assertRotated([4, 0, 1, 2, 3], [0, 1, 2, 3, 4], 1); assertRotated([3, 4, 0, 1, 2], [0, 1, 2, 3, 4], 2); assertRotated([2, 3, 4, 0, 1], [0, 1, 2, 3, 4], 3); assertRotated([1, 2, 3, 4, 0], [0, 1, 2, 3, 4], 4); assertRotated([0, 1, 2, 3, 4], [0, 1, 2, 3, 4], 5); assertRotated([4, 0, 1, 2, 3], [0, 1, 2, 3, 4], 6); } function testMoveItemWithArray() { var arr = [0, 1, 2, 3]; goog.array.moveItem(arr, 1, 3); // toIndex > fromIndex assertArrayEquals([0, 2, 3, 1], arr); goog.array.moveItem(arr, 2, 0); // toIndex < fromIndex assertArrayEquals([3, 0, 2, 1], arr); goog.array.moveItem(arr, 1, 1); // toIndex == fromIndex assertArrayEquals([3, 0, 2, 1], arr); // Out-of-bounds indexes throw assertion errors. assertThrows(function() { goog.array.moveItem(arr, -1, 1); }); assertThrows(function() { goog.array.moveItem(arr, 4, 1); }); assertThrows(function() { goog.array.moveItem(arr, 1, -1); }); assertThrows(function() { goog.array.moveItem(arr, 1, 4); }); // The array should not be modified by the out-of-bound calls. assertArrayEquals([3, 0, 2, 1], arr); } function testMoveItemWithArgumentsObject() { var f = function() { goog.array.moveItem(arguments, 0, 1); return arguments; }; assertArrayEquals([1, 0], goog.array.toArray(f(0, 1))); } function testConcat() { var a1 = [1, 2, 3]; var a2 = [4, 5, 6]; var a3 = goog.array.concat(a1, a2); a1.push(1); a2.push(5); assertArrayEquals([1, 2, 3, 4, 5, 6], a3); } function testConcatWithNoSecondArg() { var a1 = [1, 2, 3, 4]; var a2 = goog.array.concat(a1); a1.push(5); assertArrayEquals([1, 2, 3, 4], a2); } function testConcatWithNonArrayArgs() { var a1 = [1, 2, 3, 4]; var o = {0: 'a', 1: 'b', length: 2}; var a2 = goog.array.concat(a1, 5, '10', o); assertArrayEquals([1, 2, 3, 4, 5, '10', o], a2); } function testConcatWithNull() { var a1 = goog.array.concat(null, [1, 2, 3]); var a2 = goog.array.concat([1, 2, 3], null); assertArrayEquals([null, 1, 2, 3], a1); assertArrayEquals([1, 2, 3, null], a2); } function testZip() { var a1 = goog.array.zip([1, 2, 3], [3, 2, 1]); var a2 = goog.array.zip([1, 2], [3, 2, 1]); var a3 = goog.array.zip(); assertArrayEquals([[1, 3], [2, 2], [3, 1]], a1); assertArrayEquals([[1, 3], [2, 2]], a2); assertArrayEquals([], a3); } function testShuffle() { // Test array. This array should have unique values for the purposes of this // test case. var testArray = [1, 2, 3, 4, 5]; var testArrayCopy = goog.array.clone(testArray); // Custom random function, which always returns a value approaching 1, // resulting in a "shuffle" that preserves the order of original array // (for array sizes that we work with here). var noChangeShuffleFunction = function() { return .999999; }; goog.array.shuffle(testArray, noChangeShuffleFunction); assertArrayEquals(testArrayCopy, testArray); // Custom random function, which always returns 0, resulting in a // deterministic "shuffle" that is predictable but differs from the // original order of the array. var testShuffleFunction = function() { return 0; }; goog.array.shuffle(testArray, testShuffleFunction); assertArrayEquals([2, 3, 4, 5, 1], testArray); // Test the use of a real random function(no optional RNG is specified). goog.array.shuffle(testArray); // Ensure the shuffled array comprises the same elements (without regard to // order). assertSameElements(testArrayCopy, testArray); } function testRemoveAllIf() { var testArray = [9, 1, 9, 2, 9, 3, 4, 9, 9, 9, 5]; var expectedArray = [1, 2, 3, 4, 5]; var actualOutput = goog.array.removeAllIf(testArray, function(el) { return el == 9; }); assertEquals(6, actualOutput); assertArrayEquals(expectedArray, testArray); } function testRemoveAllIf_noMatches() { var testArray = [1]; var expectedArray = [1]; var actualOutput = goog.array.removeAllIf(testArray, function(el) { return false; }); assertEquals(0, actualOutput); assertArrayEquals(expectedArray, testArray); } function testCopyByIndex() { var testArray = [1, 2, 'a', 'b', 'c', 'd']; var copyIndexes = [1, 3, 0, 0, 2]; var expectedArray = [2, 'b', 1, 1, 'a']; var actualOutput = goog.array.copyByIndex(testArray, copyIndexes); assertArrayEquals(expectedArray, actualOutput); } function testComparators() { var greater = 42; var smaller = 13; assertTrue(goog.array.defaultCompare(smaller, greater) < 0); assertEquals(0, goog.array.defaultCompare(smaller, smaller)); assertTrue(goog.array.defaultCompare(greater, smaller) > 0); assertTrue(goog.array.inverseDefaultCompare(greater, smaller) < 0); assertEquals(0, goog.array.inverseDefaultCompare(greater, greater)); assertTrue(goog.array.inverseDefaultCompare(smaller, greater) > 0); } function testConcatMap() { var a = [0, 1, 2, 0]; var context = {}; var arraysToReturn = [['x', 'y', 'z'], [], ['a', 'b']]; var timesCalled = 0; var result = goog.array.concatMap(a, function(val, index, a2) { assertEquals(a, a2); assertEquals(context, this); assertEquals(timesCalled++, index); assertEquals(a[index], val); return arraysToReturn[val]; }, context); assertArrayEquals(['x', 'y', 'z', 'a', 'b', 'x', 'y', 'z'], result); }
Array.prototype.myreduce = function (func) { let arr = this; let accum = 0; for (let i = 0; i < arr.length; i++) { accum = func(accum, arr[i]); } return accum; }; // let result = [1, 2, 3].reduce((a, b) => a + b); let result = [1, 2, 3].myreduce((a, b) => a + b); console.log(result);
https://github.com/imaya/zlib.js/blob/master/src/huffman.js
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let Sms = props => <SvgIconCustom {...props}> <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM9 11H7V9h2v2zm4 0h-2V9h2v2zm4 0h-2V9h2v2z" /> </SvgIconCustom>; Sms = pure(Sms); Sms.muiName = 'SvgIcon'; export default Sms;
!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports,require("vue")):"function"==typeof define&&define.amd?define(["exports","vue"],n):n((t="undefined"!=typeof globalThis?globalThis:t||self).VueCompositionAPI={},t.Vue)}(this,(function(t,n){"use strict";function e(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var r=e(n);function o(t){return"function"==typeof t&&/native code/.test(t.toString())}var i="undefined"!=typeof Symbol&&o(Symbol)&&"undefined"!=typeof Reflect&&o(Reflect.ownKeys),u=function(t){return t};function f(t,n,e){var r=e.get,o=e.set;Object.defineProperty(t,n,{enumerable:!0,configurable:!0,get:r||u,set:o||u})}function a(t,n,e,r){Object.defineProperty(t,n,{value:e,enumerable:!!r,writable:!0,configurable:!0})}function c(t,n){return Object.hasOwnProperty.call(t,n)}function l(t){return Array.isArray(t)}var s=Object.prototype.toString,v=function(t){return s.call(t)};function d(t){var n=parseFloat(String(t));return n>=0&&Math.floor(n)===n&&isFinite(t)&&n<=4294967295}function p(t){return null!==t&&"object"==typeof t}function y(t){return"[object Object]"===function(t){return Object.prototype.toString.call(t)}(t)}function _(t){return"function"==typeof t}function h(t,n){r.default.util.warn(t,n)} /*! ***************************************************************************** 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. ***************************************************************************** */ var b=function(t,n){return b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var e in n)Object.prototype.hasOwnProperty.call(n,e)&&(t[e]=n[e])},b(t,n)};var g,m=function(){return m=Object.assign||function(t){for(var n,e=1,r=arguments.length;e<r;e++)for(var o in n=arguments[e])Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o]);return t},m.apply(this,arguments)};function w(t){var n="function"==typeof Symbol&&Symbol.iterator,e=n&&t[n],r=0;if(e)return e.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")}function $(t,n){var e="function"==typeof Symbol&&t[Symbol.iterator];if(!e)return t;var r,o,i=e.call(t),u=[];try{for(;(void 0===n||n-- >0)&&!(r=i.next()).done;)u.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(e=i.return)&&e.call(i)}finally{if(o)throw o.error}}return u}function j(t,n,e){if(e||2===arguments.length)for(var r,o=0,i=n.length;o<i;o++)!r&&o in n||(r||(r=Array.prototype.slice.call(n,0,o)),r[o]=n[o]);return t.concat(r||Array.prototype.slice.call(n))}var O=[],x=function(){function t(t){this.active=!0,this.effects=[],this.cleanups=[],this.vm=t}return t.prototype.run=function(t){if(this.active)try{return this.on(),t()}finally{this.off()}},t.prototype.on=function(){this.active&&(O.push(this),g=this)},t.prototype.off=function(){this.active&&(O.pop(),g=O[O.length-1])},t.prototype.stop=function(){this.active&&(this.vm.$destroy(),this.effects.forEach((function(t){return t.stop()})),this.cleanups.forEach((function(t){return t()})),this.active=!1)},t}(),S=function(t){function n(n){void 0===n&&(n=!1);var e,r=void 0;return function(t){var n=D;D=!1;try{t()}finally{D=n}}((function(){r=K(B())})),e=t.call(this,r)||this,n||function(t,n){var e;if((n=n||g)&&n.active)return void n.effects.push(t);var r=null===(e=V())||void 0===e?void 0:e.proxy;r&&r.$on("hook:destroyed",(function(){return t.stop()}))}(e),e}return function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function e(){this.constructor=t}b(t,n),t.prototype=null===n?Object.create(n):(e.prototype=n.prototype,new e)}(n,t),n}(x);function k(){return g}function E(){var t,n;return(null===(t=k())||void 0===t?void 0:t.vm)||(null===(n=V())||void 0===n?void 0:n.proxy)}var R=void 0;try{var C=require("vue");C&&U(C)?R=C:C&&"default"in C&&U(C.default)&&(R=C.default)}catch(t){}var M=null,P=null,D=!0,A="__composition_api_installed__";function U(t){return t&&_(t)&&"Vue"===t.name}function B(){return M}function T(t){if(D){var n=P;null==n||n.scope.off(),null==(P=t)||P.scope.on()}}function V(){return P}var W,z=new WeakMap;function F(t){if(z.has(t))return z.get(t);var n={proxy:t,update:t.$forceUpdate,type:t.$options,uid:t._uid,emit:t.$emit.bind(t),parent:null,root:null};!function(t){if(!t.scope){var n=new x(t.proxy);t.scope=n,t.proxy.$on("hook:destroyed",(function(){return n.stop()}))}t.scope}(n);return["data","props","attrs","refs","vnode","slots"].forEach((function(e){f(n,e,{get:function(){return t["$".concat(e)]}})})),f(n,"isMounted",{get:function(){return t._isMounted}}),f(n,"isUnmounted",{get:function(){return t._isDestroyed}}),f(n,"isDeactivated",{get:function(){return t._inactive}}),f(n,"emitted",{get:function(){return t._events}}),z.set(t,n),t.$parent&&(n.parent=F(t.$parent)),t.$root&&(n.root=F(t.$root)),n}function I(t,n){return n=n||V()}function K(t,n){void 0===n&&(n={});var e=t.config.silent;t.config.silent=!0;var r=new t(n);return t.config.silent=e,r}function q(t,n){return function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];if(t.$scopedSlots[n])return t.$scopedSlots[n].apply(t,e)}}function Q(t){return i?Symbol.for(t):t}var G=Q("composition-api.preFlushQueue"),H=Q("composition-api.postFlushQueue"),J="composition-api.refKey",L=new WeakMap,N=new WeakMap,X=new WeakMap;function Y(t,n,e){var r=B().util;r.warn;var o=r.defineReactive,i=t.__ob__;function u(){i&&p(e)&&!c(e,"__ob__")&&dt(e)}if(l(t)){if(d(n))return t.length=Math.max(t.length,n),t.splice(n,1,e),u(),e;if("length"===n&&e!==t.length)return t.length=e,null==i||i.dep.notify(),e}return n in t&&!(n in Object.prototype)?(t[n]=e,u(),e):t._isVue||i&&i.vmCount?e:i?(o(i.value,n,e),st(t,n,e),u(),i.dep.notify(),e):(t[n]=e,e)}var Z=!1;function tt(t){Z=t}var nt=function(t){f(this,"value",{get:t.get,set:t.set})};function et(t,n,e){void 0===n&&(n=!1),void 0===e&&(e=!1);var r=new nt(t);e&&(r.effect=!0);var o=Object.seal(r);return n&&X.set(o,!0),o}function rt(t){var n;if(ot(t))return t;var e=_t(((n={})[J]=t,n));return et({get:function(){return e[J]},set:function(t){return e[J]=t}})}function ot(t){return t instanceof nt}function it(t){return ot(t)?t.value:t}function ut(t){if(!y(t))return t;var n={};for(var e in t)n[e]=ft(t,e);return n}function ft(t,n){n in t||Y(t,n,void 0);var e=t[n];return ot(e)?e:et({get:function(){return t[n]},set:function(e){return t[n]=e}})}function at(t){var n;return Boolean(t&&c(t,"__ob__")&&"object"==typeof t.__ob__&&(null===(n=t.__ob__)||void 0===n?void 0:n.__raw__))}function ct(t){var n;return Boolean(t&&c(t,"__ob__")&&"object"==typeof t.__ob__&&!(null===(n=t.__ob__)||void 0===n?void 0:n.__raw__))}function lt(t){if(!(!y(t)||at(t)||l(t)||ot(t)||function(t){var n=B();return n&&t instanceof n}(t)||L.has(t))){L.set(t,!0);for(var n=Object.keys(t),e=0;e<n.length;e++)st(t,n[e])}}function st(t,n,e){if("__ob__"!==n&&!at(t[n])){var r,o,i=Object.getOwnPropertyDescriptor(t,n);if(i){if(!1===i.configurable)return;r=i.get,o=i.set,r&&!o||2!==arguments.length||(e=t[n])}lt(e),f(t,n,{get:function(){var o=r?r.call(t):e;return n!==J&&ot(o)?o.value:o},set:function(i){r&&!o||(n!==J&&ot(e)&&!ot(i)?e.value=i:o?(o.call(t,i),e=i):e=i,lt(i))}})}}function vt(t){var n,e=M||R;e.observable?n=e.observable(t):n=K(e,{data:{$$state:t}})._data.$$state;return c(n,"__ob__")||dt(n),n}function dt(t,n){var e,r;if(void 0===n&&(n=new Set),!n.has(t)&&!c(t,"__ob__")&&Object.isExtensible(t)){a(t,"__ob__",function(t){void 0===t&&(t={});return{value:t,dep:{notify:u,depend:u,addSub:u,removeSub:u}}}(t)),n.add(t);try{for(var o=w(Object.keys(t)),i=o.next();!i.done;i=o.next()){var f=t[i.value];(y(f)||l(f))&&!at(f)&&Object.isExtensible(f)&&dt(f,n)}}catch(t){e={error:t}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}}}function pt(){return vt({}).__ob__}function yt(t){var n,e;if(!p(t))return t;if(!y(t)&&!l(t)||at(t)||!Object.isExtensible(t))return t;var r=vt(l(t)?[]:{}),o=r.__ob__,i=function(n){var e,i,u=t[n],a=Object.getOwnPropertyDescriptor(t,n);if(a){if(!1===a.configurable)return"continue";e=a.get,i=a.set}f(r,n,{get:function(){var n,r=e?e.call(t):u;return null===(n=o.dep)||void 0===n||n.depend(),r},set:function(n){var r;if(!e||i){var f=e?e.call(t):u;(Z||f!==n)&&(i?i.call(t,n):u=n,null===(r=o.dep)||void 0===r||r.notify())}}})};try{for(var u=w(Object.keys(t)),a=u.next();!a.done;a=u.next()){i(a.value)}}catch(t){n={error:t}}finally{try{a&&!a.done&&(e=u.return)&&e.call(u)}finally{if(n)throw n.error}}return r}function _t(t){if(!p(t))return t;if(!y(t)&&!l(t)||at(t)||!Object.isExtensible(t))return t;var n=vt(t);return lt(n),n}function ht(t){return function(n,e){var r,o=I("on".concat((r=t)[0].toUpperCase()+r.slice(1)),e);return o&&function(t,n,e,r){var o=n.proxy.$options,i=t.config.optionMergeStrategies[e],u=function(t,n){return function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];var o=V();T(t);try{return n.apply(void 0,j([],$(e),!1))}finally{T(o)}}}(n,r);return o[e]=i(o[e],u),u}(B(),o,t,n)}}var bt,gt=ht("beforeMount"),mt=ht("mounted"),wt=ht("beforeUpdate"),$t=ht("updated"),jt=ht("beforeDestroy"),Ot=ht("destroyed"),xt=ht("errorCaptured"),St=ht("activated"),kt=ht("deactivated"),Et=ht("serverPrefetch");function Rt(){Pt(this,G)}function Ct(){Pt(this,H)}function Mt(){var t=E();return t?function(t){return void 0!==t[G]}(t)||function(t){t[G]=[],t[H]=[],t.$on("hook:beforeUpdate",Rt),t.$on("hook:updated",Ct)}(t):(bt||(bt=K(B())),t=bt),t}function Pt(t,n){for(var e=t[n],r=0;r<e.length;r++)e[r]();e.length=0}function Dt(t,n,e){var r=function(){t.$nextTick((function(){t[G].length&&Pt(t,G),t[H].length&&Pt(t,H)}))};switch(e){case"pre":r(),t[G].push(n);break;case"post":r(),t[H].push(n);break;default:!function(t,n){if(!t)throw new Error("[vue-composition-api] ".concat(n))}(!1,'flush must be one of ["post", "pre", "sync"], but got '.concat(e))}}function At(t,n){var e=t.teardown;t.teardown=function(){for(var r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];e.apply(t,r),n()}}function Ut(t,n,e,r){var o,i,f=r.flush,a="sync"===f,c=function(t){i=function(){try{t()}catch(t){!function(t,n,e){if("undefined"==typeof window||"undefined"==typeof console)throw t;console.error(t)}(t)}}},s=function(){i&&(i(),i=null)},v=function(n){return a||t===bt?n:function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Dt(t,(function(){n.apply(void 0,j([],$(e),!1))}),f)}};if(null===e){var d=!1,p=function(t,n,e,r){var o=t._watchers.length;return t.$watch(n,e,{immediate:r.immediateInvokeCallback,deep:r.deep,lazy:r.noRun,sync:r.sync,before:r.before}),t._watchers[o]}(t,(function(){if(!d)try{d=!0,n(c)}finally{d=!1}}),u,{deep:r.deep||!1,sync:a,before:s});At(p,s),p.lazy=!1;var y=p.get.bind(p);return p.get=v(y),function(){p.teardown()}}var h,b=r.deep,g=!1;if(ot(n)?h=function(){return n.value}:ct(n)?(h=function(){return n},b=!0):l(n)?(g=!0,h=function(){return n.map((function(t){return ot(t)?t.value:ct(t)?Tt(t):_(t)?t():u}))}):h=_(n)?n:u,b){var m=h;h=function(){return Tt(m())}}var w=function(t,n){if(b||!g||!t.every((function(t,e){return Object.is(t,n[e])})))return s(),e(t,n,c)},O=v(w);if(r.immediate){var x=O,S=function(t,n){return S=x,w(t,l(t)?[]:n)};O=function(t,n){return S(t,n)}}var k=t.$watch(h,O,{immediate:r.immediate,deep:b,sync:a}),E=t._watchers[t._watchers.length-1];return ct(E.value)&&(null===(o=E.value.__ob__)||void 0===o?void 0:o.dep)&&b&&E.value.__ob__.dep.addSub({update:function(){E.run()}}),At(E,s),function(){k()}}function Bt(t,n){var e=function(t){return m({flush:"pre"},t)}(n);return Ut(Mt(),t,null,e)}function Tt(t,n){if(void 0===n&&(n=new Set),!p(t)||n.has(t))return t;if(n.add(t),ot(t))Tt(t.value,n);else if(l(t))for(var e=0;e<t.length;e++)Tt(t[e],n);else if("[object Set]"===v(t)||function(t){return"[object Map]"===v(t)}(t))t.forEach((function(t){Tt(t,n)}));else if(y(t))for(var r in t)Tt(t[r],n);return t}var Vt={};var Wt={},zt=function(t){var n;void 0===t&&(t="$style");var e=V();if(!e)return Wt;var r=null===(n=e.proxy)||void 0===n?void 0:n[t];return r||Wt},Ft=zt;var It;function Kt(){return V().setupContext}var qt={set:function(t,n,e){(t.__composition_api_state__=t.__composition_api_state__||{})[n]=e},get:function(t,n){return(t.__composition_api_state__||{})[n]}};function Qt(t){var n=qt.get(t,"rawBindings")||{};if(n&&Object.keys(n).length){for(var e=t.$refs,r=qt.get(t,"refs")||[],o=0;o<r.length;o++){var i=n[a=r[o]];!e[a]&&i&&ot(i)&&(i.value=null)}var u=Object.keys(e),f=[];for(o=0;o<u.length;o++){var a;i=n[a=u[o]];e[a]&&i&&ot(i)&&(i.value=e[a],f.push(a))}qt.set(t,"refs",f)}}function Gt(t,n){var e,r;if(t){var o=qt.get(t,"attrBindings");if(o||n){if(!o){var i=_t({});o={ctx:n,data:i},qt.set(t,"attrBindings",o),f(n,"attrs",{get:function(){return null==o?void 0:o.data},set:function(){}})}var u=t.$attrs,a=function(n){c(o.data,n)||f(o.data,n,{get:function(){return t.$attrs[n]}})};try{for(var l=w(Object.keys(u)),s=l.next();!s.done;s=l.next()){a(s.value)}}catch(t){e={error:t}}finally{try{s&&!s.done&&(r=l.return)&&r.call(l)}finally{if(e)throw e.error}}}}}function Ht(t,n){var e=t.$options._parentVnode;if(e){for(var r=qt.get(t,"slots")||[],o=function(t,n){var e;if(t){if(t._normalized)return t._normalized;for(var r in e={},t)t[r]&&"$"!==r[0]&&(e[r]=!0)}else e={};for(var r in n)r in e||(e[r]=!0);return e}(e.data.scopedSlots,t.$slots),i=0;i<r.length;i++){o[f=r[i]]||delete n[f]}var u=Object.keys(o);for(i=0;i<u.length;i++){var f;n[f=u[i]]||(n[f]=q(t,f))}qt.set(t,"slots",u)}}function Jt(t,n,e){var r=V();T(t);try{return n(t)}catch(t){if(!e)throw t;e(t)}finally{T(r)}}function Lt(t){function n(t,e){if(void 0===e&&(e=new Set),!e.has(t)&&y(t)&&!ot(t)&&!ct(t)&&!at(t)){var r=B().util.defineReactive;Object.keys(t).forEach((function(o){var i=t[o];r(t,o,i),i&&(e.add(i),n(i,e))}))}}function e(t,n){return void 0===n&&(n=new Map),n.has(t)?n.get(t):(n.set(t,!1),l(t)&&ct(t)?(n.set(t,!0),!0):!(!y(t)||at(t)||ot(t))&&Object.keys(t).some((function(r){return e(t[r],n)})))}t.mixin({beforeCreate:function(){var t=this,r=t.$options,o=r.setup,i=r.render;i&&(r.render=function(){for(var n=this,e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return Jt(F(t),(function(){return i.apply(n,e)}))});if(!o)return;if(!_(o))return;var u=r.data;r.data=function(){return function(t,r){void 0===r&&(r={});var o,i=t.$options.setup,u=function(t){var n={slots:{}},e=["emit"];return["root","parent","refs","listeners","isServer","ssrContext"].forEach((function(e){var r="$".concat(e);f(n,e,{get:function(){return t[r]},set:function(){}})})),Gt(t,n),e.forEach((function(e){var r="$".concat(e);f(n,e,{get:function(){return function(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];t[r].apply(t,n)}}})})),n}(t),s=F(t);if(s.setupContext=u,a(r,"__ob__",pt()),Ht(t,u.slots),Jt(s,(function(){o=i(r,u)})),!o)return;if(_(o)){var v=o;return void(t.$options.render=function(){return Ht(t,u.slots),Jt(s,(function(){return v()}))})}if(p(o)){ct(o)&&(o=ut(o)),qt.set(t,"rawBindings",o);var d=o;Object.keys(d).forEach((function(r){var o=d[r];if(!ot(o))if(ct(o))l(o)&&(o=rt(o));else if(_(o)){var i=o;o=o.bind(t),Object.keys(i).forEach((function(t){o[t]=i[t]}))}else p(o)?e(o)&&n(o):o=rt(o);!function(t,n,e){var r=t.$options.props;n in t||r&&c(r,n)||(ot(e)?f(t,n,{get:function(){return e.value},set:function(t){e.value=t}}):f(t,n,{get:function(){return ct(e)&&e.__ob__.dep.depend(),e},set:function(t){e=t}}))}(t,r,o)}))}}(t,t.$props),_(u)?u.call(t,t):u||{}}},mounted:function(){Qt(this)},beforeUpdate:function(){Gt(this)},updated:function(){var t;Qt(this),(null===(t=this.$vnode)||void 0===t?void 0:t.context)&&Qt(this.$vnode.context)}})}function Nt(t,n){if(!t)return n;if(!n)return t;for(var e,r,o,u=i?Reflect.ownKeys(t):Object.keys(t),f=0;f<u.length;f++)"__ob__"!==(e=u[f])&&(r=n[e],o=t[e],c(n,e)?r!==o&&y(r)&&!ot(r)&&y(o)&&!ot(o)&&Nt(o,r):n[e]=o);return n}function Xt(t){(function(t){return M&&c(t,A)})(t)||(t.config.optionMergeStrategies.setup=function(t,n){return function(e,r){return Nt(_(t)?t(e,r)||{}:void 0,_(n)?n(e,r)||{}:void 0)}},function(t){M=t,Object.defineProperty(t,A,{configurable:!0,writable:!0,value:!0})}(t),Lt(t))}var Yt={install:function(t){return Xt(t)}};"undefined"!=typeof window&&window.Vue&&window.Vue.use(Yt),t.EffectScope=S,t.computed=function(t){var n,e,r,o,i=E();if(_(t)?n=t:(n=t.get,e=t.set),i&&!i.$isServer){var f,a=function(){if(!W){var t=K(B(),{computed:{value:function(){return 0}}}),n=t._computedWatchers.value.constructor,e=t._data.__ob__.dep.constructor;W={Watcher:n,Dep:e},t.$destroy()}return W}(),c=a.Watcher,l=a.Dep;o=function(){return f||(f=new c(i,n,u,{lazy:!0})),f.dirty&&f.evaluate(),l.target&&f.depend(),f.value},r=function(t){e&&e(t)}}else{var s=K(B(),{computed:{$$state:{get:n,set:e}}});i&&i.$on("hook:destroyed",(function(){return s.$destroy()})),o=function(){return s.$$state},r=function(t){s.$$state=t}}return et({get:o,set:r},!e,!0)},t.createApp=function(t,n){void 0===n&&(n=void 0);var e=B(),r=void 0,o={config:e.config,use:e.use.bind(e),mixin:e.mixin.bind(e),component:e.component.bind(e),directive:function(t,n){return n?(e.directive(t,n),o):e.directive(t)},mount:function(o,i){return r||((r=new e(m({propsData:n},t))).$mount(o,i),r)},unmount:function(){r&&(r.$destroy(),r=void 0)}};return o},t.createRef=et,t.customRef=function(t){var n=rt(0);return et(t((function(){n.value}),(function(){++n.value})))},t.default=Yt,t.defineAsyncComponent=function(t){_(t)&&(t={loader:t});var n=t.loader,e=t.loadingComponent,r=t.errorComponent,o=t.delay,i=void 0===o?200:o,u=t.timeout;t.suspensible;var f=t.onError,a=null,c=0,l=function(){var t;return a||(t=a=n().catch((function(t){if(t=t instanceof Error?t:new Error(String(t)),f)return new Promise((function(n,e){f(t,(function(){return n((c++,a=null,l()))}),(function(){return e(t)}),c+1)}));throw t})).then((function(n){return t!==a&&a?a:(n&&(n.__esModule||"Module"===n[Symbol.toStringTag])&&(n=n.default),n)})))};return function(){return{component:l(),delay:i,timeout:u,error:r,loading:e}}},t.defineComponent=function(t){return t},t.del=function(t,n){if(B().util.warn,l(t)&&d(n))t.splice(n,1);else{var e=t.__ob__;t._isVue||e&&e.vmCount||c(t,n)&&(delete t[n],e&&e.dep.notify())}},t.effectScope=function(t){return new S(t)},t.getCurrentInstance=V,t.getCurrentScope=k,t.h=function(){for(var t,n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var r=null===(t=V())||void 0===t?void 0:t.proxy;return r?r.$createElement.apply(r,n):(It||(It=K(B()).$createElement),It.apply(It,n))},t.inject=function(t,n,e){var r;void 0===e&&(e=!1);var o=null===(r=V())||void 0===r?void 0:r.proxy;if(o){if(!t)return n;var i=function(t,n){for(var e=n;e;){if(e._provided&&c(e._provided,t))return e._provided[t];e=e.$parent}return Vt}(t,o);return i!==Vt?i:e&&_(n)?n():n}},t.isRaw=at,t.isReactive=ct,t.isReadonly=function(t){return X.has(t)},t.isRef=ot,t.markRaw=function(t){if(!y(t)&&!l(t)||!Object.isExtensible(t))return t;var n=pt();return n.__raw__=!0,a(t,"__ob__",n),N.set(t,!0),t},t.nextTick=function(){for(var t,n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];return null===(t=B())||void 0===t?void 0:t.nextTick.apply(this,n)},t.onActivated=St,t.onBeforeMount=gt,t.onBeforeUnmount=jt,t.onBeforeUpdate=wt,t.onDeactivated=kt,t.onErrorCaptured=xt,t.onMounted=mt,t.onScopeDispose=function(t){g&&g.cleanups.push(t)},t.onServerPrefetch=Et,t.onUnmounted=Ot,t.onUpdated=$t,t.provide=function(t,n){var e,r=null===(e=I())||void 0===e?void 0:e.proxy;if(r){if(!r._provided){var o={};f(r,"_provided",{get:function(){return o},set:function(t){return Object.assign(o,t)}})}r._provided[t]=n}},t.proxyRefs=function(t){var n,e,r;if(ct(t))return t;var o=_t(((n={})[J]=t,n));a(o,J,o[J],!1);var i=function(t){f(o,t,{get:function(){return ot(o[J][t])?o[J][t].value:o[J][t]},set:function(n){if(ot(o[J][t]))return o[J][t].value=it(n);o[J][t]=it(n)}})};try{for(var u=w(Object.keys(t)),c=u.next();!c.done;c=u.next()){i(c.value)}}catch(t){e={error:t}}finally{try{c&&!c.done&&(r=u.return)&&r.call(u)}finally{if(e)throw e.error}}return o},t.reactive=_t,t.readonly=function(t){return X.set(t,!0),t},t.ref=rt,t.set=Y,t.shallowReactive=yt,t.shallowReadonly=function(t){var n,e;if(!p(t))return t;if(!y(t)&&!l(t)||!Object.isExtensible(t)&&!ot(t))return t;var r=ot(t)?new nt({}):ct(t)?vt({}):{},o=_t({}).__ob__,i=function(n){var e,i=t[n],u=Object.getOwnPropertyDescriptor(t,n);if(u){if(!1===u.configurable&&!ot(t))return"continue";e=u.get}f(r,n,{get:function(){var n=e?e.call(t):i;return o.dep.depend(),n},set:function(t){}})};try{for(var u=w(Object.keys(t)),a=u.next();!a.done;a=u.next()){i(a.value)}}catch(t){n={error:t}}finally{try{a&&!a.done&&(e=u.return)&&e.call(u)}finally{if(n)throw n.error}}return X.set(r,!0),r},t.shallowRef=function(t){var n;if(ot(t))return t;var e=yt(((n={})[J]=t,n));return et({get:function(){return e[J]},set:function(t){return e[J]=t}})},t.toRaw=function(t){var n,e;return at(t)||!Object.isExtensible(t)?t:(null===(e=null===(n=t)||void 0===n?void 0:n.__ob__)||void 0===e?void 0:e.value)||t},t.toRef=ft,t.toRefs=ut,t.triggerRef=function(t){ot(t)&&(tt(!0),t.value=t.value,tt(!1))},t.unref=it,t.useAttrs=function(){return Kt().attrs},t.useCSSModule=Ft,t.useCssModule=zt,t.useSlots=function(){return Kt().slots},t.version="1.4.4",t.warn=function(t){var n;h(t,null===(n=V())||void 0===n?void 0:n.proxy)},t.watch=function(t,n,e){var r=null;_(n)?r=n:(e=n,r=null);var o=function(t){return m({immediate:!1,deep:!1,flush:"pre"},t)}(e);return Ut(Mt(),t,r,o)},t.watchEffect=Bt,t.watchPostEffect=function(t){return Bt(t,{flush:"post"})},t.watchSyncEffect=function(t){return Bt(t,{flush:"sync"})},Object.defineProperty(t,"__esModule",{value:!0})}));
function initializeMap() { var mapOptions = { center: {lat: 59.323, lng: 18.03}, zoom: 13, scrollwheel: false, navigationControl: false, mapTypeControl: false, scaleControl: false, draggable: false, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById('map'), mapOptions); var styles = [ { stylers: [ {hue: "#F47821"}, {saturation: 70} ] }, { featureType: "road", elementType: "labels", stylers: [ {visibility: "off"} ] } ]; map.setOptions({styles: styles}); var image = 'img/pin.png'; var myLatLng = new google.maps.LatLng(59.323, 18.07433); var beachMarker = new google.maps.Marker({ position: myLatLng, map: map, icon: image }); } if (window.google) { google.maps.event.addDomListener(window, 'load', initializeMap); }
import messageHandler from "baselayer/MessageHandler"; import * as API from "../API"; import store from "../store"; const FETCH_RECENT_SOURCES = "skyportal/FETCH_RECENT_SOURCES"; const FETCH_RECENT_SOURCES_OK = "skyportal/FETCH_RECENT_SOURCES_OK"; // eslint-disable-next-line import/prefer-default-export export const fetchRecentSources = () => API.GET("/api/internal/recent_sources", FETCH_RECENT_SOURCES); // Websocket message handler messageHandler.add((actionType, payload, dispatch) => { if (actionType === FETCH_RECENT_SOURCES) { dispatch(fetchRecentSources()); } }); const reducer = (state = { recentSources: undefined }, action) => { switch (action.type) { case FETCH_RECENT_SOURCES_OK: { const recentSources = action.data; return { recentSources, }; } default: return state; } }; store.injectReducer("recentSources", reducer);
import moment from 'moment' import _ from 'lodash' import Logger from './../../utils/Logger' class StockDetails { static toHTMLString(stock) { const htmlString = `<div class="alert alert-${ parseFloat(stock.c) > 0 ? "success" : "danger" }"> <div class="row"> <div class="col-xs-6"> <h4>${stock.t} <h6>${stock.c} (${stock.cp} %)</h6></h4> </div> <div class="col-xs-6"> <div class="text-right"> <h4>${stock.l_cur}</h4> <small>${moment(stock.lt_dts).format('YYYY MMM, Do hh:mm a')}</small> </div> </div> </div> </div>` return htmlString } } export default StockDetails
let loginController = ($scope, $state) => { $scope.loginUser = function() { $state.go('home'); } $scope.notyetavailable = function() { alert('This feature is currently not available.'); } } loginController.$inject = [ "$scope", "$state"]; export { loginController };
/*! * Bootstrap-select v1.11.2 (http://silviomoreto.github.io/bootstrap-select) * * Copyright 2013-2016 bootstrap-select * Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE) */ !function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(a){return b(a)}):"object"==typeof exports?module.exports=b(require("jquery")):b(jQuery)}(this,function(a){!function(a){a.fn.selectpicker.defaults={noneSelectedText:"Ei valintoja",noneResultsText:"Ei hakutuloksia {0}",countSelectedText:function(a,b){return 1==a?"{0} valittu":"{0} valitut"},maxOptionsText:function(a,b){return["Valintojen maksimimäärä ({n} saavutettu)","Ryhmän maksimimäärä ({n} saavutettu)"]},selectAllText:"Valitse kaikki",deselectAllText:"Poista kaikki",multipleSeparator:", "}}(a)});
const path = require('path'); const webpack = require('webpack'); const { CheckerPlugin } = require('awesome-typescript-loader'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); function genarateCssLoader(test, lang, options) { return { test, use: [{ loader: MiniCssExtractPlugin.loader }, 'css-loader', { loader: `${lang}-loader`, options: options || {} }] }; } module.exports = { devtool: 'cheap-source-map', target: 'web', mode: 'development', stats: 'errors-only', cache: true, // Default in watch mode resolve: { extensions: ['.ts', '.js'], alias: {} }, watchOptions: { ignored: /node_modules/ }, externals: [ { rxjs: 'rxjs', '@angular/common': 'ng.common', '@angular/compiler': 'ng.compiler', '@angular/core': 'ng.core', '@angular/http': 'ng.http', '@angular/platform-browser': 'ng.platformBrowser', '@angular/platform-browser-dynamic': 'ng.platformBrowserDynamic', '@angular/router': 'ng.router', '@angular/forms': 'ng.forms', 'app/common': 'ampApp.common', '@angular/animations': 'ng.animations' }, (context, request, callback) => { if (request.indexOf('app/') === 0) { let key = request.split('/')[1]; return callback(null, `var ampApp['${key}']`); } callback(); } ], module: { rules: [ { test: /\.ts$/, use: ['awesome-typescript-loader', 'angular2-template-loader'], exclude: /node_modules/ }, { test: /\.html$/, use: 'raw-loader' }, { test: /\.css$/, use: [{ loader: MiniCssExtractPlugin.loader }, 'css-loader'] }, genarateCssLoader(/\.styl$/, 'stylus'), genarateCssLoader(/\.less$/, 'less'), genarateCssLoader(/\.scss$/, 'sass'), genarateCssLoader(/\.sass$/, 'sass', { indentedSyntax: true }) ] }, plugins: [new CheckerPlugin()] };
/* * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development"). * This devtool is neither made for production nor for readable output files. * It uses "eval()" calls to create a separate source file in the browser devtools. * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/) * or disable the default devtool with "devtool: false". * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/). */ (self["webpackChunkAudioNode"] = self["webpackChunkAudioNode"] || []).push([["node_modules_monaco-editor_esm_vs_basic-languages_csharp_csharp_js"],{ /***/ "./node_modules/monaco-editor/esm/vs/basic-languages/csharp/csharp.js": /*!****************************************************************************!*\ !*** ./node_modules/monaco-editor/esm/vs/basic-languages/csharp/csharp.js ***! \****************************************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"conf\": () => (/* binding */ conf),\n/* harmony export */ \"language\": () => (/* binding */ language)\n/* harmony export */ });\n/*---------------------------------------------------------------------------------------------\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License. See License.txt in the project root for license information.\r\n *--------------------------------------------------------------------------------------------*/\r\nvar conf = {\r\n wordPattern: /(-?\\d*\\.\\d\\w*)|([^\\`\\~\\!\\#\\$\\%\\^\\&\\*\\(\\)\\-\\=\\+\\[\\{\\]\\}\\\\\\|\\;\\:\\'\\\"\\,\\.\\<\\>\\/\\?\\s]+)/g,\r\n comments: {\r\n lineComment: '//',\r\n blockComment: ['/*', '*/']\r\n },\r\n brackets: [\r\n ['{', '}'],\r\n ['[', ']'],\r\n ['(', ')']\r\n ],\r\n autoClosingPairs: [\r\n { open: '{', close: '}' },\r\n { open: '[', close: ']' },\r\n { open: '(', close: ')' },\r\n { open: \"'\", close: \"'\", notIn: ['string', 'comment'] },\r\n { open: '\"', close: '\"', notIn: ['string', 'comment'] }\r\n ],\r\n surroundingPairs: [\r\n { open: '{', close: '}' },\r\n { open: '[', close: ']' },\r\n { open: '(', close: ')' },\r\n { open: '<', close: '>' },\r\n { open: \"'\", close: \"'\" },\r\n { open: '\"', close: '\"' }\r\n ],\r\n folding: {\r\n markers: {\r\n start: new RegExp('^\\\\s*#region\\\\b'),\r\n end: new RegExp('^\\\\s*#endregion\\\\b')\r\n }\r\n }\r\n};\r\nvar language = {\r\n defaultToken: '',\r\n tokenPostfix: '.cs',\r\n brackets: [\r\n { open: '{', close: '}', token: 'delimiter.curly' },\r\n { open: '[', close: ']', token: 'delimiter.square' },\r\n { open: '(', close: ')', token: 'delimiter.parenthesis' },\r\n { open: '<', close: '>', token: 'delimiter.angle' }\r\n ],\r\n keywords: [\r\n 'extern',\r\n 'alias',\r\n 'using',\r\n 'bool',\r\n 'decimal',\r\n 'sbyte',\r\n 'byte',\r\n 'short',\r\n 'ushort',\r\n 'int',\r\n 'uint',\r\n 'long',\r\n 'ulong',\r\n 'char',\r\n 'float',\r\n 'double',\r\n 'object',\r\n 'dynamic',\r\n 'string',\r\n 'assembly',\r\n 'is',\r\n 'as',\r\n 'ref',\r\n 'out',\r\n 'this',\r\n 'base',\r\n 'new',\r\n 'typeof',\r\n 'void',\r\n 'checked',\r\n 'unchecked',\r\n 'default',\r\n 'delegate',\r\n 'var',\r\n 'const',\r\n 'if',\r\n 'else',\r\n 'switch',\r\n 'case',\r\n 'while',\r\n 'do',\r\n 'for',\r\n 'foreach',\r\n 'in',\r\n 'break',\r\n 'continue',\r\n 'goto',\r\n 'return',\r\n 'throw',\r\n 'try',\r\n 'catch',\r\n 'finally',\r\n 'lock',\r\n 'yield',\r\n 'from',\r\n 'let',\r\n 'where',\r\n 'join',\r\n 'on',\r\n 'equals',\r\n 'into',\r\n 'orderby',\r\n 'ascending',\r\n 'descending',\r\n 'select',\r\n 'group',\r\n 'by',\r\n 'namespace',\r\n 'partial',\r\n 'class',\r\n 'field',\r\n 'event',\r\n 'method',\r\n 'param',\r\n 'property',\r\n 'public',\r\n 'protected',\r\n 'internal',\r\n 'private',\r\n 'abstract',\r\n 'sealed',\r\n 'static',\r\n 'struct',\r\n 'readonly',\r\n 'volatile',\r\n 'virtual',\r\n 'override',\r\n 'params',\r\n 'get',\r\n 'set',\r\n 'add',\r\n 'remove',\r\n 'operator',\r\n 'true',\r\n 'false',\r\n 'implicit',\r\n 'explicit',\r\n 'interface',\r\n 'enum',\r\n 'null',\r\n 'async',\r\n 'await',\r\n 'fixed',\r\n 'sizeof',\r\n 'stackalloc',\r\n 'unsafe',\r\n 'nameof',\r\n 'when'\r\n ],\r\n namespaceFollows: ['namespace', 'using'],\r\n parenFollows: ['if', 'for', 'while', 'switch', 'foreach', 'using', 'catch', 'when'],\r\n operators: [\r\n '=',\r\n '??',\r\n '||',\r\n '&&',\r\n '|',\r\n '^',\r\n '&',\r\n '==',\r\n '!=',\r\n '<=',\r\n '>=',\r\n '<<',\r\n '+',\r\n '-',\r\n '*',\r\n '/',\r\n '%',\r\n '!',\r\n '~',\r\n '++',\r\n '--',\r\n '+=',\r\n '-=',\r\n '*=',\r\n '/=',\r\n '%=',\r\n '&=',\r\n '|=',\r\n '^=',\r\n '<<=',\r\n '>>=',\r\n '>>',\r\n '=>'\r\n ],\r\n symbols: /[=><!~?:&|+\\-*\\/\\^%]+/,\r\n // escape sequences\r\n escapes: /\\\\(?:[abfnrtv\\\\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,\r\n // The main tokenizer for our languages\r\n tokenizer: {\r\n root: [\r\n // identifiers and keywords\r\n [\r\n /\\@?[a-zA-Z_]\\w*/,\r\n {\r\n cases: {\r\n '@namespaceFollows': {\r\n token: 'keyword.$0',\r\n next: '@namespace'\r\n },\r\n '@keywords': {\r\n token: 'keyword.$0',\r\n next: '@qualified'\r\n },\r\n '@default': { token: 'identifier', next: '@qualified' }\r\n }\r\n }\r\n ],\r\n // whitespace\r\n { include: '@whitespace' },\r\n // delimiters and operators\r\n [\r\n /}/,\r\n {\r\n cases: {\r\n '$S2==interpolatedstring': {\r\n token: 'string.quote',\r\n next: '@pop'\r\n },\r\n '$S2==litinterpstring': {\r\n token: 'string.quote',\r\n next: '@pop'\r\n },\r\n '@default': '@brackets'\r\n }\r\n }\r\n ],\r\n [/[{}()\\[\\]]/, '@brackets'],\r\n [/[<>](?!@symbols)/, '@brackets'],\r\n [\r\n /@symbols/,\r\n {\r\n cases: {\r\n '@operators': 'delimiter',\r\n '@default': ''\r\n }\r\n }\r\n ],\r\n // numbers\r\n [/[0-9_]*\\.[0-9_]+([eE][\\-+]?\\d+)?[fFdD]?/, 'number.float'],\r\n [/0[xX][0-9a-fA-F_]+/, 'number.hex'],\r\n [/0[bB][01_]+/, 'number.hex'],\r\n [/[0-9_]+/, 'number'],\r\n // delimiter: after number because of .\\d floats\r\n [/[;,.]/, 'delimiter'],\r\n // strings\r\n [/\"([^\"\\\\]|\\\\.)*$/, 'string.invalid'],\r\n [/\"/, { token: 'string.quote', next: '@string' }],\r\n [/\\$\\@\"/, { token: 'string.quote', next: '@litinterpstring' }],\r\n [/\\@\"/, { token: 'string.quote', next: '@litstring' }],\r\n [/\\$\"/, { token: 'string.quote', next: '@interpolatedstring' }],\r\n // characters\r\n [/'[^\\\\']'/, 'string'],\r\n [/(')(@escapes)(')/, ['string', 'string.escape', 'string']],\r\n [/'/, 'string.invalid']\r\n ],\r\n qualified: [\r\n [\r\n /[a-zA-Z_][\\w]*/,\r\n {\r\n cases: {\r\n '@keywords': { token: 'keyword.$0' },\r\n '@default': 'identifier'\r\n }\r\n }\r\n ],\r\n [/\\./, 'delimiter'],\r\n ['', '', '@pop']\r\n ],\r\n namespace: [\r\n { include: '@whitespace' },\r\n [/[A-Z]\\w*/, 'namespace'],\r\n [/[\\.=]/, 'delimiter'],\r\n ['', '', '@pop']\r\n ],\r\n comment: [\r\n [/[^\\/*]+/, 'comment'],\r\n // [/\\/\\*/, 'comment', '@push' ], // no nested comments :-(\r\n ['\\\\*/', 'comment', '@pop'],\r\n [/[\\/*]/, 'comment']\r\n ],\r\n string: [\r\n [/[^\\\\\"]+/, 'string'],\r\n [/@escapes/, 'string.escape'],\r\n [/\\\\./, 'string.escape.invalid'],\r\n [/\"/, { token: 'string.quote', next: '@pop' }]\r\n ],\r\n litstring: [\r\n [/[^\"]+/, 'string'],\r\n [/\"\"/, 'string.escape'],\r\n [/\"/, { token: 'string.quote', next: '@pop' }]\r\n ],\r\n litinterpstring: [\r\n [/[^\"{]+/, 'string'],\r\n [/\"\"/, 'string.escape'],\r\n [/{{/, 'string.escape'],\r\n [/}}/, 'string.escape'],\r\n [/{/, { token: 'string.quote', next: 'root.litinterpstring' }],\r\n [/\"/, { token: 'string.quote', next: '@pop' }]\r\n ],\r\n interpolatedstring: [\r\n [/[^\\\\\"{]+/, 'string'],\r\n [/@escapes/, 'string.escape'],\r\n [/\\\\./, 'string.escape.invalid'],\r\n [/{{/, 'string.escape'],\r\n [/}}/, 'string.escape'],\r\n [/{/, { token: 'string.quote', next: 'root.interpolatedstring' }],\r\n [/\"/, { token: 'string.quote', next: '@pop' }]\r\n ],\r\n whitespace: [\r\n [/^[ \\t\\v\\f]*#((r)|(load))(?=\\s)/, 'directive.csx'],\r\n [/^[ \\t\\v\\f]*#\\w.*$/, 'namespace.cpp'],\r\n [/[ \\t\\v\\f\\r\\n]+/, ''],\r\n [/\\/\\*/, 'comment', '@comment'],\r\n [/\\/\\/.*$/, 'comment']\r\n ]\r\n }\r\n};\r\n\n\n//# sourceURL=webpack://AudioNode/./node_modules/monaco-editor/esm/vs/basic-languages/csharp/csharp.js?"); /***/ }) }]);
/** * 对象数组根据属性去重 * @param {*} data * @returns [] */ export function arrayClearReapt (data, key) { let arrs = data let newArrs = [] for(let i = 0; i < arrs.length; i++) { let flag = false for(let j = i + 1; j < arrs.length; j++) { if (arrs[i][key] === arrs[j][key]) { flag = true } } if (!flag) newArrs.push(arrs[i]) } return newArrs }
// updater.js // // Updates the state of the world // // Copyright 2013, E14N (https://e14n.com/) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var _ = require("underscore"), async = require("async"), PumpIOClientApp = require("pump.io-client-app"), User = PumpIOClientApp.User, Host = PumpIOClientApp.Host, StatusNetUser = require("../models/statusnetuser"); var ignore = function(err) {}; var S = 1000; var M = 60 * S; var H = 60 * M; var Updater = function(options) { var log = options.log.child({component: "updater"}), site = options.site, updateAll = function() { log.info("Start queueing users"); StatusNetUser.scan( function(snu) { q.push(snu, function(err) { if (err) { log.error(err); } else { log.info({snu: snu.id}, "Done updating"); } }); }, function(err) { if (err) { log.error(err); } else { log.info("Done queueing users"); } } ); }, updateFollowing = function(snu, callback) { snu.updateFollowing(site, callback); }, q = async.queue(updateFollowing, 25); this.start = function() { // Do this every 12 hours setInterval(updateAll, 12 * H); // Do one at the beginning updateAll(); return; }; }; module.exports = Updater;
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("@artezio/observable-react"),require("@artezio/models")):"function"==typeof define&&define.amd?define(["react","@artezio/observable-react","@artezio/models"],t):"object"==typeof exports?exports.Designer=t(require("react"),require("@artezio/observable-react"),require("@artezio/models")):e.Designer=t(e.react,e["@artezio/observable-react"],e["@artezio/models"])}(window,(function(e,t,n){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=12)}([function(t,n){t.exports=e},function(e,n){e.exports=t},function(e,t,n){"use strict";n.r(t),function(e,r){n.d(t,"Form",(function(){return Xn})),n.d(t,"FormProvider",(function(){return $n})),n.d(t,"withFormApi",(function(){return sr})),n.d(t,"withFormState",(function(){return ur})),n.d(t,"withFieldApi",(function(){return mr})),n.d(t,"withFieldState",(function(){return pr})),n.d(t,"withRadioGroup",(function(){return vr})),n.d(t,"asField",(function(){return gr})),n.d(t,"useForm",(function(){return Yn})),n.d(t,"useField",(function(){return rr})),n.d(t,"useFieldApi",(function(){return dr})),n.d(t,"useFieldState",(function(){return hr})),n.d(t,"useFormApi",(function(){return zn})),n.d(t,"useFormState",(function(){return Kn})),n.d(t,"Text",(function(){return Er})),n.d(t,"Radio",(function(){return wr})),n.d(t,"TextArea",(function(){return Cr})),n.d(t,"Select",(function(){return xr})),n.d(t,"Option",(function(){return Ir})),n.d(t,"Checkbox",(function(){return Fr})),n.d(t,"RadioGroup",(function(){return Nr})),n.d(t,"BasicText",(function(){return yr})),n.d(t,"BasicRadio",(function(){return _r})),n.d(t,"BasicRadioGroup",(function(){return Mr})),n.d(t,"BasicTextArea",(function(){return Or})),n.d(t,"BasicSelect",(function(){return Sr})),n.d(t,"BasicCheckbox",(function(){return Tr})),n.d(t,"Scope",(function(){return Jn})),n.d(t,"ArrayField",(function(){return lr})),n.d(t,"useArrayField",(function(){return ar}));var i=n(0),o=n.n(i),a=n(11);function l(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function u(e,t,n){return t&&s(e.prototype,t),n&&s(e,n),e}function c(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function d(){return(d=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}function f(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){c(e,t,n[t])}))}return e}function h(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&m(e,t)}function p(e){return(p=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function m(e,t){return(m=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function v(e,t){if(null==e)return{};var n,r,i=function(e,t){if(null==e)return{};var n,r,i={},o=Object.keys(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||(i[n]=e[n]);return i}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function g(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function b(e,t){return!t||"object"!=typeof t&&"function"!=typeof t?g(e):t}function y(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=[],r=!0,i=!1,o=void 0;try{for(var a,l=e[Symbol.iterator]();!(r=(a=l.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){i=!0,o=e}finally{try{r||null==l.return||l.return()}finally{if(i)throw o}}return n}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function E(e){return function(e){if(Array.isArray(e)){for(var t=0,n=new Array(e.length);t<e.length;t++)n[t]=e[t];return n}}(e)||function(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}var _="undefined"!=typeof window?window:void 0!==e?e:"undefined"!=typeof self?self:{};function w(e,t){return e(t={exports:{}},t.exports),t.exports}var O=w((function(e){function t(e,t){for(var n=0,r=0;r<e.length;r++)n=(n<<5)-n+e.charCodeAt(r),n|=0;return t[Math.abs(n)%t.length]}function n(e,t){var n=t.namespace;if(t.useColors){var r=t.color,i=" ".concat("[3"+(r<8?r:"8;5;"+r),";1m").concat(n," ");e[0]=i+e[0].split("\n").join("\n"+i)}else e[0]=n+" "+e[0]}function i(e,t){if(e[0]=(t.useColors?"%c":"")+t.namespace,t.useColors){var n="color: "+t.color,r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,(function(e){"%%"!==e&&(r++,"%c"===e&&(i=r))})),e.splice(i,0,n)}}var o=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function a(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,n=arguments.length>1?arguments[1]:void 0;return function(){for(var r=arguments.length,i=new Array(r),o=0;o<r;o++)i[o]=arguments[o];e&&i.unshift(e);var a=n.namespaces.split(",").map((function(e){return"*"===e[e.length-1]?new RegExp("^"+e.slice(0,e.length-1)+".*$"):new RegExp("^"+e+"$")}));a.some((function(t){return t.test(e)})),t(e,n.colors),n.useColors}}void 0===r||"renderer"===r.type||!0===r.browser||r.__nwjs?e.exports=function(e){return a(e,function(){var e;try{e=localStorage.getItem("debug")}catch(e){}return!e&&void 0!==r&&"env"in r&&(e=r.env.DEBUG),{namespaces:e||"",colors:o,useColors:!0,formatArgs:i}}())}:e.exports=function(e){return a(e,{namespaces:r.env.DEBUG||"",colors:[6,2,3,4,5,1],useColors:!0,formatArgs:n})}})),C="object"==typeof _&&_&&_.Object===Object&&_,A="object"==typeof self&&self&&self.Object===Object&&self,S=C||A||Function("return this")(),x=S.Symbol,I=Object.prototype,T=I.hasOwnProperty,F=I.toString,M=x?x.toStringTag:void 0;var N=function(e){var t=T.call(e,M),n=e[M];try{e[M]=void 0;var r=!0}catch(e){}var i=F.call(e);return r&&(t?e[M]=n:delete e[M]),i},D=Object.prototype.toString;var j=function(e){return D.call(e)},P="[object Null]",k="[object Undefined]",R=x?x.toStringTag:void 0;var L=function(e){return null==e?void 0===e?k:P:R&&R in Object(e)?N(e):j(e)};var B=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)},V="[object AsyncFunction]",q="[object Function]",G="[object GeneratorFunction]",W="[object Proxy]";var $,H=function(e){if(!B(e))return!1;var t=L(e);return t==q||t==G||t==V||t==W},U=S["__core-js_shared__"],Y=($=/[^.]+$/.exec(U&&U.keys&&U.keys.IE_PROTO||""))?"Symbol(src)_1."+$:"";var Q=function(e){return!!Y&&Y in e},X=Function.prototype.toString;var z=function(e){if(null!=e){try{return X.call(e)}catch(e){}try{return e+""}catch(e){}}return""},K=/^\[object .+?Constructor\]$/,J=Function.prototype,Z=Object.prototype,ee=J.toString,te=Z.hasOwnProperty,ne=RegExp("^"+ee.call(te).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");var re=function(e){return!(!B(e)||Q(e))&&(H(e)?ne:K).test(z(e))};var ie=function(e,t){return null==e?void 0:e[t]};var oe=function(e,t){var n=ie(e,t);return re(n)?n:void 0},ae=function(){try{var e=oe(Object,"defineProperty");return e({},"",{}),e}catch(e){}}();var le=function(e,t,n){"__proto__"==t&&ae?ae(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n};var se=function(e,t){return e===t||e!=e&&t!=t},ue=Object.prototype.hasOwnProperty;var ce=function(e,t,n){var r=e[t];ue.call(e,t)&&se(r,n)&&(void 0!==n||t in e)||le(e,t,n)},de=Array.isArray;var fe=function(e){return null!=e&&"object"==typeof e},he="[object Symbol]";var pe=function(e){return"symbol"==typeof e||fe(e)&&L(e)==he},me=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ve=/^\w*$/;var ge=function(e,t){if(de(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!pe(e))||(ve.test(e)||!me.test(e)||null!=t&&e in Object(t))},be=oe(Object,"create");var ye=function(){this.__data__=be?be(null):{},this.size=0};var Ee=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},_e="__lodash_hash_undefined__",we=Object.prototype.hasOwnProperty;var Oe=function(e){var t=this.__data__;if(be){var n=t[e];return n===_e?void 0:n}return we.call(t,e)?t[e]:void 0},Ce=Object.prototype.hasOwnProperty;var Ae=function(e){var t=this.__data__;return be?void 0!==t[e]:Ce.call(t,e)},Se="__lodash_hash_undefined__";var xe=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=be&&void 0===t?Se:t,this};function Ie(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}Ie.prototype.clear=ye,Ie.prototype.delete=Ee,Ie.prototype.get=Oe,Ie.prototype.has=Ae,Ie.prototype.set=xe;var Te=Ie;var Fe=function(){this.__data__=[],this.size=0};var Me=function(e,t){for(var n=e.length;n--;)if(se(e[n][0],t))return n;return-1},Ne=Array.prototype.splice;var De=function(e){var t=this.__data__,n=Me(t,e);return!(n<0)&&(n==t.length-1?t.pop():Ne.call(t,n,1),--this.size,!0)};var je=function(e){var t=this.__data__,n=Me(t,e);return n<0?void 0:t[n][1]};var Pe=function(e){return Me(this.__data__,e)>-1};var ke=function(e,t){var n=this.__data__,r=Me(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this};function Re(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}Re.prototype.clear=Fe,Re.prototype.delete=De,Re.prototype.get=je,Re.prototype.has=Pe,Re.prototype.set=ke;var Le=Re,Be=oe(S,"Map");var Ve=function(){this.size=0,this.__data__={hash:new Te,map:new(Be||Le),string:new Te}};var qe=function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e};var Ge=function(e,t){var n=e.__data__;return qe(t)?n["string"==typeof t?"string":"hash"]:n.map};var We=function(e){var t=Ge(this,e).delete(e);return this.size-=t?1:0,t};var $e=function(e){return Ge(this,e).get(e)};var He=function(e){return Ge(this,e).has(e)};var Ue=function(e,t){var n=Ge(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this};function Ye(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}Ye.prototype.clear=Ve,Ye.prototype.delete=We,Ye.prototype.get=$e,Ye.prototype.has=He,Ye.prototype.set=Ue;var Qe=Ye,Xe="Expected a function";function ze(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new TypeError(Xe);var n=function(){var r=arguments,i=t?t.apply(this,r):r[0],o=n.cache;if(o.has(i))return o.get(i);var a=e.apply(this,r);return n.cache=o.set(i,a)||o,a};return n.cache=new(ze.Cache||Qe),n}ze.Cache=Qe;var Ke=ze,Je=500;var Ze=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,et=/\\(\\)?/g,tt=function(e){var t=Ke(e,(function(e){return n.size===Je&&n.clear(),e})),n=t.cache;return t}((function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(Ze,(function(e,n,r,i){t.push(r?i.replace(et,"$1"):n||e)})),t}));var nt=function(e,t){for(var n=-1,r=null==e?0:e.length,i=Array(r);++n<r;)i[n]=t(e[n],n,e);return i},rt=1/0,it=x?x.prototype:void 0,ot=it?it.toString:void 0;var at=function e(t){if("string"==typeof t)return t;if(de(t))return nt(t,e)+"";if(pe(t))return ot?ot.call(t):"";var n=t+"";return"0"==n&&1/t==-rt?"-0":n};var lt=function(e){return null==e?"":at(e)};var st=function(e,t){return de(e)?e:ge(e,t)?[e]:tt(lt(e))},ut=9007199254740991,ct=/^(?:0|[1-9]\d*)$/;var dt=function(e,t){var n=typeof e;return!!(t=null==t?ut:t)&&("number"==n||"symbol"!=n&&ct.test(e))&&e>-1&&e%1==0&&e<t},ft=1/0;var ht=function(e){if("string"==typeof e||pe(e))return e;var t=e+"";return"0"==t&&1/e==-ft?"-0":t};var pt=function(e,t,n,r){if(!B(e))return e;for(var i=-1,o=(t=st(t,e)).length,a=o-1,l=e;null!=l&&++i<o;){var s=ht(t[i]),u=n;if(i!=a){var c=l[s];void 0===(u=r?r(c,s,l):void 0)&&(u=B(c)?c:dt(t[i+1])?[]:{})}ce(l,s,u),l=l[s]}return e};var mt=function(e,t,n,r){return r="function"==typeof r?r:void 0,null==e?e:pt(e,t,n,r)};var vt=function(e){var t=null==e?0:e.length;return t?e[t-1]:void 0};var gt=function(e,t){for(var n=0,r=(t=st(t,e)).length;null!=e&&n<r;)e=e[ht(t[n++])];return n&&n==r?e:void 0};var bt=function(e,t,n){var r=-1,i=e.length;t<0&&(t=-t>i?0:i+t),(n=n>i?i:n)<0&&(n+=i),i=t>n?0:n-t>>>0,t>>>=0;for(var o=Array(i);++r<i;)o[r]=e[r+t];return o};var yt=function(e,t){return t.length<2?e:gt(e,bt(t,0,-1))};var Et=function(e,t){return t=st(t,e),null==(e=yt(e,t))||delete e[ht(vt(t))]};var _t=function(e,t){return null==e||Et(e,t)};var wt=function(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t};var Ot=function(e){return de(e)?nt(e,ht):pe(e)?[e]:wt(tt(lt(e)))};var Ct=function(e,t,n){var r=null==e?void 0:gt(e,t);return void 0===r?n:r},At=Object.prototype.hasOwnProperty;var St=function(e,t){return null!=e&&At.call(e,t)},xt="[object Arguments]";var It=function(e){return fe(e)&&L(e)==xt},Tt=Object.prototype,Ft=Tt.hasOwnProperty,Mt=Tt.propertyIsEnumerable,Nt=It(function(){return arguments}())?It:function(e){return fe(e)&&Ft.call(e,"callee")&&!Mt.call(e,"callee")},Dt=9007199254740991;var jt=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=Dt};var Pt=function(e,t,n){for(var r=-1,i=(t=st(t,e)).length,o=!1;++r<i;){var a=ht(t[r]);if(!(o=null!=e&&n(e,a)))break;e=e[a]}return o||++r!=i?o:!!(i=null==e?0:e.length)&&jt(i)&&dt(a,i)&&(de(e)||Nt(e))};var kt=function(e,t){return null!=e&&Pt(e,t,St)};var Rt=function(e,t){return nt(t,(function(t){return e[t]}))};var Lt=function(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r};var Bt=function(){return!1},Vt=w((function(e,t){var n=t&&!t.nodeType&&t,r=n&&e&&!e.nodeType&&e,i=r&&r.exports===n?S.Buffer:void 0,o=(i?i.isBuffer:void 0)||Bt;e.exports=o})),qt={};qt["[object Float32Array]"]=qt["[object Float64Array]"]=qt["[object Int8Array]"]=qt["[object Int16Array]"]=qt["[object Int32Array]"]=qt["[object Uint8Array]"]=qt["[object Uint8ClampedArray]"]=qt["[object Uint16Array]"]=qt["[object Uint32Array]"]=!0,qt["[object Arguments]"]=qt["[object Array]"]=qt["[object ArrayBuffer]"]=qt["[object Boolean]"]=qt["[object DataView]"]=qt["[object Date]"]=qt["[object Error]"]=qt["[object Function]"]=qt["[object Map]"]=qt["[object Number]"]=qt["[object Object]"]=qt["[object RegExp]"]=qt["[object Set]"]=qt["[object String]"]=qt["[object WeakMap]"]=!1;var Gt=function(e){return fe(e)&&jt(e.length)&&!!qt[L(e)]};var Wt=function(e){return function(t){return e(t)}},$t=w((function(e,t){var n=t&&!t.nodeType&&t,r=n&&e&&!e.nodeType&&e,i=r&&r.exports===n&&C.process,o=function(){try{var e=r&&r.require&&r.require("util").types;return e||i&&i.binding&&i.binding("util")}catch(e){}}();e.exports=o})),Ht=$t&&$t.isTypedArray,Ut=Ht?Wt(Ht):Gt,Yt=Object.prototype.hasOwnProperty;var Qt=function(e,t){var n=de(e),r=!n&&Nt(e),i=!n&&!r&&Vt(e),o=!n&&!r&&!i&&Ut(e),a=n||r||i||o,l=a?Lt(e.length,String):[],s=l.length;for(var u in e)!t&&!Yt.call(e,u)||a&&("length"==u||i&&("offset"==u||"parent"==u)||o&&("buffer"==u||"byteLength"==u||"byteOffset"==u)||dt(u,s))||l.push(u);return l},Xt=Object.prototype;var zt=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Xt)};var Kt=function(e,t){return function(n){return e(t(n))}}(Object.keys,Object),Jt=Object.prototype.hasOwnProperty;var Zt=function(e){if(!zt(e))return Kt(e);var t=[];for(var n in Object(e))Jt.call(e,n)&&"constructor"!=n&&t.push(n);return t};var en=function(e){return null!=e&&jt(e.length)&&!H(e)};var tn=function(e){return en(e)?Qt(e):Zt(e)};var nn=function(e){return null==e?[]:Rt(e,tn(e))};var rn=function(e,t){for(var n=-1,r=t.length,i=Array(r),o=null==e;++n<r;)i[n]=o?void 0:Ct(e,t[n]);return i},on=Array.prototype.splice;var an=function(e,t){for(var n=e?t.length:0,r=n-1;n--;){var i=t[n];if(n==r||i!==o){var o=i;dt(i)?on.call(e,i,1):Et(e,i)}}return e};var ln=function(e,t){if(e!==t){var n=void 0!==e,r=null===e,i=e==e,o=pe(e),a=void 0!==t,l=null===t,s=t==t,u=pe(t);if(!l&&!u&&!o&&e>t||o&&a&&s&&!l&&!u||r&&a&&s||!n&&s||!i)return 1;if(!r&&!o&&!u&&e<t||u&&n&&i&&!r&&!o||l&&n&&i||!a&&i||!s)return-1}return 0};var sn=function(e,t){for(var n=-1,r=t.length,i=e.length;++n<r;)e[i+n]=t[n];return e},un=x?x.isConcatSpreadable:void 0;var cn=function(e){return de(e)||Nt(e)||!!(un&&e&&e[un])};var dn=function e(t,n,r,i,o){var a=-1,l=t.length;for(r||(r=cn),o||(o=[]);++a<l;){var s=t[a];n>0&&r(s)?n>1?e(s,n-1,r,i,o):sn(o,s):i||(o[o.length]=s)}return o};var fn=function(e){return(null==e?0:e.length)?dn(e,1):[]};var hn=function(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)},pn=Math.max;var mn=function(e,t,n){return t=pn(void 0===t?e.length-1:t,0),function(){for(var r=arguments,i=-1,o=pn(r.length-t,0),a=Array(o);++i<o;)a[i]=r[t+i];i=-1;for(var l=Array(t+1);++i<t;)l[i]=r[i];return l[t]=n(a),hn(e,this,l)}};var vn=function(e){return function(){return e}};var gn=function(e){return e},bn=ae?function(e,t){return ae(e,"toString",{configurable:!0,enumerable:!1,value:vn(t),writable:!0})}:gn,yn=800,En=16,_n=Date.now;var wn=function(e){var t=0,n=0;return function(){var r=_n(),i=En-(r-n);if(n=r,i>0){if(++t>=yn)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}(bn);On=function(e,t){var n=null==e?0:e.length,r=rn(e,t);return an(e,nt(t,(function(e){return dt(e,n)?+e:e})).sort(ln)),r},wn(mn(On,void 0,fn),On+"");var On;var Cn=function(e,t){return wn(mn(e,t,gn),e+"")};var An=function(e,t,n,r){for(var i=e.length,o=n+(r?1:-1);r?o--:++o<i;)if(t(e[o],o,e))return o;return-1};var Sn=function(e){return e!=e};var xn=function(e,t,n){for(var r=n-1,i=e.length;++r<i;)if(e[r]===t)return r;return-1};var In=function(e,t,n){return t==t?xn(e,t,n):An(e,Sn,n)};var Tn=function(e,t,n,r){for(var i=n-1,o=e.length;++i<o;)if(r(e[i],t))return i;return-1},Fn=Array.prototype.splice;var Mn=function(e,t,n,r){var i=r?Tn:In,o=-1,a=t.length,l=e;for(e===t&&(t=wt(t)),n&&(l=nt(e,Wt(n)));++o<a;)for(var s=0,u=t[o],c=n?n(u):u;(s=i(l,c,s,r))>-1;)l!==e&&Fn.call(l,s,1),Fn.call(e,s,1);return e};var Nn=Cn((function(e,t){return e&&e.length&&t&&t.length?Mn(e,t):e})),Dn=O("informed:ObjMap\t"),jn=function(e){var t=Ot(e);return Number.isInteger(+t[t.length-1])},Pn=function(){function e(){l(this,e)}return u(e,null,[{key:"empty",value:function(e){return 0===nn(e).length}},{key:"get",value:function(e,t){var n=Ct(e,t);return Dn("GOT",t,n),n}},{key:"has",value:function(e,t){return kt(e,t)}},{key:"set",value:function(t,n,r){if(void 0!==r)Dn("SETTING",n,r),mt(t,n,r);else if(jn(n)&&void 0!==e.get(t,n)){Dn("Special case SETTING",n,"to undefined"),mt(t,n,void 0);var i=Ot(n);kn(t,i=i.slice(0,i.length-1),!1)}else jn(n)||void 0===e.get(t,n)||(Dn("Special case REMOVING",n,"from object completley"),e.delete(t,n))}},{key:"delete",value:function(e,t){Dn("DELETE",t),_t(e,t);var n=Ot(t);kn(e,n=n.slice(0,n.length-1))}}]),e}();function kn(e,t){var n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(0!==t.length){var r=Ct(e,t);Array.isArray(r)&&n&&Nn(r,void 0),(Array.isArray(r)?r.every((function(e){return null==e})):"{}"===JSON.stringify(r))&&_t(e,t),kn(e,t.slice(0,t.length-1))}}var Rn=O("informed:Controller\t"),Ln=function(e){function t(){var e,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return l(this,t),(e=b(this,p(t).call(this))).options=n,e.fields=new Map,e.registered={},e.expectedRemovals={},e.state={values:{},touched:{},errors:{},pristine:!0,dirty:!1,invalid:!1,submits:0},e.deregister=e.deregister.bind(g(e)),e.register=e.register.bind(g(e)),e.setValue=e.setValue.bind(g(e)),e.setTouched=e.setTouched.bind(g(e)),e.setError=e.setError.bind(g(e)),e.setFormError=e.setFormError.bind(g(e)),e.submitForm=e.submitForm.bind(g(e)),e.reset=e.reset.bind(g(e)),e.update=e.update.bind(g(e)),e.validate=e.validate.bind(g(e)),e.keyDown=e.keyDown.bind(g(e)),e.getField=e.getField.bind(g(e)),e.expectRemoval=e.expectRemoval.bind(g(e)),e.updater={register:e.register,deregister:e.deregister,setValue:e.setValue,setTouched:e.setTouched,setError:e.setError,update:e.update,getField:e.getField,expectRemoval:e.expectRemoval},e}return h(t,e),u(t,[{key:"setOptions",value:function(e){this.options=e}},{key:"getFormState",value:function(){return f({},this.state,{pristine:this.pristine(),dirty:this.dirty(),invalid:this.invalid()})}},{key:"getFormApi",value:function(){var e=this;return{setValue:function(t,n,r){return e.fields.get(t).fieldApi.setValue(n,null,f({allowEmptyString:e.options.allowEmptyStrings},r))},setTouched:function(t,n){return e.fields.get(t).fieldApi.setTouched(n)},setError:function(t,n){return e.fields.get(t).fieldApi.setError(n)},setValues:function(t){return e.setValues(t)},setInitialValue:function(t,n){return e.setInitialValue(t,n)},getValue:function(t){return e.getValue(t)},getTouched:function(t){return e.getTouched(t)},getError:function(t){return e.getError(t)},reset:function(){return e.reset()},submitForm:function(t){return e.submitForm(t)},getState:function(){return e.getFormState()},getValues:function(){return e.getFormState().values},getFullField:function(t){return e.getFullField(t)},fieldExists:function(t){return null!=e.fields.get(t)},getInitialValue:function(t){return e.getInitialValue(t)},setFormError:function(t){return e.setFormError(t)},validate:function(){return e.validate()},validateField:function(t){return e.fields.get(t).fieldApi.validate()},resetField:function(t){return e.fields.get(t).fieldApi.reset()},emitter:this,setFieldError:function(t,n){return e.setError(t,n)},getOptions:function(){return e.options}}}},{key:"setValue",value:function(e,t){var n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];Rn("Setting ".concat(e," to ").concat(t)),Pn.set(this.state.values,e,t),delete this.state.error,this.emit("change"),this.emit("value",e,t),n&&this.notify(e)}},{key:"setTouched",value:function(e,t){Pn.set(this.state.touched,e,t),this.emit("change")}},{key:"setError",value:function(e,t){if(Rn("Setting ".concat(e,"'s error to ").concat(t)),/\[[0-9]*\]$/.test(e)){var n=e.slice(0,e.lastIndexOf("[")),r=Pn.get(this.state.errors,n);if(Rn("Array field ".concat(n,"'s error is ").concat(r)),r&&!Array.isArray(r))return void Rn("Never set ".concat(e,"'s error to ").concat(t," becuase there is already array level validation with error ").concat(r))}Pn.set(this.state.errors,e,t),this.emit("change")}},{key:"setFormError",value:function(e){this.state.error=e,this.emit("change")}},{key:"setInitialValue",value:function(e,t){Pn.set(this.options.initialValues,e,t)}},{key:"notify",value:function(e){var t=this,n=this.fields.get(e);n.notify&&n.notify.forEach((function(e){var n=t.fields.get(e);if(n){Rn("Notifying",n.field);var r=t.getValue(n.field);n.fieldApi.validate(r)}}))}},{key:"getValue",value:function(e){return Rn("Getting value for",e,Pn.get(this.state.values,e)),Pn.get(this.state.values,e)}},{key:"getTouched",value:function(e){return Pn.get(this.state.touched,e)}},{key:"getError",value:function(e){return Pn.get(this.state.errors,e)}},{key:"getFullField",value:function(e){return e}},{key:"valid",value:function(){return!(!Pn.empty(this.state.errors)||this.state.error)}},{key:"invalid",value:function(){return!(Pn.empty(this.state.errors)&&!this.state.error)}},{key:"pristine",value:function(){return Pn.empty(this.state.touched)&&Pn.empty(this.state.values)}},{key:"dirty",value:function(){return!this.pristine()}},{key:"getInitialValue",value:function(e){return Pn.get(this.options.initialValues,e)}},{key:"reset",value:function(){var e=this;Rn("Resetting"),this.fields.forEach((function(t){t.fieldApi.reset();var n=Pn.get(e.options.initialValues,t.field);void 0!==n&&e.getFormApi().setValue(t.field,n,{initial:!0})})),this.emit("change")}},{key:"setValues",value:function(e){var t=this;Rn("Setting values"),this.fields.forEach((function(n){var r=Pn.get(e,n.field);void 0!==r&&t.getFormApi().setValue(n.field,r)})),this.emit("change")}},{key:"validate",value:function(){var e=this;if(Rn("Validating all fields"),this.fields.forEach((function(t,n){var r=e.getValue(n);t.fieldApi.validate(r),t.fieldApi.setTouched(!0)})),this.options.validate){var t=this.options.validate(this.state.values);this.setFormError(t)}if(this.options.validateFields){var n=this.options.validateFields(this.state.values);this.fields.forEach((function(t){if(Pn.has(n,t.field)){var r=Pn.get(n,t.field);e.getFormApi().setError(t.field,r)}}))}}},{key:"keyDown",value:function(e){if(13==e.keyCode&&this.options.preventEnter)return e.preventDefault(e),!1}},{key:"submitForm",value:function(e){this.state.submits=this.state.submits+1,!this.options.dontPreventDefault&&e&&e.preventDefault(e),this.validate(),this.emit("change"),this.valid()?(Rn("Submit",this.state),this.emit("submit")):(Rn("Submit",this.state),this.emit("failure"))}},{key:"register",value:function(e,t,n){Rn("Register",e,t);var r=this.registered[e];this.registered[e]=!0,this.fields.set(e,n);var i=e.slice(0,e.lastIndexOf("]")+1||e.length);if(delete this.expectedRemovals[i],!n.shadow){if(n.keepState){var o=Pn.get(this.state.values,e),a=Pn.get(this.options.initialValues,e);void 0!==o?this.getFormApi().setValue(e,o||t.value):void 0!==a?this.getFormApi().setValue(e,a):this.setValue(e,t.value,!1);var l=Pn.get(this.state.touched,e);this.getFormApi().setTouched(e,l)}else{var s=Pn.get(this.options.initialValues,e);void 0===s||r?this.setValue(e,t.value,!1):this.getFormApi().setValue(e,s,{initial:!0}),this.setTouched(e,t.touched)}this.setError(e,t.error)}}},{key:"deregister",value:function(e,t){Rn("Deregister",e);var n=this.fields.get(e),r=e.slice(0,e.lastIndexOf("]")+1||e.length);n.keepState&&!this.expectedRemovals[r]||(Pn.delete(this.state.values,e),Pn.delete(this.state.touched,e),Pn.delete(this.state.errors,e)),this.fields.delete(e),this.emit("change"),this.emit("value",e)}},{key:"expectRemoval",value:function(e){Rn("Expecting removal of",e),this.expectedRemovals[e]=!0}},{key:"update",value:function(e,t){Rn("Update",e),this.fields.set(e,t)}},{key:"getField",value:function(e){return Rn("Getting Field",e),this.fields.get(e)}}]),t}(a.EventEmitter),Bn=o.a.createContext({register:function(){},deregister:function(){},setValue:function(){},setTouched:function(){},setError:function(){},update:function(){},getField:function(){},expectRemoval:function(){}}),Vn=o.a.createContext({}),qn=o.a.createContext({getFullField:function(){},getValues:function(){},getOptions:function(){return{}},setInitialValue:function(){},getInitialValue:function(){}}),Gn=o.a.createContext(),Wn=(o.a.createContext(),O("informed:FormProvider\t\t")),$n=function(e){var t=e.children,n=e.formApi,r=e.formController,i=e.formState,a=v(e,["children","formApi","formController","formState"]);if(Wn("Render FormProvider"),n)return Wn("Render FormProvider with given values"),o.a.createElement(Bn.Provider,{value:r.updater},o.a.createElement(qn.Provider,{value:n},o.a.createElement(Vn.Provider,{value:i},t)));Wn("Render FormProvider with generated values");var l=Yn(a);return o.a.createElement(Bn.Provider,{value:l.formController.updater},o.a.createElement(qn.Provider,{value:l.formApi},o.a.createElement(Vn.Provider,{value:l.formState},t)))},Hn="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement?i.useLayoutEffect:i.useEffect,Un=O("informed:useForm\t\t"),Yn=function(e){var t=e.dontPreventDefault,n=e.initialValues,r=e.validate,a=e.validateFields,l=e.allowEmptyStrings,s=e.preventEnter,u=e.getApi,c=e.onChange,d=e.onSubmit,f=e.onValueChange,h=e.onSubmitFailure,p=v(e,["dontPreventDefault","initialValues","validate","validateFields","allowEmptyStrings","preventEnter","getApi","onChange","onSubmit","onValueChange","onSubmitFailure"]);Un("Render useForm");var m=Object(i.useMemo)((function(){return{dontPreventDefault:t,initialValues:n,validate:r,validateFields:a,allowEmptyStrings:l,preventEnter:s}}),[t,n,r,a,l,s]),g=y(Object(i.useState)((function(){return new Ln(m)})),1)[0];Object(i.useEffect)((function(){g.setOptions(m)}),[m]);var b=y(Object(i.useState)((function(){return g.getFormState()})),2),E=b[0],_=b[1];Hn((function(){var e=function(){return c&&c(g.getFormState())},t=function(){return d&&d(g.getFormState().values)},n=function(){return f&&f(g.getFormState().values)},r=function(){return h&&h(g.getFormState().errors)};return g.on("change",e),g.on("submit",t),g.on("value",n),g.on("failure",r),function(){g.removeListener("change",e),g.removeListener("submit",t),g.removeListener("value",n),g.removeListener("failure",r)}}),[c,d,f,h]),Object(i.useState)((function(){g.on("change",(function(){return _(g.getFormState())})),u&&u(g.getFormApi())}));var w=y(Object(i.useState)((function(){return g.getFormApi()})),1)[0];return{formApi:w,formState:E,formController:g,render:function(e){return o.a.createElement($n,{formApi:w,formState:E,formController:g},e)},userProps:p}},Qn=O("informed:Form\t\t"),Xn=function(e){var t=e.children,n=e.render,r=e.component,i=v(e,["children","render","component"]);Qn("Render FORM");var a,l=Yn(i),s=l.formApi,u=l.formController,c=l.formState,f=l.render,h=l.userProps;return f(o.a.createElement("form",d({},h,{onReset:u.reset,onSubmit:u.submitForm,onKeyDown:u.keyDown}),(a={formState:c,formApi:s},r?o.a.createElement(r,a,t):n?n(a):"function"==typeof t?t(a):t)))};function zn(){return Object(i.useContext)(qn)}function Kn(){return Object(i.useContext)(Vn)}var Jn=function(e){var t=e.scope,n=e.children,r=Object(i.useContext)(Bn),a=zn(),l=Kn(),s=Object(i.useMemo)((function(){return function(e,t){return f({},t,{getValue:function(n){return t.getValue("".concat(e,".").concat(n))},getTouched:function(n){return t.getTouched("".concat(e,".").concat(n))},getError:function(n){return t.getError("".concat(e,".").concat(n))},setValue:function(n,r){return t.setValue("".concat(e,".").concat(n),r)},setTouched:function(n,r){return t.setTouched("".concat(e,".").concat(n),r)},setError:function(n,r){return t.setError("".concat(e,".").concat(n),r)},getFullField:function(n){return"".concat(t.getFullField(e),".").concat(n)}})}(t,a)}),[t]),u=Object(i.useMemo)((function(){return function(e,t){var n=t.register,r=t.deregister,i=t.setValue,o=t.setTouched,a=t.setError,l=t.update,s=t.getField,u=t.expectRemoval;return{register:function(t){for(var r=arguments.length,i=new Array(r>1?r-1:0),o=1;o<r;o++)i[o-1]=arguments[o];return n.apply(void 0,["".concat(e,".").concat(t)].concat(i))},deregister:function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;o<n;o++)i[o-1]=arguments[o];return r.apply(void 0,["".concat(e,".").concat(t)].concat(i))},update:function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return l.apply(void 0,["".concat(e,".").concat(t)].concat(r))},setValue:function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return i.apply(void 0,["".concat(e,".").concat(t)].concat(r))},setTouched:function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return o.apply(void 0,["".concat(e,".").concat(t)].concat(r))},setError:function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return a.apply(void 0,["".concat(e,".").concat(t)].concat(r))},getField:function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return s.apply(void 0,["".concat(e,".").concat(t)].concat(r))},expectRemoval:function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return u.apply(void 0,["".concat(e,".").concat(t)].concat(r))}}}(t,r)}),[t]);return o.a.createElement(Bn.Provider,{value:u},o.a.createElement(qn.Provider,{value:s},o.a.createElement(Vn.Provider,{value:l},n)))};function Zn(e){var t=Object(i.useRef)(),n=y(Object(i.useState)(e),2),r=n[0],o=n[1];t.current=r;return[r,function(e){t.current=e,o(e)},function(){return t.current}]}var er=O("informed:useField\t"),tr=function(e,t){if(null!=e)return t?t(e):e},nr=function(e,t,n){return t&&n?t(e):e};function rr(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0,n=e.field,r=e.validate,a=e.mask,l=e.maskWithCursorOffset,s=e.format,u=e.parse,c=e.initialValue,d=e.validateOnChange,f=e.validateOnBlur,h=e.validateOnMount,p=e.maskOnBlur,m=e.allowEmptyString,g=e.onValueChange,b=e.notify,_=e.keepState,w=e.maintainCursor,O=e.debug,C=e.shadow,A=v(e,["field","validate","mask","maskWithCursorOffset","format","parse","initialValue","validateOnChange","validateOnBlur","validateOnMount","maskOnBlur","allowEmptyString","onValueChange","notify","keepState","maintainCursor","debug","shadow"]),S=Object(i.useContext)(Bn),x=zn(),I=y(Zn(tr(c,a)),3),T=I[0],F=I[1],M=I[2],N=y(Zn(h?r(T):void 0),3),D=N[0],j=N[1],P=N[2],k=y(Zn(),3),R=k[0],L=k[1],B=k[2],V=y(Zn(0),3),q=(V[0],V[1]),G=V[2],W=y(Zn(0),3),$=(W[0],W[1]),H=W[2],U=y(Object(i.useState)(nr(T,s,u)),2),Y=U[0],Q=U[1],X=Object(i.useRef)(c);X.current=c;var z=function(e){er("Setting ".concat(n,"'s error to ").concat(e)),j(e),S.setError(n,e)},K=function(t,i){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},c=x.getOptions();er("Setting ".concat(n," to ").concat(t));var f=t;if(""!==t||m||o.allowEmptyString||c.allowEmptyStrings||(t=void 0),"number"===e.type&&void 0!==t&&(t=+t),a&&!p&&(f=a(t),t=a(t)),l&&!p){var h=l(t);f=h.value,t=h.value,$(h.offset)}s&&u&&(t=u(t),f=s(t)),r&&d&&!o.initial&&(er("Validating after change ".concat(n," ").concat(t)),z(r(t,x.getValues()))),i&&i.target&&i.target.selectionStart&&q(i.target.selectionStart),F(t),Q(f),g&&g(t),S.setValue(n,t)},J=function(e,t){if(r&&f&&!t&&e&&(er("Validating after blur ".concat(n," ").concat(M())),z(r(M(),x.getValues()))),a&&p){var i=a(M());F(i),Q(i),g&&g(i),S.setValue(n,i)}if(l&&p){var o=l(M());$(o.offset),F(o.value),Q(o.value),g&&g(o.value),S.setValue(n,o.value)}L(e),S.setTouched(n,e)},Z={setValue:K,setTouched:J,setError:z,reset:function(){var e=tr(X.current,a);K(X.current),z(h?r(e):void 0),J(void 0,!0)},validate:function(e){r&&(er("Field validating ".concat(n," ").concat(M()||e)),z(r(M()||e,x.getValues())))},getValue:M,getTouched:B,getError:P},ee={value:T,error:D,touched:R,maskedValue:Y};C&&(ee={error:D,touched:R}),Object(i.useState)((function(){var e=x.getFullField(n);er("Initial Register",e),S.register(n,ee,{field:e,fieldApi:Z,fieldState:ee,notify:b,keepState:_,shadow:C})})),er("Render",x.getFullField(n),ee);var te=Object(i.useRef)(null),ne=o.a.useMemo((function(){return t||te}),[]);Object(i.useEffect)((function(){var e=x.getFullField(n);return er("Register",e),S.register(n,ee,{field:e,fieldApi:Z,fieldState:ee,notify:b,keepState:_,shadow:C}),function(){er("Deregister",e),S.deregister(n)}}),[n]),Object(i.useEffect)((function(){var e=x.getFullField(n);er("Update",n),S.update(n,{field:e,fieldApi:Z,fieldState:ee,notify:b,keepState:_,shadow:C})}),[r,d,f,g]),Hn((function(){w&&null!=ne.current&&G()&&(ne.current.selectionEnd=G()+H())}),[T]),Hn((function(){O&&ne&&(ne.current.style.border="5px solid orange",setTimeout((function(){ne.current.style.borderWidth="2px",ne.current.style.borderStyle="inset",ne.current.style.borderColor="initial",ne.current.style.borderImage="initial"}),500))}));var re=[].concat(E(Object.values(ee)),E(Object.values(e)),E(Object.values(A)));return{fieldState:ee,fieldApi:Z,render:function(e){return Object(i.useMemo)((function(){return e}),E(re))},ref:ne,userProps:A}}var ir=O("informed:useArrayField\t"),or=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},ar=function(e){var t=e.field,n=e.initialValue,r=e.validate,o=v(e,["field","initialValue","validate"]),a=zn(),l=Object(i.useContext)(Bn),s=a.getFullField(t),u=a.getInitialValue(s)||n||[],c=a.getValue(s),d=y(Object(i.useState)(c||u),2),h=d[0],p=d[1],m=y(Zn(h?h.map((function(){return or()})):[]),3),g=m[0],b=m[1],_=m[2],w=Object(i.useMemo)((function(){return function(e,t){var n=null==_()?0:_().length;return r?r(e,n,t):void 0}})),O=rr(f({field:t,validate:w,shadow:!0},o)).fieldApi;Hn((function(){var e=function(e){if(e!==s&&(ir("".concat(s," changed")),RegExp("".concat(s,"\\[[0-9]+\\]")).test(e))){var n=a.getValue(t);ir("setting array field ".concat(s," to ").concat(n)),O.setValue(n)}};return a.emitter.on("value",e),function(){a.emitter.removeListener("value",e)}}),[t]);return{fields:g.map((function(e,n){return{key:e,field:"".concat(t,"[").concat(n,"]"),remove:function(){return function(e){l.expectRemoval("".concat(t,"[").concat(e,"]"));var n=g.slice(0,e).concat(g.slice(e+1,g.length));b(n);var r=h.slice(0,e).concat(h.slice(e+1,h.length));p(r),a.setInitialValue(t,r)}(n)},initialValue:h&&h[n]}})),add:function(){g.push(or()),b(E(g))},addWithInitialValue:function(e){g.push(or()),b(E(g));var t=E(h);t[g.length-1]=e,p(t)}}},lr=function(e){var t=e.children,n=v(e,["children"]);return t(ar(n))},sr=function(e){return o.a.forwardRef((function(t,n){return o.a.createElement(qn.Consumer,null,(function(r){return o.a.createElement(e,d({formApi:r,ref:n},t))}))}))},ur=function(e){return o.a.forwardRef((function(t,n){return o.a.createElement(Vn.Consumer,null,(function(r){return o.a.createElement(e,d({formState:r,ref:n},t))}))}))},cr=function(e,t){return{getValue:function(){return e.getValue(t)},setValue:function(n){return e.setValue(t,n)},getTouched:function(){return e.getTouched(t)},setTouched:function(n){return e.setTouched(t,n)},getError:function(){return e.getError(t)},setError:function(n){return e.setError(t,n)},reset:function(){return e.resetField(t)},validate:function(){return e.validateField(t)},exists:function(){return e.fieldExists(t)}}};function dr(e){var t=zn();return Object(i.useMemo)((function(){return cr(t,e)}),[e])}var fr=function(e){return{value:e.getValue(),touched:e.getTouched(),error:e.getError()}};function hr(e){var t=dr(e);Kn();return fr(t)}var pr=function(e){return function(t){return function(n){var r=hr(e);return o.a.createElement(t,d({fieldState:r},n))}}},mr=function(e){return function(t){return function(n){var r=dr(e);return o.a.createElement(t,d({fieldApi:r},n))}}},vr=function(e){return o.a.forwardRef((function(t,n){return o.a.createElement(Gn.Consumer,null,(function(r){var i=r.radioGroupApi,a=r.radioGroupState;return o.a.createElement(e,d({radioGroupApi:i,radioGroupState:a,ref:n},t))}))}))},gr=function(e){var t,n=o.a.forwardRef((function(t,n){var r=rr(t,n),i=r.fieldState,a=r.fieldApi,l=r.render,s=r.ref,u=r.userProps;return l(o.a.createElement(e,d({fieldApi:a,fieldState:i,field:t.field,forwardedRef:s,debug:t.debug,type:t.type},u)))}));return n.displayName="asField(".concat((t=e).type&&t.type.name?t.type.name:t.displayName||t.name||"Component",")"),n},br=O("informed:Text\t"),yr=function(e){var t=e.fieldApi,n=e.fieldState,r=v(e,["fieldApi","fieldState"]),i=n.maskedValue,a=t.setValue,l=t.setTouched,s=r.onChange,u=r.onBlur,c=r.field,f=(r.initialValue,r.forwardedRef),h=r.debug,p=v(r,["onChange","onBlur","field","initialValue","forwardedRef","debug"]);return br("Render",c),Hn((function(){h&&f&&(f.current.style.background="red",setTimeout((function(){f.current.style.background="white"}),500))})),o.a.createElement("input",d({},p,{name:c,ref:f,value:i||0===i?i:"",onChange:function(e){a(e.target.value,e),s&&s(e)},onBlur:function(e){l(!0),u&&u(e)}}))},Er=gr(yr),_r=function(e){var t=e.radioGroupApi,n=e.radioGroupState,r=v(e,["radioGroupApi","radioGroupState"]),i=n.value,a=t.setValue,l=t.setTouched,s=t.onChange,u=t.onBlur,c=r.value,f=r.onChange,h=r.onBlur,p=r.field,m=(r.initialValue,r.forwardedRef),g=v(r,["value","onChange","onBlur","field","initialValue","forwardedRef"]);return o.a.createElement("input",d({},g,{name:p,ref:m,value:c,checked:i===c,onChange:function(e){e.target.checked&&(a(c),f&&f(e),s&&s(e))},onBlur:function(e){l(!0),h&&h(e),u&&u(e)},type:"radio"}))},wr=vr(_r),Or=function(e){var t=e.fieldApi,n=e.fieldState,r=v(e,["fieldApi","fieldState"]),i=n.maskedValue,a=t.setValue,l=t.setTouched,s=r.onChange,u=r.onBlur,c=r.field,f=(r.initialValue,r.forwardedRef),h=r.debug,p=v(r,["onChange","onBlur","field","initialValue","forwardedRef","debug"]);return Hn((function(){h&&f&&(f.current.style.background="red",setTimeout((function(){f.current.style.background="white"}),500))})),o.a.createElement("textarea",d({},p,{name:c,ref:f,value:i||"",onChange:function(e){a(e.target.value,e),s&&s(e)},onBlur:function(e){l(!0),u&&u(e)}}))},Cr=gr(Or),Ar=O("informed:Select\t"),Sr=function(e){var t=e.fieldApi,n=e.fieldState,r=v(e,["fieldApi","fieldState"]),a=n.value,l=t.setTouched,s=r.onChange,u=r.onBlur,c=r.field,f=(r.initialValue,r.children),h=r.forwardedRef,p=r.debug,m=r.multiple,g=v(r,["onChange","onBlur","field","initialValue","children","forwardedRef","debug","multiple"]),b=Object(i.useRef)();return Hn((function(){p&&h&&(h.current.style.background="red",setTimeout((function(){h.current.style.background="white"}),500))})),Ar("Render",c,a),o.a.createElement("select",d({},g,{multiple:m,name:c,ref:h||b,value:a||(m?[]:""),onChange:function(e){var n=Array.from((h||b).current).filter((function(e){return e.selected})).map((function(e){return e.value}));t.setValue(m?n:n[0]||""),s&&e&&s(e)},onBlur:function(e){l(!0),u&&u(e)}}),f)},xr=gr(Sr),Ir=function(e){var t=e.value,n=e.forwardedRef,r=e.children,i=v(e,["value","forwardedRef","children"]);return o.a.createElement("option",d({ref:n,value:t,key:t},i),r)},Tr=function(e){var t=e.fieldApi,n=e.fieldState,r=v(e,["fieldApi","fieldState"]),i=n.value,a=t.setValue,l=t.setTouched,s=r.onChange,u=r.onBlur,c=r.field,f=(r.initialValue,r.debug,r.forwardedRef),h=v(r,["onChange","onBlur","field","initialValue","debug","forwardedRef"]);return o.a.createElement("input",d({},h,{name:c,ref:f,checked:!!i,onChange:function(e){a(e.target.checked),s&&s(e)},onBlur:function(e){l(!0),u&&u(e)},type:"checkbox"}))},Fr=gr(Tr),Mr=function(e){function t(){return l(this,t),b(this,p(t).apply(this,arguments))}return h(t,e),u(t,[{key:"render",value:function(){return o.a.createElement(Gn.Provider,{value:this.groupContext},this.props.children)}},{key:"groupContext",get:function(){return{radioGroupApi:f({},this.props.fieldApi,{onChange:this.props.onChange,onBlur:this.props.onBlur}),radioGroupState:this.props.fieldState}}}]),t}(i.Component),Nr=gr(Mr)}.call(this,n(18),n(19))},function(e,t){e.exports=n},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});const i=r(n(0)),o=r(n(3));class a extends i.Component{constructor(){super(...arguments),this.initialAnswerFactory=new o.InitialAnswerFactory(this.props.item)}submitForm(){this.formApi&&this.formApi.submitForm()}getFormApi(e){this.formApi=e}handleSubmit(e){const{item:t}=this.props;t.setSingleInitialAnswer(this.initialAnswerFactory.createInitialAnswer({value:e.value}))}componentDidUpdate(){const{item:e}=this.props,t=e.initialAnswers[0]&&e.initialAnswers[0].value;this.formApi&&this.formApi.setValue("value",t)}}t.QuestionItem=a,t.default=a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.HumanReadableGuid=function(){let e;const t=()=>{let e=1;const t=new Map;return{getHumanReadableId:n=>(n=>(t.has(n)||t.set(n,e++),((e,t)=>{if(void 0===e)return;let n=""+e;for(;n.length<t;)n="0"+n;return n})(t.get(n),3)||""))(n),updateKey(e,n){((e,n)=>{if(!t.has(e))return;const r=t.get(e);t.set(n,r),t.delete(e)})(e,n)}}};return{getHumanReadableGuid:()=>(e||(e=t()),e)}}(),t.default=t.HumanReadableGuid},function(e,t,n){"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.rightPanel="RIGHT_PANEL",e.insideItem="INSIDE_ITEM"}(r=t.SETTINGS_DISPLAY_MODE||(t.SETTINGS_DISPLAY_MODE={})),t.default=r},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});const i=r(n(0)),o=r(n(3));class a extends i.Component{constructor(){super(...arguments),this.itemFactory=new o.ItemFactory(this.props.item)}addItem(){const{item:e,selectTargetItem:t}=this.props,n=this.itemFactory.createItem();e.addItem(n),t&&t(n)}addGroupItem(){const{item:e,selectTargetItem:t}=this.props,n=this.itemFactory.createGroupItem();e.addItem(n),t&&t(n)}addChoiceItem(){const{item:e,selectTargetItem:t}=this.props,n=this.itemFactory.createChoiceItem(),r=new o.AnswerOptionFactory(n);n.addAnswerOption(r.createAnswerOption({value:"Option 1"})),e.addItem(n),t&&t(n)}render(){return i.createElement("div",{className:"item-collection-menu btn-group"},i.createElement("button",{className:"btn btn-secondary",title:"Add text",onClick:this.addItem.bind(this)},i.createElement("i",{className:"fas fa-font"})),i.createElement("button",{className:"btn btn-secondary",title:"Add group",onClick:this.addGroupItem.bind(this)},i.createElement("i",{className:"fas fa-layer-group"})),i.createElement("button",{className:"btn btn-secondary",title:"Add question",onClick:this.addChoiceItem.bind(this)},i.createElement("i",{className:"fas fa-plus"})))}}t.ItemCollectionMenu=a,t.default=a},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=i(n(20)),l=i(n(10));class s extends o.Component{componentDidMount(){const{subscribe:e}=this.props;e&&e()}render(){const{itemList:e,className:t="",nestingLevel:n,subscribe:r,isItemActive:i}=this.props;return o.createElement("div",{className:`questionnaire-item-list ${t}`,"data-nesting-level":n},e.map((e,t)=>o.createElement(l.default.Consumer,{key:e.id},l=>o.createElement(a.default,Object.assign({item:e,nestingLevel:`${n}:${t}`,subscribe:r,isItemActive:i},l)))))}}t.QuestionnaireItemList=s,t.default=s},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});const i=r(n(0)),o=n(1);class a extends i.Component{constructor(){super(...arguments),this.RadioRef=i.createRef()}onBlur(e){const{option:t}=this.props;t.setValue(e.target.value)}remove(){const{option:e}=this.props;e.remove()}onChange(e){const{option:t}=this.props;e.target.checked?t.selectAsDefault():t.unselectAsDefault()}onClick(e){const{option:t}=this.props;e.target.checked&&t.selectAsDefault()}render(){const{option:e}=this.props;return i.createElement("div",{className:"form-group"},i.createElement("div",{className:"input-group"},i.createElement("div",{className:"input-group-prepend"},i.createElement("div",{className:"input-group-text"},i.createElement("label",{htmlFor:`${e.id}-initial`,className:"mr-1 mb-0"},"By default"),i.createElement("input",{checked:e.defaultSelected,id:`${e.id}-initial`,type:"radio",onChange:this.onChange.bind(this),onClick:this.onClick.bind(this)}))),i.createElement("input",{autoComplete:"off",id:`${e.id}-option`,className:"form-control",defaultValue:e.value,onBlur:this.onBlur.bind(this)}),i.createElement("div",{className:"input-group-append"},i.createElement("button",{className:"btn btn-outline-secondary",onClick:this.remove.bind(this)},i.createElement("i",{className:"fas fa-trash"})))))}}t.ChoiceOption=a,t.default=o.useObservableModel(a)},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=i(n(6));t.QuestionnaireContext=o.createContext({settingsDisplayMode:a.default.rightPanel}),t.default=t.QuestionnaireContext},function(e,t,n){"use strict";var r,i="object"==typeof Reflect?Reflect:null,o=i&&"function"==typeof i.apply?i.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};r=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var a=Number.isNaN||function(e){return e!=e};function l(){l.init.call(this)}e.exports=l,l.EventEmitter=l,l.prototype._events=void 0,l.prototype._eventsCount=0,l.prototype._maxListeners=void 0;var s=10;function u(e){return void 0===e._maxListeners?l.defaultMaxListeners:e._maxListeners}function c(e,t,n,r){var i,o,a,l;if("function"!=typeof n)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof n);if(void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),a=o[t]),void 0===a)a=o[t]=n,++e._eventsCount;else if("function"==typeof a?a=o[t]=r?[n,a]:[a,n]:r?a.unshift(n):a.push(n),(i=u(e))>0&&a.length>i&&!a.warned){a.warned=!0;var s=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");s.name="MaxListenersExceededWarning",s.emitter=e,s.type=t,s.count=a.length,l=s,console&&console.warn&&console.warn(l)}return e}function d(){for(var e=[],t=0;t<arguments.length;t++)e.push(arguments[t]);this.fired||(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,o(this.listener,this.target,e))}function f(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=d.bind(r);return i.listener=n,r.wrapFn=i,i}function h(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):m(i,i.length)}function p(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function m(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}Object.defineProperty(l,"defaultMaxListeners",{enumerable:!0,get:function(){return s},set:function(e){if("number"!=typeof e||e<0||a(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");s=e}}),l.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},l.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||a(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},l.prototype.getMaxListeners=function(){return u(this)},l.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,i=this._events;if(void 0!==i)r=r&&void 0===i.error;else if(!r)return!1;if(r){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var l=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw l.context=a,l}var s=i[e];if(void 0===s)return!1;if("function"==typeof s)o(s,this,t);else{var u=s.length,c=m(s,u);for(n=0;n<u;++n)o(c[n],this,t)}return!0},l.prototype.addListener=function(e,t){return c(this,e,t,!1)},l.prototype.on=l.prototype.addListener,l.prototype.prependListener=function(e,t){return c(this,e,t,!0)},l.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t);return this.on(e,f(this,e,t)),this},l.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t);return this.prependListener(e,f(this,e,t)),this},l.prototype.removeListener=function(e,t){var n,r,i,o,a;if("function"!=typeof t)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t);if(void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,i=o;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,a||t)}return this},l.prototype.off=l.prototype.removeListener,l.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,o=Object.keys(n);for(r=0;r<o.length;++r)"removeListener"!==(i=o[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},l.prototype.listeners=function(e){return h(this,e,!0)},l.prototype.rawListeners=function(e){return h(this,e,!1)},l.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},l.prototype.listenerCount=p,l.prototype.eventNames=function(){return this._eventsCount>0?r(this._events):[]}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){for(var n in e)t.hasOwnProperty(n)||(t[n]=e[n])}(n(13))},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=r(n(3));n(14);const l=n(2),s=n(1),u=i(n(7)),c=i(n(8)),d=i(n(48)),f=i(n(10)),h=n(6);class p extends o.Component{constructor(){super(...arguments),this.state={settingsDisplayModel:h.SETTINGS_DISPLAY_MODE.insideItem,targetItem:void 0,targetGroup:this.props.questionnaireModel},this.questionnaireItemListRef=o.createRef(),this.itemFactory=new a.ItemFactory(this.props.questionnaireModel),this.nestingLevel="0",this.itemListsMap=new Map,this.sortableOptions={group:"nested",animation:550,fallbackOnBody:!0,swapThreshold:.35,handle:".drag-handle",dragClass:"sortable-drag",onChoose:this.onDragChoose.bind(this),onUnchoose:this.onDragUnchoose.bind(this),onEnd:this.onDragEnd.bind(this),forceFallback:!0,filter:".no-drag",fallbackTolerance:1,emptyInsertThreshold:30},this.bodyListener=e=>{this.questionnaireItemListRef.current&&this.questionnaireItemListRef.current.contains(e.target)||this.clearTargetItem()}}handleSubmit(e){const{questionnaireModel:t}=this.props;t.updateQuestionnaire({...t,title:e.title,description:e.description})}submitForm(){this.formApi&&this.formApi.submitForm()}getFormApi(e){this.formApi=e}escListener(e){27===e.keyCode&&this.clearTargetItem()}componentDidMount(){this.makeItemsDraggable(),document.addEventListener("keydown",this.escListener.bind(this)),document.body.addEventListener("mousedown",this.bodyListener),this.clearTargetItem()}componentDidUpdate(){const{questionnaireModel:e}=this.props;this.formApi.setValues(e)}componentWillUnmount(){this.clearSortables(),document.removeEventListener("keydown",this.escListener.bind(this)),document.body.removeEventListener("mousedown",this.bodyListener)}clearSortables(){this.itemListsMap.forEach(e=>e.destroy())}makeItemsDraggable(){document.querySelectorAll("#drag-drop-nested .questionnaire-item-list").forEach(e=>{this.itemListsMap.has(e)||this.itemListsMap.set(e,new d.default(e,this.sortableOptions))})}onDragChoose(e){document.body.style.height=`${document.body.clientHeight}px`}fillQuestionList(e,t){t.items&&t.items.forEach(t=>{t.type===a.GROUP&&this.fillQuestionList(e,t),e.push(t)})}prepareQuestionList(){const{questionnaireModel:e}=this.props,t=[];return this.fillQuestionList(t,e),t}onDragUnchoose(e){document.body.style.height="";const t=this.prepareQuestionList().find(t=>t.id===e.item.dataset.id);this.selectTargetItem(t)}onDragEnd(e){const t=this.findNestedItemList(e.from.dataset.nestingLevel),n=this.findNestedItemList(e.to.dataset.nestingLevel);if(t===n&&e.oldIndex===e.newIndex||void 0===t||void 0===n)return;const r=t.items.find(t=>t.id===e.item.dataset.id);r&&(t!==n&&e.from.appendChild(e.item),r.remove(),n.addItem(r,e.newIndex))}findNestedItemList(e){if(void 0===e)return;const t=e.split(":");t.shift();const{questionnaireModel:n}=this.props;let r=n;return 0===e.length?r:(t.forEach(e=>{Array.isArray(r.items)&&(r=r.items[+e])}),r)}selectTargetItem(e){this.setState({targetItem:e,targetGroup:e.type===a.GROUP?e:e.parent})}clearTargetItem(){const{questionnaireModel:e}=this.props;this.setState({targetItem:void 0,targetGroup:e})}renderItemList(){const{questionnaireModel:e}=this.props,{targetItem:t,settingsDisplayModel:n,targetGroup:r}=this.state;return o.createElement("div",{id:"drag-drop-nested"},o.createElement(f.default.Provider,{value:{questionnaire:e,selectTargetItem:this.selectTargetItem.bind(this),targetItemId:t&&t.id,settingsDisplayMode:n,clearTargetItem:this.clearTargetItem.bind(this),targetGroupId:r&&r.id}},o.createElement(c.default,{itemList:e.items,nestingLevel:this.nestingLevel,subscribe:this.makeItemsDraggable.bind(this)})))}render(){const{questionnaireModel:e,className:t}=this.props;return o.createElement("div",{className:`questionnaire-designer media ${t}`},o.createElement("div",{className:"questionnaire-items media-body"},o.createElement("div",{className:"questionnaire card mb-3"},o.createElement("div",{className:"card-header d-flex justify-content-end"}),o.createElement("div",{className:"card-body"},o.createElement(l.Form,{getApi:this.getFormApi.bind(this),key:e.id,initialValues:e,onSubmit:this.handleSubmit.bind(this)},o.createElement("div",{className:"form-group"},o.createElement("label",{htmlFor:`${e.id}-title`},"Questionnaire Title"),o.createElement(l.Text,{autoComplete:"off",className:"form-control",id:`${e.id}-title`,field:"title",placeholder:"My Questionnaire",autoFocus:!0,onBlur:this.submitForm.bind(this)})),o.createElement("div",{className:"form-group"},o.createElement("label",{htmlFor:`${e.id}-description`},"Questionnaire Description"),o.createElement(l.TextArea,{autoComplete:"off",className:"form-control",id:`${e.id}-description`,field:"description",placeholder:"My description",onBlur:this.submitForm.bind(this)}))))),0===e.items.length&&o.createElement("div",{className:"w-100 d-flex justify-content-center align-items-center"},o.createElement(u.default,{item:e,selectTargetItem:this.selectTargetItem.bind(this)})),o.createElement("div",{ref:this.questionnaireItemListRef},this.renderItemList())))}}t.Questionnaire=p,p.defaultProps={className:""};const m=s.useObservableModel(p);t.QuestionnaireDesigner=m,t.default=m},function(e,t,n){var r=n(15);"string"==typeof r&&(r=[[e.i,r,""]]);var i={insert:"head",singleton:!1};n(17)(r,i);r.locals&&(e.exports=r.locals)},function(e,t,n){(e.exports=n(16)(!1)).push([e.i,".questionnaire-item {\n position: relative; }\n\n.bottom-line {\n display: flex;\n flex-wrap: wrap;\n position: absolute;\n right: -27px;\n width: calc(100% + 27px);\n height: 16px;\n bottom: -8px;\n padding-right: 1px; }\n .bottom-line button.toggle {\n padding: 2px !important;\n border: 0 !important;\n width: 32px !important;\n height: 32px !important;\n flex: 0 0 auto;\n z-index: 100; }\n .bottom-line hr {\n flex-basis: 0;\n flex-grow: 1;\n max-width: 100%; }\n .bottom-line .dropdown-menu {\n padding: 0;\n border: 0;\n min-width: 0; }\n .bottom-line .btn-group-vertical {\n position: absolute; }\n\n.bottom-line:not(:hover) hr {\n opacity: 0; }\n",""])},function(e,t,n){"use strict";e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var n=function(e,t){var n=e[1]||"",r=e[3];if(!r)return n;if(t&&"function"==typeof btoa){var i=(a=r,"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(a))))+" */"),o=r.sources.map((function(e){return"/*# sourceURL="+r.sourceRoot+e+" */"}));return[n].concat(o).concat([i]).join("\n")}var a;return[n].join("\n")}(t,e);return t[2]?"@media "+t[2]+"{"+n+"}":n})).join("")},t.i=function(e,n){"string"==typeof e&&(e=[[null,e,""]]);for(var r={},i=0;i<this.length;i++){var o=this[i][0];null!=o&&(r[o]=!0)}for(i=0;i<e.length;i++){var a=e[i];null!=a[0]&&r[a[0]]||(n&&!a[2]?a[2]=n:n&&(a[2]="("+a[2]+") and ("+n+")"),t.push(a))}},t}},function(e,t,n){"use strict";var r,i={},o=function(){return void 0===r&&(r=Boolean(window&&document&&document.all&&!window.atob)),r},a=function(){var e={};return function(t){if(void 0===e[t]){var n=document.querySelector(t);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(e){n=null}e[t]=n}return e[t]}}();function l(e,t){for(var n=[],r={},i=0;i<e.length;i++){var o=e[i],a=t.base?o[0]+t.base:o[0],l={css:o[1],media:o[2],sourceMap:o[3]};r[a]?r[a].parts.push(l):n.push(r[a]={id:a,parts:[l]})}return n}function s(e,t){for(var n=0;n<e.length;n++){var r=e[n],o=i[r.id],a=0;if(o){for(o.refs++;a<o.parts.length;a++)o.parts[a](r.parts[a]);for(;a<r.parts.length;a++)o.parts.push(v(r.parts[a],t))}else{for(var l=[];a<r.parts.length;a++)l.push(v(r.parts[a],t));i[r.id]={id:r.id,refs:1,parts:l}}}}function u(e){var t=document.createElement("style");if(void 0===e.attributes.nonce){var r=n.nc;r&&(e.attributes.nonce=r)}if(Object.keys(e.attributes).forEach((function(n){t.setAttribute(n,e.attributes[n])})),"function"==typeof e.insert)e.insert(t);else{var i=a(e.insert||"head");if(!i)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");i.appendChild(t)}return t}var c,d=(c=[],function(e,t){return c[e]=t,c.filter(Boolean).join("\n")});function f(e,t,n,r){var i=n?"":r.css;if(e.styleSheet)e.styleSheet.cssText=d(t,i);else{var o=document.createTextNode(i),a=e.childNodes;a[t]&&e.removeChild(a[t]),a.length?e.insertBefore(o,a[t]):e.appendChild(o)}}function h(e,t,n){var r=n.css,i=n.media,o=n.sourceMap;if(i&&e.setAttribute("media",i),o&&btoa&&(r+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),e.styleSheet)e.styleSheet.cssText=r;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(r))}}var p=null,m=0;function v(e,t){var n,r,i;if(t.singleton){var o=m++;n=p||(p=u(t)),r=f.bind(null,n,o,!1),i=f.bind(null,n,o,!0)}else n=u(t),r=h.bind(null,n,t),i=function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(n)};return r(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;r(e=t)}else i()}}e.exports=function(e,t){(t=t||{}).attributes="object"==typeof t.attributes?t.attributes:{},t.singleton||"boolean"==typeof t.singleton||(t.singleton=o());var n=l(e,t);return s(n,t),function(e){for(var r=[],o=0;o<n.length;o++){var a=n[o],u=i[a.id];u&&(u.refs--,r.push(u))}e&&s(l(e,t),t);for(var c=0;c<r.length;c++){var d=r[c];if(0===d.refs){for(var f=0;f<d.parts.length;f++)d.parts[f]();delete i[d.id]}}}}},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t){var n,r,i=e.exports={};function o(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function l(e){if(n===setTimeout)return setTimeout(e,0);if((n===o||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:o}catch(e){n=o}try{r="function"==typeof clearTimeout?clearTimeout:a}catch(e){r=a}}();var s,u=[],c=!1,d=-1;function f(){c&&s&&(c=!1,s.length?u=s.concat(u):d=-1,u.length&&h())}function h(){if(!c){var e=l(f);c=!0;for(var t=u.length;t;){for(s=u,u=[];++d<t;)s&&s[d].run();d=-1,t=u.length}s=null,c=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===a||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}(e)}}function p(e,t){this.fun=e,this.array=t}function m(){}i.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];u.push(new p(e,t)),1!==u.length||c||l(h)},p.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=m,i.addListener=m,i.once=m,i.off=m,i.removeListener=m,i.removeAllListeners=m,i.emit=m,i.prependListener=m,i.prependOnceListener=m,i.listeners=function(e){return[]},i.binding=function(e){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(e){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=r(n(3)),l=n(1),s=i(n(21)),u=n(2),c=i(n(36)),d=i(n(38)),f=i(n(5)),h=n(46),p=i(n(6)),m=i(n(47));class v extends o.PureComponent{constructor(){super(...arguments),this.state={bottomMenuShowed:!1},this.bottomLineRef=o.createRef(),this.inputRef=o.createRef(),this.itemRef=o.createRef(),this.humanReadableGuid=f.default.getHumanReadableGuid()}submitForm(){this.formApi&&this.formApi.submitForm()}submitForm_2(){this.formApi_2&&this.formApi_2.submitForm()}getFormApi(e){this.formApi=e}getFormApi_2(e){this.formApi_2=e}handleSubmit(e){const{item:t}=this.props;t.updateItem({...t,text:e.text})}handleSubmit_2(e){const{item:t}=this.props;t.updateItem({...t,...e})}componentDidUpdate(){const{item:e,targetItemId:t}=this.props;e.id===t&&(this.formApi&&this.formApi.setValues(e),this.formApi_2&&this.formApi_2.setValues(e))}componentWillUnmount(){this.clearTargetItem(),clearTimeout(this.closingBottomMenuTimeOutKey)}componentDidMount(){const e=this.inputRef.current;if(e){const t=window.pageXOffset,n=window.pageYOffset;e.focus(),window.scrollTo(t,n)}}toggleBottomMenu(){this.setState({bottomMenuShowed:!this.state.bottomMenuShowed})}closeBottomMenu(){this.state.bottomMenuShowed&&this.setState({bottomMenuShowed:!1})}prepareClosingBottomMenu(){this.closingBottomMenuTimeOutKey=setTimeout(()=>{this.closeBottomMenu()})}preventClosingBottomMenu(){clearTimeout(this.closingBottomMenuTimeOutKey)}clearTargetItem(){const{clearTargetItem:e}=this.props;e&&e()}makeItemTarget(){const{selectTargetItem:e,item:t}=this.props;e&&e(t)}toggleTargetItem(){const{item:e,targetItemId:t}=this.props;e.id===t?this.clearTargetItem():this.makeItemTarget()}selectTargetItem(e){const{item:t,targetItemId:n}=this.props,r=t.id===n;e.stopPropagation(),("click"!==e.type||!r||this.itemRef.current&&!this.itemRef.current.contains(e.target))&&(this.bottomLineRef.current&&this.bottomLineRef.current.contains(e.target)||this.makeItemTarget())}getHeadlineControl(){const{item:e}=this.props;return e.type===a.DISPLAY?o.createElement(u.TextArea,{forwardedRef:this.inputRef,autoComplete:"off",className:"form-control",id:`${e.id}-text`,field:"text",placeholder:"Static text",onBlur:this.submitForm.bind(this)}):o.createElement(u.Text,{forwardedRef:this.inputRef,autoComplete:"off",className:"form-control",id:`${e.id}-text`,field:"text",placeholder:e.type===a.GROUP?"Questions group":"Question text",onBlur:this.submitForm.bind(this)})}getHeadlineFromClassName(){const{item:e}=this.props;switch(e.type){case a.GROUP:return"questionnaire-group-item__headline form-group";case a.DISPLAY:return"questionnaire-display-item__headline";default:return"questionnaire-item__headline form-group"}}getHeadlineLogoText(){const{item:e}=this.props;switch(e.type){case a.GROUP:return"Group Title";case a.DISPLAY:return"Text";default:return"Question"}}getClassNameIdentifier(){const{item:e}=this.props;return e.type===a.GROUP?"questionnaire-item questionnaire-group-item":e.type===a.DISPLAY?"questionnaire-item questionnaire-display-item":"questionnaire-item questionnaire-question-item"}renderHeadlineLabelReplacerText(){const{item:e}=this.props;switch(e.type){case a.GROUP:return"Questions group";case a.DISPLAY:return"Text";default:return"Question"}}renderHeader(){const{item:e,targetItemId:t}=this.props,n=e.id===t;return o.createElement("div",{className:"row"},o.createElement("div",{className:"col-4 d-flex align-items-center"},o.createElement("button",{className:"btn btn-outline-secondary border-0 mr-2 no-drag",title:n?"collapse":"expand",onClick:this.toggleTargetItem.bind(this)},n?o.createElement("i",{className:"fas fa-angle-down"}):o.createElement("i",{className:"fas fa-angle-right"})),o.createElement("span",null,"#",this.humanReadableGuid.getHumanReadableId(e.id))),o.createElement("div",{className:"col-4 d-flex justify-content-center align-items-center"},o.createElement("i",{className:"fas fa-grip-horizontal text-muted"})),o.createElement("div",{className:"col-4 d-flex justify-content-end align-items-center"},o.createElement("div",{className:"btn-group no-drag"},t===e.id&&o.createElement("button",{className:"btn btn-outline-secondary border-0",onClick:e.remove.bind(e)},o.createElement("i",{className:"fas fa-trash"})))))}renderHeadline(){const{item:e,targetItemId:t,selectTargetItem:n}=this.props,r=e.id===t;return o.createElement("div",{className:`form-row ${this.getHeadlineFromClassName()}`},r?o.createElement("div",{className:"col"},o.createElement(u.Form,{getApi:this.getFormApi.bind(this),initialValues:e,onSubmit:this.handleSubmit.bind(this)},o.createElement("div",null,o.createElement("label",{htmlFor:`${e.id}-text`},this.getHeadlineLogoText()),this.getHeadlineControl()))):o.createElement("div",{className:"col"},o.createElement("label",{className:"labelReplacer"},e.text||this.renderHeadlineLabelReplacerText(),e.required&&o.createElement("span",{className:"text-danger"},"*"))),e.type!==a.DISPLAY&&e.type!==a.GROUP&&r&&o.createElement("div",{className:"col-md-4"},o.createElement(c.default,{selectTargetItem:n,title:"Question Type",item:e})))}renderFooter(){const{item:e,questionnaire:t}=this.props;return o.createElement("div",null,o.createElement("div",{className:"d-flex justify-content-start align-items-center"},o.createElement("div",null,e.type!==a.GROUP&&e.type!==a.DISPLAY&&o.createElement(u.Form,{className:"mr-3",getApi:this.getFormApi_2.bind(this),initialValues:e,onSubmit:this.handleSubmit_2.bind(this)},o.createElement("div",{className:"form-check"},o.createElement(u.Checkbox,{key:e.required+"",field:"required",type:"checkbox",className:"form-check-input",id:`${e.id}-required`,onChange:this.submitForm_2.bind(this)}),o.createElement("label",{className:"mb-0",htmlFor:`${e.id}-required`},"Required"))))),o.createElement("div",{className:"item-settings"},e.type!==a.GROUP&&e.type!==a.DISPLAY&&o.createElement("hr",null),t&&o.createElement(d.default,{questionnaire:t,item:e})))}render(){const{item:e,nestingLevel:t,className:n,subscribe:r,targetItemId:i,settingsDisplayMode:a,targetGroupId:l,selectTargetItem:u}=this.props,{bottomMenuShowed:c}=this.state,d=this.getClassNameIdentifier(),f=a===p.default.insideItem,v=i===e.id,g=v?h.activeItemClassName:"";return o.createElement("div",{className:`${d} card mb-3 ${g} ${n}`,"data-id":e.id,ref:this.itemRef,onFocus:this.selectTargetItem.bind(this),onClick:this.selectTargetItem.bind(this)},o.createElement("div",{className:"card-header drag-handle"},this.renderHeader()),o.createElement("div",{className:"card-body"},this.renderHeadline(),o.createElement("div",{className:"questionnaire-item__details"},o.createElement(s.default,{item:e,key:e.id,nestingLevel:t,subscribe:r,isItemActive:v}))),f&&v&&o.createElement("div",{className:"card-footer"},this.renderFooter()),e.parent&&e.parent.id===l&&o.createElement("div",{className:"bottom-line",onFocus:this.preventClosingBottomMenu.bind(this),onBlur:this.prepareClosingBottomMenu.bind(this),ref:this.bottomLineRef},o.createElement("hr",null),o.createElement("div",{className:"dropup d-flex"},o.createElement("button",{className:"toggle btn btn-outline-secondary",onClick:this.toggleBottomMenu.bind(this),title:"Add item"},o.createElement("i",{className:"fas fa-bars"})),c&&o.createElement(m.default,{close:this.closeBottomMenu.bind(this),selectTargetItem:u,item:e}))))}}t.ItemWrapper=v,v.defaultProps={className:""},t.default=l.useObservableModel(v)},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});const i=r(n(0)),o=r(n(3)),a=n(22),l=n(23),s=n(24),u=n(25),c=n(26),d=n(27),f=n(28),h=n(29),p=n(30),m=n(31),v=n(32),g=n(34);t.ItemProvider=e=>{const{item:t}=e;switch(t.type){case o.GROUP:return i.createElement(a.GroupItem,Object.assign({},e));case o.TEXT:return i.createElement(l.TextItem,Object.assign({},e));case o.STRING:return i.createElement(s.StringItem,Object.assign({},e));case o.DECIMAL:return i.createElement(u.DecimalItem,Object.assign({},e));case o.BOOLEAN:return i.createElement(c.BooleanItem,Object.assign({},e));case o.TIME:return i.createElement(d.TimeItem,Object.assign({},e));case o.DATE:return i.createElement(f.DateItem,Object.assign({},e));case o.DATE_TIME:return i.createElement(h.DateTimeItem,Object.assign({},e));case o.ATTACHMENT:return i.createElement(p.AttachmentItem,Object.assign({},e));case o.CHOICE:return i.createElement(m.ChoiceItem,Object.assign({},e));case o.OPEN_CHOICE:return i.createElement(v.OpenChoiceItem,Object.assign({},e));case o.MULTI_CHOICE:return i.createElement(g.MultiChoiceItem,Object.assign({},e));default:return null}},t.default=t.ItemProvider},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=n(1),l=i(n(8)),s=i(n(7));class u extends o.Component{render(){const{item:e,nestingLevel:t,subscribe:n,isItemActive:r}=this.props;return o.createElement("div",null,0===e.items.length&&r&&o.createElement("div",{className:"w-100 d-flex justify-content-center align-items-center"},o.createElement(s.default,{item:e})),o.createElement(l.default,{itemList:e.items,nestingLevel:t,subscribe:n,isItemActive:r}))}}t.GroupItem=u,t.default=a.useObservableModel(u)},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=n(2),l=n(1),s=i(n(4));class u extends s.default{render(){const{item:e}=this.props,t=e.initialAnswers[0]&&e.initialAnswers[0].value;return o.createElement(a.Form,{getApi:this.getFormApi.bind(this),key:e.id,onSubmit:this.handleSubmit.bind(this)},o.createElement("label",{htmlFor:`${e.id}-initial`,className:"question-item-label"},"Default answer"),o.createElement(a.TextArea,{autoComplete:"off",className:"form-control js-text-area",initialValue:t,field:"value",id:`${e.id}-initial`,placeholder:"Patient default answer",onBlur:this.submitForm.bind(this)}))}}t.TextItem=u,t.default=l.useObservableModel(u)},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=n(2),l=n(1),s=i(n(4));class u extends s.default{render(){const{item:e}=this.props,t=e.initialAnswers[0]&&e.initialAnswers[0].value;return o.createElement(a.Form,{getApi:this.getFormApi.bind(this),key:e.id,onSubmit:this.handleSubmit.bind(this)},o.createElement("label",{htmlFor:`${e.id}-initial`,className:"question-item-label"},"Default answer"),o.createElement(a.Text,{autoComplete:"off",className:"form-control",initialValue:t,field:"value",id:`${e.id}-initial`,placeholder:"Patient default answer",onBlur:this.submitForm.bind(this)}))}}t.StringItem=u,t.default=l.useObservableModel(u)},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=n(2),l=n(1),s=i(n(4));class u extends s.default{render(){const{item:e}=this.props,t=e.initialAnswers[0]&&e.initialAnswers[0].value;return o.createElement(a.Form,{getApi:this.getFormApi.bind(this),key:e.id,onSubmit:this.handleSubmit.bind(this)},o.createElement("label",{htmlFor:`${e.id}-initial`,className:"question-item-label"},"Default answer"),o.createElement(a.Text,{autoComplete:"off",className:"form-control",type:"number",initialValue:t,field:"value",id:`${e.id}-initial`,placeholder:"Patient default answer",onBlur:this.submitForm.bind(this)}))}}t.DecimalItem=u,t.default=l.useObservableModel(u)},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=n(2),l=n(1),s=i(n(4));class u extends s.default{reset(){const{item:e}=this.props;e.clearInitialAnswers()}render(){const{item:e}=this.props,t=e.initialAnswers[0]&&e.initialAnswers[0].value;return o.createElement(a.Form,{getApi:this.getFormApi.bind(this),key:e.id,onSubmit:this.handleSubmit.bind(this)},o.createElement("div",{className:"d-flex align-items-baseline"},o.createElement("label",{className:"question-item-label mr-3 mb-0"},"Default answer"),e.initialAnswers.length>0&&o.createElement("button",{type:"button",className:"btn btn-link text-secondary p-0",onClick:this.reset.bind(this)},"Remove default value")),o.createElement(a.RadioGroup,{initialValue:t,field:"value"},o.createElement("div",null,o.createElement("div",{className:"form-check"},o.createElement(a.Radio,{className:"form-check-input",id:`${e.id}-true`,value:!0,onChange:this.submitForm.bind(this)}),o.createElement("label",{className:"form-check-label",htmlFor:`${e.id}-true`},"Yes")),o.createElement("div",{className:"form-check"},o.createElement(a.Radio,{className:"form-check-input",id:`${e.id}-false`,value:!1,onChange:this.submitForm.bind(this)}),o.createElement("label",{className:"form-check-label",htmlFor:`${e.id}-false`},"No")))))}}t.BooleanItem=u,t.default=l.useObservableModel(u)},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=n(2),l=n(1),s=i(n(4));class u extends s.default{render(){const{item:e}=this.props,t=e.initialAnswers[0]&&e.initialAnswers[0].value;return o.createElement(a.Form,{getApi:this.getFormApi.bind(this),key:e.id,onSubmit:this.handleSubmit.bind(this)},o.createElement("label",{htmlFor:`${e.id}-initial`,className:"question-item-label"},"Default answer"),o.createElement(a.Text,{autoComplete:"off",className:"form-control",type:"time",initialValue:t,field:"value",id:`${e.id}-initial`,onBlur:this.submitForm.bind(this)}))}}t.TimeItem=u,t.default=l.useObservableModel(u)},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=n(2),l=n(1),s=i(n(4));class u extends s.default{render(){const{item:e}=this.props,t=e.initialAnswers[0]&&e.initialAnswers[0].value;return o.createElement(a.Form,{getApi:this.getFormApi.bind(this),key:e.id,onSubmit:this.handleSubmit.bind(this)},o.createElement("label",{htmlFor:`${e.id}-initial`,className:"question-item-label"},"Default answer"),o.createElement(a.Text,{autoComplete:"off",className:"form-control",type:"date",initialValue:t,field:"value",id:`${e.id}-initial`,onBlur:this.submitForm.bind(this)}))}}t.DateItem=u,t.default=l.useObservableModel(u)},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=n(2),l=n(1),s=i(n(4));class u extends s.default{render(){const{item:e}=this.props,t=e.initialAnswers[0]&&e.initialAnswers[0].value;return o.createElement(a.Form,{getApi:this.getFormApi.bind(this),key:e.id,onSubmit:this.handleSubmit.bind(this)},o.createElement("label",{htmlFor:`${e.id}-initial`,className:"question-item-label"},"Default answer"),o.createElement(a.Text,{autoComplete:"off",className:"form-control",type:"datetime-local",initialValue:t,field:"value",id:`${e.id}-initial`,onBlur:this.submitForm.bind(this)}))}}t.DateTimeItem=u,t.default=l.useObservableModel(u)},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=n(1),l=n(2),s=i(n(4));class u extends s.default{getFormApi(e){this.formApi=e}handleSubmit(e){const{item:t}=this.props;t.updateItem({...t,multipleFiles:!!e.multipleFiles})}componentDidUpdate(){const{item:e}=this.props;this.formApi&&this.formApi.setValue("multipleFiles",e.multipleFiles)}render(){const{item:e}=this.props;return o.createElement(l.Form,{getApi:this.getFormApi.bind(this),key:e.id,onSubmit:this.handleSubmit.bind(this)},o.createElement("div",{className:"form-group"},o.createElement("input",{type:"file",className:"form-control-file",id:`${e.id}-initial`,disabled:!0})),o.createElement("div",null,o.createElement("div",{className:"form-check"},o.createElement(l.Checkbox,{className:"form-check-input",initialValue:e.multipleFiles,field:"multipleFiles",id:`${e.id}-multipleFiles`,onChange:this.submitForm.bind(this)}),o.createElement("label",{className:"form-check-label",htmlFor:`${e.id}-multipleFiles`},"Allow multiple upload"))))}}t.AttachmentItem=u,t.default=a.useObservableModel(u)},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=r(n(3)),l=n(1),s=i(n(9)),u=n(2),c=i(n(4));class d extends c.default{constructor(){super(...arguments),this.answerOptionFactory=new a.AnswerOptionFactory(this.props.item)}reset(){const{item:e}=this.props;e.clearInitialAnswers()}addOption(){const{item:e}=this.props;e.addAnswerOption(this.answerOptionFactory.createAnswerOption())}renderChoiceOptions(){const{item:e}=this.props,t=e.initialAnswers[0]&&e.initialAnswers[0].value;return o.createElement("div",{className:"option-list"},o.createElement(u.Form,{getApi:this.getFormApi.bind(this),onSubmit:this.handleSubmit.bind(this)},o.createElement(u.RadioGroup,{initialValue:t,field:"value"},e.options.map(e=>o.createElement(s.default,{key:e.id,option:e})))))}render(){return o.createElement("div",null,o.createElement("button",{className:"btn btn-link text-secondary pl-0",onClick:this.reset.bind(this)},"Remove default value"),this.renderChoiceOptions(),o.createElement("div",null,o.createElement("button",{className:"btn btn-outline-secondary border-0",onClick:this.addOption.bind(this)},o.createElement("i",{className:"fas fa-plus mr-1"}),o.createElement("span",null,"Add option"))))}}t.ChoiceItem=d,t.default=l.useObservableModel(d)},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=r(n(3)),l=n(1),s=i(n(9)),u=n(2),c=i(n(4)),d=n(33);class f extends c.default{constructor(){super(...arguments),this.answerOptionFactory=new a.AnswerOptionFactory(this.props.item)}reset(){const{item:e}=this.props;e.clearInitialAnswers()}addOption(){const{item:e}=this.props;e.addAnswerOption(this.answerOptionFactory.createAnswerOption())}renderChoiceOptions(){const{item:e}=this.props,t=e.initialAnswers[0]&&e.initialAnswers[0].value;return o.createElement("div",{className:"option-list"},o.createElement(u.Form,{getApi:this.getFormApi.bind(this),onSubmit:this.handleSubmit.bind(this)},o.createElement(u.RadioGroup,{initialValue:t,field:"value"},e.options.map((t,n)=>n===e.options.length-1?o.createElement(d.ChoiceOptionOther,{key:t.id,option:t}):o.createElement(s.default,{key:t.id,option:t})))))}render(){return o.createElement("div",null,o.createElement("button",{className:"btn btn-link text-secondary pl-0",onClick:this.reset.bind(this)},"Remove default value"),this.renderChoiceOptions(),o.createElement("div",null,o.createElement("button",{className:"btn btn-outline-secondary border-0",onClick:this.addOption.bind(this)},o.createElement("i",{className:"fas fa-plus mr-1"}),o.createElement("span",null,"Add option"))))}}t.OpenChoiceItem=f,t.default=l.useObservableModel(f)},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});const i=r(n(0)),o=n(1);class a extends i.Component{constructor(){super(...arguments),this.RadioRef=i.createRef()}onBlur(e){const{option:t}=this.props;t.setValue(e.target.value)}remove(){const{option:e}=this.props;e.remove()}onChange(e){const{option:t}=this.props;e.target.checked?t.selectAsDefault():t.unselectAsDefault()}render(){const{option:e}=this.props,t=!e.defaultSelected;return i.createElement("div",{className:"form-group"},i.createElement("label",{htmlFor:`${e.id}-option`},"Other"),i.createElement("div",{className:"input-group"},i.createElement("div",{className:"input-group-prepend"},i.createElement("div",{className:"input-group-text"},i.createElement("label",{htmlFor:`${e.id}-initial`,className:"mr-1 mb-0"},"By default"),i.createElement("input",{checked:e.defaultSelected,id:`${e.id}-initial`,type:"radio",onChange:this.onChange.bind(this)}))),i.createElement("input",{autoComplete:"off",id:`${e.id}-option`,className:"form-control",disabled:t,defaultValue:e.value,onBlur:this.onBlur.bind(this)})))}}t.ChoiceOptionOther=a,t.default=o.useObservableModel(a)},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=r(n(3)),l=n(1),s=i(n(35));class u extends o.Component{constructor(){super(...arguments),this.answerOptionFactory=new a.AnswerOptionFactory(this.props.item)}addOption(){const{item:e}=this.props;e.addAnswerOption(this.answerOptionFactory.createAnswerOption())}renderChoiceOptions(){const{item:e}=this.props;return o.createElement("div",{className:"option-list"},e.options.map(t=>o.createElement(s.default,{key:t.id,option:t,item:e})))}render(){return o.createElement("div",null,this.renderChoiceOptions(),o.createElement("div",null,o.createElement("button",{className:"btn btn-outline-secondary border-0",onClick:this.addOption.bind(this)},o.createElement("i",{className:"fas fa-plus mr-1"}),o.createElement("span",null,"Add option"))))}}t.MultiChoiceItem=u,t.default=l.useObservableModel(u)},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});const i=r(n(0)),o=n(1);class a extends i.Component{onBlur(e){const{option:t}=this.props;t.setValue(e.target.value)}remove(){const{option:e}=this.props;e.remove()}onChange(e){const{option:t}=this.props;e.target.checked?t.selectAsDefault():t.unselectAsDefault()}renderCheckbox(){const{option:e}=this.props;return i.createElement("div",{className:"input-group-text"},i.createElement("label",{className:"mr-1 mb-0",htmlFor:`${e.id}-checkbox`},"By default"),i.createElement("input",{id:`${e.id}-checkbox`,type:"checkbox",checked:e.defaultSelected,onChange:this.onChange.bind(this)}))}render(){const{option:e}=this.props;return i.createElement("div",{className:"form-group"},i.createElement("div",{className:"input-group"},i.createElement("div",{className:"input-group-prepend"},this.renderCheckbox()),i.createElement("input",{autoComplete:"off",className:"form-control",defaultValue:e.value,onBlur:this.onBlur.bind(this)}),i.createElement("div",{className:"input-group-append"},i.createElement("button",{type:"button",className:"btn btn-outline-secondary",onClick:this.remove.bind(this)},i.createElement("i",{className:"fas fa-trash"})))))}}t.MultiChoiceOption=a,t.default=o.useObservableModel(a)},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=r(n(3)),l=i(n(5)),s=n(37);class u extends o.Component{constructor(e){super(e),this.options=s.questionTypes,this.humanReadableGuide=l.default.getHumanReadableGuid(),this.item=e.item,this.factory=new a.ItemFactory(this.item.parent)}onChange(e){switch(e.target.value){case a.STRING:this.changeItemToString();break;case a.TEXT:this.changeItemToText();break;case a.BOOLEAN:this.changeItemToBoolean();break;case a.DECIMAL:this.changeItemToDecimal();break;case a.TIME:this.changeItemToTime();break;case a.DATE:this.changeItemToDate();break;case a.DATE_TIME:this.changeItemToDateTime();break;case a.CHOICE:this.changeItemToChoice();break;case a.OPEN_CHOICE:this.changeItemToOpenChoice();break;case a.ATTACHMENT:this.changeItemToAttachment();break;case a.MULTI_CHOICE:this.changeItemToMultiChoice();break;default:return}}changeItemToString(){const{item:e,selectTargetItem:t}=this.props,n=this.factory.createStringItem({text:e.text,required:e.required,enableWhen:e.enableWhen,enableBehavior:e.enableBehavior});e.replace(n),t&&t(n),this.humanReadableGuide.updateKey(e.id,n.id)}changeItemToText(){const{item:e,selectTargetItem:t}=this.props,n=this.factory.createTextItem({text:e.text,required:e.required,enableWhen:e.enableWhen,enableBehavior:e.enableBehavior});e.replace(n),t&&t(n),this.humanReadableGuide.updateKey(e.id,n.id)}changeItemToBoolean(){const{item:e,selectTargetItem:t}=this.props,n=this.factory.createBooleanItem({text:e.text,required:e.required,enableWhen:e.enableWhen,enableBehavior:e.enableBehavior});e.replace(n),t&&t(n),this.humanReadableGuide.updateKey(e.id,n.id)}changeItemToDecimal(){const{item:e,selectTargetItem:t}=this.props,n=this.factory.createDecimalItem({text:e.text,required:e.required,enableWhen:e.enableWhen,enableBehavior:e.enableBehavior});e.replace(n),t&&t(n),this.humanReadableGuide.updateKey(e.id,n.id)}changeItemToTime(){const{item:e,selectTargetItem:t}=this.props,n=this.factory.createTimeItem({text:e.text,required:e.required,enableWhen:e.enableWhen,enableBehavior:e.enableBehavior});e.replace(n),t&&t(n),this.humanReadableGuide.updateKey(e.id,n.id)}changeItemToDate(){const{item:e,selectTargetItem:t}=this.props,n=this.factory.createDateItem({text:e.text,required:e.required,enableWhen:e.enableWhen,enableBehavior:e.enableBehavior});e.replace(n),t&&t(n),this.humanReadableGuide.updateKey(e.id,n.id)}changeItemToDateTime(){const{item:e,selectTargetItem:t}=this.props,n=this.factory.createDateTimeItem({text:e.text,required:e.required,enableWhen:e.enableWhen,enableBehavior:e.enableBehavior});e.replace(n),t&&t(n),this.humanReadableGuide.updateKey(e.id,n.id)}changeItemToChoice(){const{item:e,selectTargetItem:t}=this.props,n=new a.AnswerOptionFactory;let r;void 0===e.options||0===e.options.length||e.type===a.OPEN_CHOICE&&1===e.options.length?r=[n.createAnswerOption({value:"Option 1"})]:(r=e.options.slice(),e.type===a.OPEN_CHOICE&&r.pop());const i=this.factory.createChoiceItem({text:e.text,options:r,required:e.required,enableWhen:e.enableWhen,enableBehavior:e.enableBehavior});i.options.forEach(e=>{e.parent=i}),e.replace(i),t&&t(i),this.humanReadableGuide.updateKey(e.id,i.id)}changeItemToOpenChoice(){const{item:e,selectTargetItem:t}=this.props,n=new a.AnswerOptionFactory;let r;r=void 0===e.options?[n.createAnswerOption({value:"Option 1"})]:0===e.options.length?[n.createAnswerOption({value:"Option 1"})]:e.options.slice(),r.push(n.createAnswerOption());const i=this.factory.createOpenChoiceItem({text:e.text,options:r,required:e.required,enableWhen:e.enableWhen,enableBehavior:e.enableBehavior});i.options.forEach(e=>{e.parent=i}),e.replace(i),t&&t(i),this.humanReadableGuide.updateKey(e.id,i.id)}changeItemToMultiChoice(){const{item:e,selectTargetItem:t}=this.props,n=new a.AnswerOptionFactory;let r;void 0===e.options||0===e.options.length||e.type===a.OPEN_CHOICE&&1===e.options.length?r=[n.createAnswerOption({value:"Option 1"})]:(r=e.options.slice(),e.type===a.OPEN_CHOICE&&r.pop());const i=this.factory.createMultiChoiceItem({text:e.text,options:r,required:e.required,enableWhen:e.enableWhen,enableBehavior:e.enableBehavior});i.options.forEach(e=>{e.parent=i}),e.replace(i),t&&t(i),this.humanReadableGuide.updateKey(e.id,i.id)}changeItemToAttachment(){const{item:e,selectTargetItem:t}=this.props,n=this.factory.createAttachmentItem({text:e.text,required:e.required,enableWhen:e.enableWhen,enableBehavior:e.enableBehavior});e.replace(n),t&&t(n),this.humanReadableGuide.updateKey(e.id,n.id)}render(){const{item:e,title:t}=this.props;return o.createElement("div",null,o.createElement("label",{htmlFor:`${e.id}-select-menu`},t),o.createElement("select",{id:`${e.id}-select-menu`,className:"form-control",defaultValue:e.type,onChange:this.onChange.bind(this)},this.options.map(t=>o.createElement("option",{key:`${e.id}-${t.value}`,value:t.value},t.title))))}}t.QuestionTypeMenu=u,t.default=u},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});const i=r(n(3));t.questionTypes=[{title:"String (one row)",value:i.STRING},{title:"Text (several rows)",value:i.TEXT},{title:"Number",value:i.DECIMAL},{title:"Date",value:i.DATE},{title:"Time",value:i.TIME},{title:"Date-time",value:i.DATE_TIME},{title:"Yes/No question",value:i.BOOLEAN},{title:"Single choice",value:i.CHOICE},{title:"Open choice",value:i.OPEN_CHOICE},{title:"Multiple choice",value:i.MULTI_CHOICE},{title:"Attachment",value:i.ATTACHMENT}]},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=r(n(3)),l=n(2),s=i(n(39)),u=n(1);class c extends o.Component{constructor(e){super(e),this.enableWhenFactory=new a.EnableWhenFactory(e.item)}getFormApi(e){this.formApi=e}componentDidUpdate(){const{item:e}=this.props;this.formApi&&this.formApi.setValues(e)}fillQuestionList(e,t){t.items&&t.items.forEach(t=>{t.type===a.GROUP?this.fillQuestionList(e,t):t.type!==a.DISPLAY&&t.type!==a.ATTACHMENT&&e.push(t)})}prepareQuestionList(){const{questionnaire:e}=this.props,t=[];return this.fillQuestionList(t,e),t}addEnableWhen(){const{item:e}=this.props,t=this.enableWhenFactory.createEnableWhen({operator:a.EQUAL});e.addEnableWhen(t)}removeAllEnableWhen(){const{item:e}=this.props;e.enableWhen=[]}setEnableBehavior(){const{item:e}=this.props;this.formApi&&(e.enableBehavior=this.formApi.getValue("enableBehavior"))}render(){const{item:e}=this.props,t=this.prepareQuestionList();return o.createElement("div",{className:"enable-when"},o.createElement(l.Form,{initialValues:e,getApi:this.getFormApi.bind(this)},o.createElement("div",{className:"d-flex"},o.createElement("label",{htmlFor:`enableWhenBehavior-${e.id}`,className:"mr-3"},o.createElement("span",null,"This component should Display if "),o.createElement(l.Select,{id:`enableWhenBehavior-${e.id}`,className:"form-control w-auto d-inline ml-2",field:"enableBehavior",onChange:this.setEnableBehavior.bind(this)},o.createElement(l.Option,{value:a.AND},"all the rules are consistent"),o.createElement(l.Option,{value:a.OR},"one of the rules is consistent")))),o.createElement("div",null,o.createElement("div",{className:"list-group list-group-flush form-group"},!!e.enableWhen.length&&o.createElement("div",{className:"list-group-item list-group-item-action"},o.createElement("div",{className:"row"},o.createElement("div",{className:"col col-3"},"Question"),o.createElement("div",{className:"col col-3"},"Operator"),o.createElement("div",{className:"col col-5"},"Answer"),o.createElement("div",{className:"col col-1"}))),o.createElement(l.Scope,{scope:"enableWhen"},e.enableWhen.map((n,r)=>{const i=t.filter(t=>t.id!==e.id);return o.createElement(o.Fragment,{key:n.id},o.createElement(s.default,{questionList:i,enableWhen:n,index:r}))})))),o.createElement("div",null,o.createElement("button",{className:"btn btn-outline-secondary border-0",onClick:this.addEnableWhen.bind(this)},o.createElement("i",{className:"fas fa-plus mr-1"}),"Add Rule"))))}}t.EnableSettings=c,t.default=u.useObservableModel(c)},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=r(n(3)),l=n(2),s=i(n(40)),u=n(1),c=i(n(5));class d extends o.Component{constructor(e){super(e),this.state={},this.operators=[{value:a.EQUAL,text:"Equal( == )"},{value:a.NOT_EQUAL,text:"Not equal( != )"},{value:a.EXISTS,text:"Exists( not null )"},{value:a.MORE,text:"More( > )"},{value:a.LESS,text:"Less( < )"},{value:a.MORE_OR_EQUAL,text:"More or equal( >= )"},{value:a.LESS_OR_EQUAL,text:"Less or equal( <= )"}],this.humanReadableGuid=c.default.getHumanReadableGuid();const t=e.enableWhen.questionId,n=e.questionList.find(e=>e.id===t);this.state={selectedQuestion:n}}selectQuestion(e){const{questionList:t,enableWhen:n,formApi:r,index:i}=this.props,o=r.getValue(`${i}][questionId`),a=t.find(e=>e.id===o);n.questionId=o,this.setState({selectedQuestion:a})}removeEnableWhen(){const{enableWhen:e}=this.props;e.remove()}setOperator(e){const{enableWhen:t}=this.props,n=e.target.value;t.operator=n}renderQuestionSelect(){const{questionList:e,index:t}=this.props;return o.createElement(l.Select,{className:"form-control",field:`${t}][questionId`,onChange:this.selectQuestion.bind(this)},o.createElement(l.Option,{value:"",disabled:!0},"Select question"),e.map(e=>o.createElement(l.Option,{key:`${e.id}-enableWhenQuestion`,value:e.id},`#${this.humanReadableGuid.getHumanReadableId(e.id)} ${void 0===e.text?"":e.text}`)))}renderOperatorSelect(){const{index:e}=this.props;return o.createElement(l.Select,{className:"form-control",field:`${e}][operator`,onChange:this.setOperator.bind(this)},o.createElement(l.Option,{value:"",disabled:!0},"Select operator"),this.operators.map((e,t)=>o.createElement(l.Option,{key:t,value:e.value},e.text)))}render(){const{index:e,enableWhen:t}=this.props,{selectedQuestion:n}=this.state;return o.createElement("div",{className:"list-group-item list-group-item-action"},o.createElement("div",{className:"row align-items-center"},o.createElement("div",{className:"col col-3"},this.renderQuestionSelect()),o.createElement("div",{className:"col col-3"},this.renderOperatorSelect()),o.createElement("div",{className:"col"},o.createElement(s.default,{item:n,index:e,enableWhen:t})),o.createElement("div",{className:"col col-auto"},o.createElement("button",{className:"btn btn-outline-secondary border-0",onClick:this.removeEnableWhen.bind(this)},o.createElement("i",{className:"fas fa-trash"})))))}}t.EnableWhen=d,t.default=l.withFormApi(u.useObservableModel(d))},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const o=r(n(0)),a=r(n(3)),l=i(n(41)),s=i(n(42)),u=i(n(43)),c=i(n(44)),d=i(n(45));t.QuestionItemProvider=e=>{const{item:t={},index:n,enableWhen:r}=e;switch(t.type){case a.STRING:return o.createElement(l.default,{enableWhen:r,index:n,type:"text"});case a.TEXT:return o.createElement(l.default,{enableWhen:r,index:n,type:"textarea"});case a.TIME:return o.createElement(l.default,{enableWhen:r,index:n,type:"time"});case a.DATE:return o.createElement(l.default,{enableWhen:r,index:n,type:"date"});case a.DATE_TIME:return o.createElement(l.default,{enableWhen:r,index:n,type:"datetime-local"});case a.DECIMAL:return o.createElement(l.default,{enableWhen:r,index:n,type:"number"});case a.CHOICE:case a.MULTI_CHOICE:return o.createElement(s.default,{enableWhen:r,index:n,item:t});case a.OPEN_CHOICE:return o.createElement(u.default,{enableWhen:r,index:n,item:t});case a.BOOLEAN:return o.createElement(c.default,{enableWhen:r,index:n});default:return o.createElement(d.default,null)}},t.default=t.QuestionItemProvider},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});const i=r(n(0)),o=n(2);t.Input=e=>{const{type:t,index:n,enableWhen:r}=e,a=o.useFormApi(),l=()=>{const e=a.getValue(`${n}][answer`);r.answer=e};return i.createElement("div",null,"textarea"===t?i.createElement(o.TextArea,{className:"form-control",field:`${n}][answer`,id:"enableWhenAnswer",onBlur:l}):i.createElement(o.Text,{type:t,className:"form-control",field:`${n}][answer`,id:"enableWhenAnswer",onBlur:l}))},t.default=t.Input},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});const i=r(n(0)),o=n(2);t.Choice=e=>{const{item:t,index:n,enableWhen:r}=e,a=o.useFormApi();return i.createElement(o.Select,{className:"form-control",field:`${n}][answer`,onChange:()=>{const e=a.getValue(`${n}][answer`),i=t.options&&t.options.find(t=>t.id===e);i&&(r.answer=i.value)}},i.createElement(o.Option,{value:"",disabled:!0},"Select answer"),t.options&&t.options.map((e,t)=>i.createElement(o.Option,{key:t,value:e.id},e.value)))},t.default=t.Choice},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});const i=r(n(0)),o=n(2);class a extends i.Component{constructor(e){super(e),this.otherAnswerInputRef=i.createRef(),e.item.options&&e.item.options.every(t=>t.value!==e.enableWhen.answer)&&0!==e.item.options.length&&(this.initialOtherOptionValue=e.enableWhen.answer,this.toggleToOtherOption())}onChange(){const{enableWhen:e,formApi:t,index:n,item:r}=this.props;let i=!1;const o=t.getValue(`${n}][answer`),a=r.options&&r.options.find((e,t)=>e.id===o&&(r.options&&t===r.options.length-1&&(i=!0),!0));i?this.toggleToOtherOption():(this.toggleToOptions(),a&&(e.answer=a.value))}toggleToOptions(){this.otherAnswerInputRef.current&&(this.otherAnswerInputRef.current.style.display="none")}toggleToOtherOption(){this.otherAnswerInputRef.current&&(this.otherAnswerInputRef.current.style.display=""),this.onBlur()}onBlur(){const{enableWhen:e}=this.props;this.otherAnswerInputRef.current&&(e.answer=this.otherAnswerInputRef.current.value)}render(){const{item:e,index:t}=this.props;return i.createElement("div",{className:"row"},i.createElement("div",{className:"col-5"},i.createElement(o.Select,{className:"form-control",field:`${t}][answer`,onChange:this.onChange.bind(this)},i.createElement(o.Option,{value:"",disabled:!0},"Select answer"),e.options&&e.options.map((t,n)=>i.createElement(o.Option,{key:n,value:t.id},e.options&&n===e.options.length-1?"Other":t.value)))),i.createElement("div",{className:"col-7"},i.createElement(o.Text,{field:`${t}][answer-other`,className:"form-control",forwardedRef:this.otherAnswerInputRef,onBlur:this.onBlur.bind(this),initialValue:this.initialOtherOptionValue,style:{display:"none"}})))}}t.OpenChoice=a,t.default=o.withFormApi(a)},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});const i=r(n(0)),o=n(2);t.Boolean=e=>{const{index:t,enableWhen:n}=e,r=o.useFormApi();return i.createElement(o.Select,{className:"form-control",field:`${t}][answer`,onChange:()=>{const e=r.getValue(`${t}][answer`);n.answer="true"===e}},i.createElement(o.Option,{value:"",disabled:!0},"Select answer"),i.createElement(o.Option,{value:!0},"Yes"),i.createElement(o.Option,{value:!1},"No"))},t.default=t.Boolean},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});const i=r(n(0));t.DefaultAnswerInput=()=>i.createElement("input",{className:"form-control",disabled:!0}),t.default=t.DefaultAnswerInput},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.activeItemClassName="card-active shadow"},function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});const i=r(n(0)),o=r(n(3));class a extends i.Component{constructor(){super(...arguments),this.itemFactory=new o.ItemFactory}addItem(){const{item:e,selectTargetItem:t,close:n}=this.props,r=this.itemFactory.createItem();e.addSiblingItemAfter(r),t&&t(r),n&&n()}addGroupItem(){const{item:e,selectTargetItem:t,close:n}=this.props,r=this.itemFactory.createGroupItem();e.addSiblingItemAfter(r),t&&t(r),n&&n()}addChoiceItem(){const{item:e,selectTargetItem:t,close:n}=this.props,r=this.itemFactory.createChoiceItem(),i=new o.AnswerOptionFactory(r);r.addAnswerOption(i.createAnswerOption({value:"Option 1"})),e.addSiblingItemAfter(r),t&&t(r),n&&n()}render(){return i.createElement("div",{className:"dropdown-menu dropdown-menu-right btn-group-vertical"},i.createElement("button",{className:"btn btn-secondary",title:"Add text",onClick:this.addItem.bind(this)},i.createElement("i",{className:"fas fa-font"})),i.createElement("button",{className:"btn btn-secondary",title:"Add group",onClick:this.addGroupItem.bind(this)},i.createElement("i",{className:"fas fa-layer-group"})),i.createElement("button",{className:"btn btn-secondary",title:"Add question",onClick:this.addChoiceItem.bind(this)},i.createElement("i",{className:"fas fa-plus"})))}}t.BottomItemCollectionMenu=a,t.default=a},function(e,t,n){"use strict"; /**! * Sortable 1.10.1 * @author RubaXa <trash@rubaxa.org> * @author owenm <owen23355@gmail.com> * @license MIT */ function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(){return(o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}function a(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){i(e,t,n[t])}))}return e}function l(e,t){if(null==e)return{};var n,r,i=function(e,t){if(null==e)return{};var n,r,i={},o=Object.keys(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||(i[n]=e[n]);return i}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function s(e){return function(e){if(Array.isArray(e)){for(var t=0,n=new Array(e.length);t<e.length;t++)n[t]=e[t];return n}}(e)||function(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}n.r(t),n.d(t,"MultiDrag",(function(){return yt})),n.d(t,"Sortable",(function(){return Ve})),n.d(t,"Swap",(function(){return st}));function u(e){if("undefined"!=typeof window&&window.navigator)return!!navigator.userAgent.match(e)}var c=u(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i),d=u(/Edge/i),f=u(/firefox/i),h=u(/safari/i)&&!u(/chrome/i)&&!u(/android/i),p=u(/iP(ad|od|hone)/i),m=u(/chrome/i)&&u(/android/i),v={capture:!1,passive:!1};function g(e,t,n){e.addEventListener(t,n,!c&&v)}function b(e,t,n){e.removeEventListener(t,n,!c&&v)}function y(e,t){if(t){if(">"===t[0]&&(t=t.substring(1)),e)try{if(e.matches)return e.matches(t);if(e.msMatchesSelector)return e.msMatchesSelector(t);if(e.webkitMatchesSelector)return e.webkitMatchesSelector(t)}catch(e){return!1}return!1}}function E(e){return e.host&&e!==document&&e.host.nodeType?e.host:e.parentNode}function _(e,t,n,r){if(e){n=n||document;do{if(null!=t&&(">"===t[0]?e.parentNode===n&&y(e,t):y(e,t))||r&&e===n)return e;if(e===n)break}while(e=E(e))}return null}var w,O=/\s+/g;function C(e,t,n){if(e&&t)if(e.classList)e.classList[n?"add":"remove"](t);else{var r=(" "+e.className+" ").replace(O," ").replace(" "+t+" "," ");e.className=(r+(n?" "+t:"")).replace(O," ")}}function A(e,t,n){var r=e&&e.style;if(r){if(void 0===n)return document.defaultView&&document.defaultView.getComputedStyle?n=document.defaultView.getComputedStyle(e,""):e.currentStyle&&(n=e.currentStyle),void 0===t?n:n[t];t in r||-1!==t.indexOf("webkit")||(t="-webkit-"+t),r[t]=n+("string"==typeof n?"":"px")}}function S(e,t){var n="";if("string"==typeof e)n=e;else do{var r=A(e,"transform");r&&"none"!==r&&(n=r+" "+n)}while(!t&&(e=e.parentNode));var i=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix;return i&&new i(n)}function x(e,t,n){if(e){var r=e.getElementsByTagName(t),i=0,o=r.length;if(n)for(;i<o;i++)n(r[i],i);return r}return[]}function I(){return c?document.documentElement:document.scrollingElement}function T(e,t,n,r,i){if(e.getBoundingClientRect||e===window){var o,a,l,s,u,d,f;if(e!==window&&e!==I()?(a=(o=e.getBoundingClientRect()).top,l=o.left,s=o.bottom,u=o.right,d=o.height,f=o.width):(a=0,l=0,s=window.innerHeight,u=window.innerWidth,d=window.innerHeight,f=window.innerWidth),(t||n)&&e!==window&&(i=i||e.parentNode,!c))do{if(i&&i.getBoundingClientRect&&("none"!==A(i,"transform")||n&&"static"!==A(i,"position"))){var h=i.getBoundingClientRect();a-=h.top+parseInt(A(i,"border-top-width")),l-=h.left+parseInt(A(i,"border-left-width")),s=a+o.height,u=l+o.width;break}}while(i=i.parentNode);if(r&&e!==window){var p=S(i||e),m=p&&p.a,v=p&&p.d;p&&(s=(a/=v)+(d/=v),u=(l/=m)+(f/=m))}return{top:a,left:l,bottom:s,right:u,width:f,height:d}}}function F(e,t,n){for(var r=P(e,!0),i=T(e)[t];r;){var o=T(r)[n];if(!("top"===n||"left"===n?i>=o:i<=o))return r;if(r===I())break;r=P(r,!1)}return!1}function M(e,t,n){for(var r=0,i=0,o=e.children;i<o.length;){if("none"!==o[i].style.display&&o[i]!==Ve.ghost&&o[i]!==Ve.dragged&&_(o[i],n.draggable,e,!1)){if(r===t)return o[i];r++}i++}return null}function N(e,t){for(var n=e.lastElementChild;n&&(n===Ve.ghost||"none"===A(n,"display")||t&&!y(n,t));)n=n.previousElementSibling;return n||null}function D(e,t){var n=0;if(!e||!e.parentNode)return-1;for(;e=e.previousElementSibling;)"TEMPLATE"===e.nodeName.toUpperCase()||e===Ve.clone||t&&!y(e,t)||n++;return n}function j(e){var t=0,n=0,r=I();if(e)do{var i=S(e),o=i.a,a=i.d;t+=e.scrollLeft*o,n+=e.scrollTop*a}while(e!==r&&(e=e.parentNode));return[t,n]}function P(e,t){if(!e||!e.getBoundingClientRect)return I();var n=e,r=!1;do{if(n.clientWidth<n.scrollWidth||n.clientHeight<n.scrollHeight){var i=A(n);if(n.clientWidth<n.scrollWidth&&("auto"==i.overflowX||"scroll"==i.overflowX)||n.clientHeight<n.scrollHeight&&("auto"==i.overflowY||"scroll"==i.overflowY)){if(!n.getBoundingClientRect||n===document.body)return I();if(r||t)return n;r=!0}}}while(n=n.parentNode);return I()}function k(e,t){return Math.round(e.top)===Math.round(t.top)&&Math.round(e.left)===Math.round(t.left)&&Math.round(e.height)===Math.round(t.height)&&Math.round(e.width)===Math.round(t.width)}function R(e,t){return function(){if(!w){var n=arguments,r=this;1===n.length?e.call(r,n[0]):e.apply(r,n),w=setTimeout((function(){w=void 0}),t)}}}function L(e,t,n){e.scrollLeft+=t,e.scrollTop+=n}function B(e){var t=window.Polymer,n=window.jQuery||window.Zepto;return t&&t.dom?t.dom(e).cloneNode(!0):n?n(e).clone(!0)[0]:e.cloneNode(!0)}function V(e,t){A(e,"position","absolute"),A(e,"top",t.top),A(e,"left",t.left),A(e,"width",t.width),A(e,"height",t.height)}function q(e){A(e,"position",""),A(e,"top",""),A(e,"left",""),A(e,"width",""),A(e,"height","")}var G="Sortable"+(new Date).getTime();function W(){var e,t=[];return{captureAnimationState:function(){(t=[],this.options.animation)&&[].slice.call(this.el.children).forEach((function(e){if("none"!==A(e,"display")&&e!==Ve.ghost){t.push({target:e,rect:T(e)});var n=a({},t[t.length-1].rect);if(e.thisAnimationDuration){var r=S(e,!0);r&&(n.top-=r.f,n.left-=r.e)}e.fromRect=n}}))},addAnimationState:function(e){t.push(e)},removeAnimationState:function(e){t.splice(function(e,t){for(var n in e)if(e.hasOwnProperty(n))for(var r in t)if(t.hasOwnProperty(r)&&t[r]===e[n][r])return Number(n);return-1}(t,{target:e}),1)},animateAll:function(n){var r=this;if(!this.options.animation)return clearTimeout(e),void("function"==typeof n&&n());var i=!1,o=0;t.forEach((function(e){var t=0,n=e.target,a=n.fromRect,l=T(n),s=n.prevFromRect,u=n.prevToRect,c=e.rect,d=S(n,!0);d&&(l.top-=d.f,l.left-=d.e),n.toRect=l,n.thisAnimationDuration&&k(s,l)&&!k(a,l)&&(c.top-l.top)/(c.left-l.left)==(a.top-l.top)/(a.left-l.left)&&(t=function(e,t,n,r){return Math.sqrt(Math.pow(t.top-e.top,2)+Math.pow(t.left-e.left,2))/Math.sqrt(Math.pow(t.top-n.top,2)+Math.pow(t.left-n.left,2))*r.animation}(c,s,u,r.options)),k(l,a)||(n.prevFromRect=a,n.prevToRect=l,t||(t=r.options.animation),r.animate(n,c,l,t)),t&&(i=!0,o=Math.max(o,t),clearTimeout(n.animationResetTimer),n.animationResetTimer=setTimeout((function(){n.animationTime=0,n.prevFromRect=null,n.fromRect=null,n.prevToRect=null,n.thisAnimationDuration=null}),t),n.thisAnimationDuration=t)})),clearTimeout(e),i?e=setTimeout((function(){"function"==typeof n&&n()}),o):"function"==typeof n&&n(),t=[]},animate:function(e,t,n,r){if(r){A(e,"transition",""),A(e,"transform","");var i=S(this.el),o=i&&i.a,a=i&&i.d,l=(t.left-n.left)/(o||1),s=(t.top-n.top)/(a||1);e.animatingX=!!l,e.animatingY=!!s,A(e,"transform","translate3d("+l+"px,"+s+"px,0)"),function(e){e.offsetWidth}(e),A(e,"transition","transform "+r+"ms"+(this.options.easing?" "+this.options.easing:"")),A(e,"transform","translate3d(0,0,0)"),"number"==typeof e.animated&&clearTimeout(e.animated),e.animated=setTimeout((function(){A(e,"transition",""),A(e,"transform",""),e.animated=!1,e.animatingX=!1,e.animatingY=!1}),r)}}}}var $=[],H={initializeByDefault:!0},U={mount:function(e){for(var t in H)!H.hasOwnProperty(t)||t in e||(e[t]=H[t]);$.push(e)},pluginEvent:function(e,t,n){var r=this;this.eventCanceled=!1,n.cancel=function(){r.eventCanceled=!0};var i=e+"Global";$.forEach((function(r){t[r.pluginName]&&(t[r.pluginName][i]&&t[r.pluginName][i](a({sortable:t},n)),t.options[r.pluginName]&&t[r.pluginName][e]&&t[r.pluginName][e](a({sortable:t},n)))}))},initializePlugins:function(e,t,n,r){for(var i in $.forEach((function(r){var i=r.pluginName;if(e.options[i]||r.initializeByDefault){var a=new r(e,t,e.options);a.sortable=e,a.options=e.options,e[i]=a,o(n,a.defaults)}})),e.options)if(e.options.hasOwnProperty(i)){var a=this.modifyOption(e,i,e.options[i]);void 0!==a&&(e.options[i]=a)}},getEventProperties:function(e,t){var n={};return $.forEach((function(r){"function"==typeof r.eventProperties&&o(n,r.eventProperties.call(t[r.pluginName],e))})),n},modifyOption:function(e,t,n){var r;return $.forEach((function(i){e[i.pluginName]&&i.optionListeners&&"function"==typeof i.optionListeners[t]&&(r=i.optionListeners[t].call(e[i.pluginName],n))})),r}};function Y(e){var t=e.sortable,n=e.rootEl,r=e.name,i=e.targetEl,o=e.cloneEl,l=e.toEl,s=e.fromEl,u=e.oldIndex,f=e.newIndex,h=e.oldDraggableIndex,p=e.newDraggableIndex,m=e.originalEvent,v=e.putSortable,g=e.extraEventProperties;if(t=t||n&&n[G]){var b,y=t.options,E="on"+r.charAt(0).toUpperCase()+r.substr(1);!window.CustomEvent||c||d?(b=document.createEvent("Event")).initEvent(r,!0,!0):b=new CustomEvent(r,{bubbles:!0,cancelable:!0}),b.to=l||n,b.from=s||n,b.item=i||n,b.clone=o,b.oldIndex=u,b.newIndex=f,b.oldDraggableIndex=h,b.newDraggableIndex=p,b.originalEvent=m,b.pullMode=v?v.lastPutMode:void 0;var _=a({},g,U.getEventProperties(r,t));for(var w in _)b[w]=_[w];n&&n.dispatchEvent(b),y[E]&&y[E].call(t,b)}}var Q=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.evt,i=l(n,["evt"]);U.pluginEvent.bind(Ve)(e,t,a({dragEl:z,parentEl:K,ghostEl:J,rootEl:Z,nextEl:ee,lastDownEl:te,cloneEl:ne,cloneHidden:re,dragStarted:ve,putSortable:ue,activeSortable:Ve.active,originalEvent:r,oldIndex:ie,oldDraggableIndex:ae,newIndex:oe,newDraggableIndex:le,hideGhostForTarget:ke,unhideGhostForTarget:Re,cloneNowHidden:function(){re=!0},cloneNowShown:function(){re=!1},dispatchSortableEvent:function(e){X({sortable:t,name:e,originalEvent:r})}},i))};function X(e){Y(a({putSortable:ue,cloneEl:ne,targetEl:z,rootEl:Z,oldIndex:ie,oldDraggableIndex:ae,newIndex:oe,newDraggableIndex:le},e))}var z,K,J,Z,ee,te,ne,re,ie,oe,ae,le,se,ue,ce,de,fe,he,pe,me,ve,ge,be,ye,Ee,_e=!1,we=!1,Oe=[],Ce=!1,Ae=!1,Se=[],xe=!1,Ie=[],Te="undefined"!=typeof document,Fe=p,Me=d||c?"cssFloat":"float",Ne=Te&&!m&&!p&&"draggable"in document.createElement("div"),De=function(){if(Te){if(c)return!1;var e=document.createElement("x");return e.style.cssText="pointer-events:auto","auto"===e.style.pointerEvents}}(),je=function(e,t){var n=A(e),r=parseInt(n.width)-parseInt(n.paddingLeft)-parseInt(n.paddingRight)-parseInt(n.borderLeftWidth)-parseInt(n.borderRightWidth),i=M(e,0,t),o=M(e,1,t),a=i&&A(i),l=o&&A(o),s=a&&parseInt(a.marginLeft)+parseInt(a.marginRight)+T(i).width,u=l&&parseInt(l.marginLeft)+parseInt(l.marginRight)+T(o).width;if("flex"===n.display)return"column"===n.flexDirection||"column-reverse"===n.flexDirection?"vertical":"horizontal";if("grid"===n.display)return n.gridTemplateColumns.split(" ").length<=1?"vertical":"horizontal";if(i&&a.float&&"none"!==a.float){var c="left"===a.float?"left":"right";return!o||"both"!==l.clear&&l.clear!==c?"horizontal":"vertical"}return i&&("block"===a.display||"flex"===a.display||"table"===a.display||"grid"===a.display||s>=r&&"none"===n[Me]||o&&"none"===n[Me]&&s+u>r)?"vertical":"horizontal"},Pe=function(e){function t(e,n){return function(r,i,o,a){var l=r.options.group.name&&i.options.group.name&&r.options.group.name===i.options.group.name;if(null==e&&(n||l))return!0;if(null==e||!1===e)return!1;if(n&&"clone"===e)return e;if("function"==typeof e)return t(e(r,i,o,a),n)(r,i,o,a);var s=(n?r:i).options.group.name;return!0===e||"string"==typeof e&&e===s||e.join&&e.indexOf(s)>-1}}var n={},i=e.group;i&&"object"==r(i)||(i={name:i}),n.name=i.name,n.checkPull=t(i.pull,!0),n.checkPut=t(i.put),n.revertClone=i.revertClone,e.group=n},ke=function(){!De&&J&&A(J,"display","none")},Re=function(){!De&&J&&A(J,"display","")};Te&&document.addEventListener("click",(function(e){if(we)return e.preventDefault(),e.stopPropagation&&e.stopPropagation(),e.stopImmediatePropagation&&e.stopImmediatePropagation(),we=!1,!1}),!0);var Le=function(e){if(z){e=e.touches?e.touches[0]:e;var t=(i=e.clientX,o=e.clientY,Oe.some((function(e){if(!N(e)){var t=T(e),n=e[G].options.emptyInsertThreshold,r=i>=t.left-n&&i<=t.right+n,l=o>=t.top-n&&o<=t.bottom+n;return n&&r&&l?a=e:void 0}})),a);if(t){var n={};for(var r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);n.target=n.rootEl=t,n.preventDefault=void 0,n.stopPropagation=void 0,t[G]._onDragOver(n)}}var i,o,a},Be=function(e){z&&z.parentNode[G]._isOutsideThisEl(e.target)};function Ve(e,t){if(!e||!e.nodeType||1!==e.nodeType)throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(e));this.el=e,this.options=t=o({},t),e[G]=this;var n={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(e.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return je(e,this.options)},ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(e,t){e.setData("Text",t.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:!1!==Ve.supportPointer&&"PointerEvent"in window,emptyInsertThreshold:5};for(var r in U.initializePlugins(this,e,n),n)!(r in t)&&(t[r]=n[r]);for(var i in Pe(t),this)"_"===i.charAt(0)&&"function"==typeof this[i]&&(this[i]=this[i].bind(this));this.nativeDraggable=!t.forceFallback&&Ne,this.nativeDraggable&&(this.options.touchStartThreshold=1),t.supportPointer?g(e,"pointerdown",this._onTapStart):(g(e,"mousedown",this._onTapStart),g(e,"touchstart",this._onTapStart)),this.nativeDraggable&&(g(e,"dragover",this),g(e,"dragenter",this)),Oe.push(this.el),t.store&&t.store.get&&this.sort(t.store.get(this)||[]),o(this,W())}function qe(e,t,n,r,i,o,a,l){var s,u,f=e[G],h=f.options.onMove;return!window.CustomEvent||c||d?(s=document.createEvent("Event")).initEvent("move",!0,!0):s=new CustomEvent("move",{bubbles:!0,cancelable:!0}),s.to=t,s.from=e,s.dragged=n,s.draggedRect=r,s.related=i||t,s.relatedRect=o||T(t),s.willInsertAfter=l,s.originalEvent=a,e.dispatchEvent(s),h&&(u=h.call(f,s,a)),u}function Ge(e){e.draggable=!1}function We(){xe=!1}function $e(e){for(var t=e.tagName+e.className+e.src+e.href+e.textContent,n=t.length,r=0;n--;)r+=t.charCodeAt(n);return r.toString(36)}function He(e){return setTimeout(e,0)}function Ue(e){return clearTimeout(e)}Ve.prototype={constructor:Ve,_isOutsideThisEl:function(e){this.el.contains(e)||e===this.el||(ge=null)},_getDirection:function(e,t){return"function"==typeof this.options.direction?this.options.direction.call(this,e,t,z):this.options.direction},_onTapStart:function(e){if(e.cancelable){var t=this,n=this.el,r=this.options,i=r.preventOnFilter,o=e.type,a=e.touches&&e.touches[0]||e.pointerType&&"touch"===e.pointerType&&e,l=(a||e).target,s=e.target.shadowRoot&&(e.path&&e.path[0]||e.composedPath&&e.composedPath()[0])||l,u=r.filter;if(function(e){Ie.length=0;var t=e.getElementsByTagName("input"),n=t.length;for(;n--;){var r=t[n];r.checked&&Ie.push(r)}}(n),!z&&!(/mousedown|pointerdown/.test(o)&&0!==e.button||r.disabled||s.isContentEditable||(l=_(l,r.draggable,n,!1))&&l.animated||te===l)){if(ie=D(l),ae=D(l,r.draggable),"function"==typeof u){if(u.call(this,e,l,this))return X({sortable:t,rootEl:s,name:"filter",targetEl:l,toEl:n,fromEl:n}),Q("filter",t,{evt:e}),void(i&&e.cancelable&&e.preventDefault())}else if(u&&(u=u.split(",").some((function(r){if(r=_(s,r.trim(),n,!1))return X({sortable:t,rootEl:r,name:"filter",targetEl:l,fromEl:n,toEl:n}),Q("filter",t,{evt:e}),!0}))))return void(i&&e.cancelable&&e.preventDefault());r.handle&&!_(s,r.handle,n,!1)||this._prepareDragStart(e,a,l)}}},_prepareDragStart:function(e,t,n){var r,i=this,o=i.el,a=i.options,l=o.ownerDocument;if(n&&!z&&n.parentNode===o){var s=T(n);if(Z=o,K=(z=n).parentNode,ee=z.nextSibling,te=n,se=a.group,Ve.dragged=z,ce={target:z,clientX:(t||e).clientX,clientY:(t||e).clientY},pe=ce.clientX-s.left,me=ce.clientY-s.top,this._lastX=(t||e).clientX,this._lastY=(t||e).clientY,z.style["will-change"]="all",r=function(){Q("delayEnded",i,{evt:e}),Ve.eventCanceled?i._onDrop():(i._disableDelayedDragEvents(),!f&&i.nativeDraggable&&(z.draggable=!0),i._triggerDragStart(e,t),X({sortable:i,name:"choose",originalEvent:e}),C(z,a.chosenClass,!0))},a.ignore.split(",").forEach((function(e){x(z,e.trim(),Ge)})),g(l,"dragover",Le),g(l,"mousemove",Le),g(l,"touchmove",Le),g(l,"mouseup",i._onDrop),g(l,"touchend",i._onDrop),g(l,"touchcancel",i._onDrop),f&&this.nativeDraggable&&(this.options.touchStartThreshold=4,z.draggable=!0),Q("delayStart",this,{evt:e}),!a.delay||a.delayOnTouchOnly&&!t||this.nativeDraggable&&(d||c))r();else{if(Ve.eventCanceled)return void this._onDrop();g(l,"mouseup",i._disableDelayedDrag),g(l,"touchend",i._disableDelayedDrag),g(l,"touchcancel",i._disableDelayedDrag),g(l,"mousemove",i._delayedDragTouchMoveHandler),g(l,"touchmove",i._delayedDragTouchMoveHandler),a.supportPointer&&g(l,"pointermove",i._delayedDragTouchMoveHandler),i._dragStartTimer=setTimeout(r,a.delay)}}},_delayedDragTouchMoveHandler:function(e){var t=e.touches?e.touches[0]:e;Math.max(Math.abs(t.clientX-this._lastX),Math.abs(t.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},_disableDelayedDrag:function(){z&&Ge(z),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var e=this.el.ownerDocument;b(e,"mouseup",this._disableDelayedDrag),b(e,"touchend",this._disableDelayedDrag),b(e,"touchcancel",this._disableDelayedDrag),b(e,"mousemove",this._delayedDragTouchMoveHandler),b(e,"touchmove",this._delayedDragTouchMoveHandler),b(e,"pointermove",this._delayedDragTouchMoveHandler)},_triggerDragStart:function(e,t){t=t||"touch"==e.pointerType&&e,!this.nativeDraggable||t?this.options.supportPointer?g(document,"pointermove",this._onTouchMove):g(document,t?"touchmove":"mousemove",this._onTouchMove):(g(z,"dragend",this),g(Z,"dragstart",this._onDragStart));try{document.selection?He((function(){document.selection.empty()})):window.getSelection().removeAllRanges()}catch(e){}},_dragStarted:function(e,t){if(_e=!1,Z&&z){Q("dragStarted",this,{evt:t}),this.nativeDraggable&&g(document,"dragover",Be);var n=this.options;!e&&C(z,n.dragClass,!1),C(z,n.ghostClass,!0),Ve.active=this,e&&this._appendGhost(),X({sortable:this,name:"start",originalEvent:t})}else this._nulling()},_emulateDragOver:function(){if(de){this._lastX=de.clientX,this._lastY=de.clientY,ke();for(var e=document.elementFromPoint(de.clientX,de.clientY),t=e;e&&e.shadowRoot&&(e=e.shadowRoot.elementFromPoint(de.clientX,de.clientY))!==t;)t=e;if(z.parentNode[G]._isOutsideThisEl(e),t)do{if(t[G]){if(t[G]._onDragOver({clientX:de.clientX,clientY:de.clientY,target:e,rootEl:t})&&!this.options.dragoverBubble)break}e=t}while(t=t.parentNode);Re()}},_onTouchMove:function(e){if(ce){var t=this.options,n=t.fallbackTolerance,r=t.fallbackOffset,i=e.touches?e.touches[0]:e,o=J&&S(J),a=J&&o&&o.a,l=J&&o&&o.d,s=Fe&&Ee&&j(Ee),u=(i.clientX-ce.clientX+r.x)/(a||1)+(s?s[0]-Se[0]:0)/(a||1),c=(i.clientY-ce.clientY+r.y)/(l||1)+(s?s[1]-Se[1]:0)/(l||1);if(!Ve.active&&!_e){if(n&&Math.max(Math.abs(i.clientX-this._lastX),Math.abs(i.clientY-this._lastY))<n)return;this._onDragStart(e,!0)}if(J){o?(o.e+=u-(fe||0),o.f+=c-(he||0)):o={a:1,b:0,c:0,d:1,e:u,f:c};var d="matrix(".concat(o.a,",").concat(o.b,",").concat(o.c,",").concat(o.d,",").concat(o.e,",").concat(o.f,")");A(J,"webkitTransform",d),A(J,"mozTransform",d),A(J,"msTransform",d),A(J,"transform",d),fe=u,he=c,de=i}e.cancelable&&e.preventDefault()}},_appendGhost:function(){if(!J){var e=this.options.fallbackOnBody?document.body:Z,t=T(z,!0,Fe,!0,e),n=this.options;if(Fe){for(Ee=e;"static"===A(Ee,"position")&&"none"===A(Ee,"transform")&&Ee!==document;)Ee=Ee.parentNode;Ee!==document.body&&Ee!==document.documentElement?(Ee===document&&(Ee=I()),t.top+=Ee.scrollTop,t.left+=Ee.scrollLeft):Ee=I(),Se=j(Ee)}C(J=z.cloneNode(!0),n.ghostClass,!1),C(J,n.fallbackClass,!0),C(J,n.dragClass,!0),A(J,"transition",""),A(J,"transform",""),A(J,"box-sizing","border-box"),A(J,"margin",0),A(J,"top",t.top),A(J,"left",t.left),A(J,"width",t.width),A(J,"height",t.height),A(J,"opacity","0.8"),A(J,"position",Fe?"absolute":"fixed"),A(J,"zIndex","100000"),A(J,"pointerEvents","none"),Ve.ghost=J,e.appendChild(J),A(J,"transform-origin",pe/parseInt(J.style.width)*100+"% "+me/parseInt(J.style.height)*100+"%")}},_onDragStart:function(e,t){var n=this,r=e.dataTransfer,i=n.options;Q("dragStart",this,{evt:e}),Ve.eventCanceled?this._onDrop():(Q("setupClone",this),Ve.eventCanceled||((ne=B(z)).draggable=!1,ne.style["will-change"]="",this._hideClone(),C(ne,this.options.chosenClass,!1),Ve.clone=ne),n.cloneId=He((function(){Q("clone",n),Ve.eventCanceled||(n.options.removeCloneOnHide||Z.insertBefore(ne,z),n._hideClone(),X({sortable:n,name:"clone"}))})),!t&&C(z,i.dragClass,!0),t?(we=!0,n._loopId=setInterval(n._emulateDragOver,50)):(b(document,"mouseup",n._onDrop),b(document,"touchend",n._onDrop),b(document,"touchcancel",n._onDrop),r&&(r.effectAllowed="move",i.setData&&i.setData.call(n,r,z)),g(document,"drop",n),A(z,"transform","translateZ(0)")),_e=!0,n._dragStartId=He(n._dragStarted.bind(n,t,e)),g(document,"selectstart",n),ve=!0,h&&A(document.body,"user-select","none"))},_onDragOver:function(e){var t,n,r,i,o=this.el,l=e.target,s=this.options,u=s.group,c=Ve.active,d=se===u,f=s.sort,h=ue||c,p=this,m=!1;if(!xe){if(void 0!==e.preventDefault&&e.cancelable&&e.preventDefault(),l=_(l,s.draggable,o,!0),k("dragOver"),Ve.eventCanceled)return m;if(z.contains(e.target)||l.animated&&l.animatingX&&l.animatingY||p._ignoreWhileAnimating===l)return B(!1);if(we=!1,c&&!s.disabled&&(d?f||(r=!Z.contains(z)):ue===this||(this.lastPutMode=se.checkPull(this,c,z,e))&&u.checkPut(this,c,z,e))){if(i="vertical"===this._getDirection(e,l),t=T(z),k("dragOverValid"),Ve.eventCanceled)return m;if(r)return K=Z,R(),this._hideClone(),k("revert"),Ve.eventCanceled||(ee?Z.insertBefore(z,ee):Z.appendChild(z)),B(!0);var v=N(o,s.draggable);if(!v||function(e,t,n){var r=T(N(n.el,n.options.draggable));return t?e.clientX>r.right+10||e.clientX<=r.right&&e.clientY>r.bottom&&e.clientX>=r.left:e.clientX>r.right&&e.clientY>r.top||e.clientX<=r.right&&e.clientY>r.bottom+10}(e,i,this)&&!v.animated){if(v===z)return B(!1);if(v&&o===e.target&&(l=v),l&&(n=T(l)),!1!==qe(Z,o,z,t,l,n,e,!!l))return R(),o.appendChild(z),K=o,V(),B(!0)}else if(l.parentNode===o){n=T(l);var g,b,y,E=z.parentNode!==o,w=!function(e,t,n){var r=n?e.left:e.top,i=n?e.right:e.bottom,o=n?e.width:e.height,a=n?t.left:t.top,l=n?t.right:t.bottom,s=n?t.width:t.height;return r===a||i===l||r+o/2===a+s/2}(z.animated&&z.toRect||t,l.animated&&l.toRect||n,i),O=i?"top":"left",S=F(l,"top","top")||F(z,"top","top"),x=S?S.scrollTop:void 0;if(ge!==l&&(b=n[O],Ce=!1,Ae=!w&&s.invertSwap||E),0!==(g=function(e,t,n,r,i,o,a,l){var s=r?e.clientY:e.clientX,u=r?n.height:n.width,c=r?n.top:n.left,d=r?n.bottom:n.right,f=!1;if(!a)if(l&&ye<u*i){if(!Ce&&(1===be?s>c+u*o/2:s<d-u*o/2)&&(Ce=!0),Ce)f=!0;else if(1===be?s<c+ye:s>d-ye)return-be}else if(s>c+u*(1-i)/2&&s<d-u*(1-i)/2)return function(e){return D(z)<D(e)?1:-1}(t);if((f=f||a)&&(s<c+u*o/2||s>d-u*o/2))return s>c+u/2?1:-1;return 0}(e,l,n,i,w?1:s.swapThreshold,null==s.invertedSwapThreshold?s.swapThreshold:s.invertedSwapThreshold,Ae,ge===l))){var I=D(z);do{I-=g,y=K.children[I]}while(y&&("none"===A(y,"display")||y===J))}if(0===g||y===l)return B(!1);ge=l,be=g;var M=l.nextElementSibling,j=!1,P=qe(Z,o,z,t,l,n,e,j=1===g);if(!1!==P)return 1!==P&&-1!==P||(j=1===P),xe=!0,setTimeout(We,30),R(),j&&!M?o.appendChild(z):l.parentNode.insertBefore(z,j?M:l),S&&L(S,0,x-S.scrollTop),K=z.parentNode,void 0===b||Ae||(ye=Math.abs(b-T(l)[O])),V(),B(!0)}if(o.contains(z))return B(!1)}return!1}function k(s,u){Q(s,p,a({evt:e,isOwner:d,axis:i?"vertical":"horizontal",revert:r,dragRect:t,targetRect:n,canSort:f,fromSortable:h,target:l,completed:B,onMove:function(n,r){return qe(Z,o,z,t,n,T(n),e,r)},changed:V},u))}function R(){k("dragOverAnimationCapture"),p.captureAnimationState(),p!==h&&h.captureAnimationState()}function B(t){return k("dragOverCompleted",{insertion:t}),t&&(d?c._hideClone():c._showClone(p),p!==h&&(C(z,ue?ue.options.ghostClass:c.options.ghostClass,!1),C(z,s.ghostClass,!0)),ue!==p&&p!==Ve.active?ue=p:p===Ve.active&&ue&&(ue=null),h===p&&(p._ignoreWhileAnimating=l),p.animateAll((function(){k("dragOverAnimationComplete"),p._ignoreWhileAnimating=null})),p!==h&&(h.animateAll(),h._ignoreWhileAnimating=null)),(l===z&&!z.animated||l===o&&!l.animated)&&(ge=null),s.dragoverBubble||e.rootEl||l===document||(z.parentNode[G]._isOutsideThisEl(e.target),!t&&Le(e)),!s.dragoverBubble&&e.stopPropagation&&e.stopPropagation(),m=!0}function V(){oe=D(z),le=D(z,s.draggable),X({sortable:p,name:"change",toEl:o,newIndex:oe,newDraggableIndex:le,originalEvent:e})}},_ignoreWhileAnimating:null,_offMoveEvents:function(){b(document,"mousemove",this._onTouchMove),b(document,"touchmove",this._onTouchMove),b(document,"pointermove",this._onTouchMove),b(document,"dragover",Le),b(document,"mousemove",Le),b(document,"touchmove",Le)},_offUpEvents:function(){var e=this.el.ownerDocument;b(e,"mouseup",this._onDrop),b(e,"touchend",this._onDrop),b(e,"pointerup",this._onDrop),b(e,"touchcancel",this._onDrop),b(document,"selectstart",this)},_onDrop:function(e){var t=this.el,n=this.options;oe=D(z),le=D(z,n.draggable),Q("drop",this,{evt:e}),K=z&&z.parentNode,oe=D(z),le=D(z,n.draggable),Ve.eventCanceled?this._nulling():(_e=!1,Ae=!1,Ce=!1,clearInterval(this._loopId),clearTimeout(this._dragStartTimer),Ue(this.cloneId),Ue(this._dragStartId),this.nativeDraggable&&(b(document,"drop",this),b(t,"dragstart",this._onDragStart)),this._offMoveEvents(),this._offUpEvents(),h&&A(document.body,"user-select",""),e&&(ve&&(e.cancelable&&e.preventDefault(),!n.dropBubble&&e.stopPropagation()),J&&J.parentNode&&J.parentNode.removeChild(J),(Z===K||ue&&"clone"!==ue.lastPutMode)&&ne&&ne.parentNode&&ne.parentNode.removeChild(ne),z&&(this.nativeDraggable&&b(z,"dragend",this),Ge(z),z.style["will-change"]="",ve&&!_e&&C(z,ue?ue.options.ghostClass:this.options.ghostClass,!1),C(z,this.options.chosenClass,!1),X({sortable:this,name:"unchoose",toEl:K,newIndex:null,newDraggableIndex:null,originalEvent:e}),Z!==K?(oe>=0&&(X({rootEl:K,name:"add",toEl:K,fromEl:Z,originalEvent:e}),X({sortable:this,name:"remove",toEl:K,originalEvent:e}),X({rootEl:K,name:"sort",toEl:K,fromEl:Z,originalEvent:e}),X({sortable:this,name:"sort",toEl:K,originalEvent:e})),ue&&ue.save()):oe!==ie&&oe>=0&&(X({sortable:this,name:"update",toEl:K,originalEvent:e}),X({sortable:this,name:"sort",toEl:K,originalEvent:e})),Ve.active&&(null!=oe&&-1!==oe||(oe=ie,le=ae),X({sortable:this,name:"end",toEl:K,originalEvent:e}),this.save()))),this._nulling())},_nulling:function(){Q("nulling",this),Z=z=K=J=ee=ne=te=re=ce=de=ve=oe=le=ie=ae=ge=be=ue=se=Ve.dragged=Ve.ghost=Ve.clone=Ve.active=null,Ie.forEach((function(e){e.checked=!0})),Ie.length=fe=he=0},handleEvent:function(e){switch(e.type){case"drop":case"dragend":this._onDrop(e);break;case"dragenter":case"dragover":z&&(this._onDragOver(e),function(e){e.dataTransfer&&(e.dataTransfer.dropEffect="move");e.cancelable&&e.preventDefault()}(e));break;case"selectstart":e.preventDefault()}},toArray:function(){for(var e,t=[],n=this.el.children,r=0,i=n.length,o=this.options;r<i;r++)_(e=n[r],o.draggable,this.el,!1)&&t.push(e.getAttribute(o.dataIdAttr)||$e(e));return t},sort:function(e){var t={},n=this.el;this.toArray().forEach((function(e,r){var i=n.children[r];_(i,this.options.draggable,n,!1)&&(t[e]=i)}),this),e.forEach((function(e){t[e]&&(n.removeChild(t[e]),n.appendChild(t[e]))}))},save:function(){var e=this.options.store;e&&e.set&&e.set(this)},closest:function(e,t){return _(e,t||this.options.draggable,this.el,!1)},option:function(e,t){var n=this.options;if(void 0===t)return n[e];var r=U.modifyOption(this,e,t);n[e]=void 0!==r?r:t,"group"===e&&Pe(n)},destroy:function(){Q("destroy",this);var e=this.el;e[G]=null,b(e,"mousedown",this._onTapStart),b(e,"touchstart",this._onTapStart),b(e,"pointerdown",this._onTapStart),this.nativeDraggable&&(b(e,"dragover",this),b(e,"dragenter",this)),Array.prototype.forEach.call(e.querySelectorAll("[draggable]"),(function(e){e.removeAttribute("draggable")})),this._onDrop(),Oe.splice(Oe.indexOf(this.el),1),this.el=e=null},_hideClone:function(){if(!re){if(Q("hideClone",this),Ve.eventCanceled)return;A(ne,"display","none"),this.options.removeCloneOnHide&&ne.parentNode&&ne.parentNode.removeChild(ne),re=!0}},_showClone:function(e){if("clone"===e.lastPutMode){if(re){if(Q("showClone",this),Ve.eventCanceled)return;Z.contains(z)&&!this.options.group.revertClone?Z.insertBefore(ne,z):ee?Z.insertBefore(ne,ee):Z.appendChild(ne),this.options.group.revertClone&&this.animate(z,ne),A(ne,"display",""),re=!1}}else this._hideClone()}},Te&&g(document,"touchmove",(function(e){(Ve.active||_e)&&e.cancelable&&e.preventDefault()})),Ve.utils={on:g,off:b,css:A,find:x,is:function(e,t){return!!_(e,t,e,!1)},extend:function(e,t){if(e&&t)for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e},throttle:R,closest:_,toggleClass:C,clone:B,index:D,nextTick:He,cancelNextTick:Ue,detectDirection:je,getChild:M},Ve.get=function(e){return e[G]},Ve.mount=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];t[0].constructor===Array&&(t=t[0]),t.forEach((function(e){if(!e.prototype||!e.prototype.constructor)throw"Sortable: Mounted plugin must be a constructor function, not ".concat({}.toString.call(e));e.utils&&(Ve.utils=a({},Ve.utils,e.utils)),U.mount(e)}))},Ve.create=function(e,t){return new Ve(e,t)},Ve.version="1.10.1";var Ye,Qe,Xe,ze,Ke,Je,Ze=[],et=!1;function tt(){Ze.forEach((function(e){clearInterval(e.pid)})),Ze=[]}function nt(){clearInterval(Je)}var rt,it=R((function(e,t,n,r){if(t.scroll){var i,o=(e.touches?e.touches[0]:e).clientX,a=(e.touches?e.touches[0]:e).clientY,l=t.scrollSensitivity,s=t.scrollSpeed,u=I(),c=!1;Qe!==n&&(Qe=n,tt(),Ye=t.scroll,i=t.scrollFn,!0===Ye&&(Ye=P(n,!0)));var d=0,f=Ye;do{var h=f,p=T(h),m=p.top,v=p.bottom,g=p.left,b=p.right,y=p.width,E=p.height,_=void 0,w=void 0,O=h.scrollWidth,C=h.scrollHeight,S=A(h),x=h.scrollLeft,F=h.scrollTop;h===u?(_=y<O&&("auto"===S.overflowX||"scroll"===S.overflowX||"visible"===S.overflowX),w=E<C&&("auto"===S.overflowY||"scroll"===S.overflowY||"visible"===S.overflowY)):(_=y<O&&("auto"===S.overflowX||"scroll"===S.overflowX),w=E<C&&("auto"===S.overflowY||"scroll"===S.overflowY));var M=_&&(Math.abs(b-o)<=l&&x+y<O)-(Math.abs(g-o)<=l&&!!x),N=w&&(Math.abs(v-a)<=l&&F+E<C)-(Math.abs(m-a)<=l&&!!F);if(!Ze[d])for(var D=0;D<=d;D++)Ze[D]||(Ze[D]={});Ze[d].vx==M&&Ze[d].vy==N&&Ze[d].el===h||(Ze[d].el=h,Ze[d].vx=M,Ze[d].vy=N,clearInterval(Ze[d].pid),0==M&&0==N||(c=!0,Ze[d].pid=setInterval(function(){r&&0===this.layer&&Ve.active._onTouchMove(Ke);var t=Ze[this.layer].vy?Ze[this.layer].vy*s:0,n=Ze[this.layer].vx?Ze[this.layer].vx*s:0;"function"==typeof i&&"continue"!==i.call(Ve.dragged.parentNode[G],n,t,e,Ke,Ze[this.layer].el)||L(Ze[this.layer].el,n,t)}.bind({layer:d}),24))),d++}while(t.bubbleScroll&&f!==u&&(f=P(f,!1)));et=c}}),30),ot=function(e){var t=e.originalEvent,n=e.putSortable,r=e.dragEl,i=e.activeSortable,o=e.dispatchSortableEvent,a=e.hideGhostForTarget,l=e.unhideGhostForTarget;if(t){var s=n||i;a();var u=t.changedTouches&&t.changedTouches.length?t.changedTouches[0]:t,c=document.elementFromPoint(u.clientX,u.clientY);l(),s&&!s.el.contains(c)&&(o("spill"),this.onSpill({dragEl:r,putSortable:n}))}};function at(){}function lt(){}function st(){function e(){this.defaults={swapClass:"sortable-swap-highlight"}}return e.prototype={dragStart:function(e){var t=e.dragEl;rt=t},dragOverValid:function(e){var t=e.completed,n=e.target,r=e.onMove,i=e.activeSortable,o=e.changed,a=e.cancel;if(i.options.swap){var l=this.sortable.el,s=this.options;if(n&&n!==l){var u=rt;!1!==r(n)?(C(n,s.swapClass,!0),rt=n):rt=null,u&&u!==rt&&C(u,s.swapClass,!1)}o(),t(!0),a()}},drop:function(e){var t=e.activeSortable,n=e.putSortable,r=e.dragEl,i=n||this.sortable,o=this.options;rt&&C(rt,o.swapClass,!1),rt&&(o.swap||n&&n.options.swap)&&r!==rt&&(i.captureAnimationState(),i!==t&&t.captureAnimationState(),function(e,t){var n,r,i=e.parentNode,o=t.parentNode;if(!i||!o||i.isEqualNode(t)||o.isEqualNode(e))return;n=D(e),r=D(t),i.isEqualNode(o)&&n<r&&r++;i.insertBefore(t,i.children[n]),o.insertBefore(e,o.children[r])}(r,rt),i.animateAll(),i!==t&&t.animateAll())},nulling:function(){rt=null}},o(e,{pluginName:"swap",eventProperties:function(){return{swapItem:rt}}})}at.prototype={startIndex:null,dragStart:function(e){var t=e.oldDraggableIndex;this.startIndex=t},onSpill:function(e){var t=e.dragEl,n=e.putSortable;this.sortable.captureAnimationState(),n&&n.captureAnimationState();var r=M(this.sortable.el,this.startIndex,this.options);r?this.sortable.el.insertBefore(t,r):this.sortable.el.appendChild(t),this.sortable.animateAll(),n&&n.animateAll()},drop:ot},o(at,{pluginName:"revertOnSpill"}),lt.prototype={onSpill:function(e){var t=e.dragEl,n=e.putSortable||this.sortable;n.captureAnimationState(),t.parentNode&&t.parentNode.removeChild(t),n.animateAll()},drop:ot},o(lt,{pluginName:"removeOnSpill"});var ut,ct,dt,ft,ht,pt=[],mt=[],vt=!1,gt=!1,bt=!1;function yt(){function e(e){for(var t in this)"_"===t.charAt(0)&&"function"==typeof this[t]&&(this[t]=this[t].bind(this));e.options.supportPointer?g(document,"pointerup",this._deselectMultiDrag):(g(document,"mouseup",this._deselectMultiDrag),g(document,"touchend",this._deselectMultiDrag)),g(document,"keydown",this._checkKeyDown),g(document,"keyup",this._checkKeyUp),this.defaults={selectedClass:"sortable-selected",multiDragKey:null,setData:function(t,n){var r="";pt.length&&ct===e?pt.forEach((function(e,t){r+=(t?", ":"")+e.textContent})):r=n.textContent,t.setData("Text",r)}}}return e.prototype={multiDragKeyDown:!1,isMultiDrag:!1,delayStartGlobal:function(e){var t=e.dragEl;dt=t},delayEnded:function(){this.isMultiDrag=~pt.indexOf(dt)},setupClone:function(e){var t=e.sortable,n=e.cancel;if(this.isMultiDrag){for(var r=0;r<pt.length;r++)mt.push(B(pt[r])),mt[r].sortableIndex=pt[r].sortableIndex,mt[r].draggable=!1,mt[r].style["will-change"]="",C(mt[r],this.options.selectedClass,!1),pt[r]===dt&&C(mt[r],this.options.chosenClass,!1);t._hideClone(),n()}},clone:function(e){var t=e.sortable,n=e.rootEl,r=e.dispatchSortableEvent,i=e.cancel;this.isMultiDrag&&(this.options.removeCloneOnHide||pt.length&&ct===t&&(Et(!0,n),r("clone"),i()))},showClone:function(e){var t=e.cloneNowShown,n=e.rootEl,r=e.cancel;this.isMultiDrag&&(Et(!1,n),mt.forEach((function(e){A(e,"display","")})),t(),ht=!1,r())},hideClone:function(e){var t=this,n=(e.sortable,e.cloneNowHidden),r=e.cancel;this.isMultiDrag&&(mt.forEach((function(e){A(e,"display","none"),t.options.removeCloneOnHide&&e.parentNode&&e.parentNode.removeChild(e)})),n(),ht=!0,r())},dragStartGlobal:function(e){e.sortable;!this.isMultiDrag&&ct&&ct.multiDrag._deselectMultiDrag(),pt.forEach((function(e){e.sortableIndex=D(e)})),pt=pt.sort((function(e,t){return e.sortableIndex-t.sortableIndex})),bt=!0},dragStarted:function(e){var t=this,n=e.sortable;if(this.isMultiDrag){if(this.options.sort&&(n.captureAnimationState(),this.options.animation)){pt.forEach((function(e){e!==dt&&A(e,"position","absolute")}));var r=T(dt,!1,!0,!0);pt.forEach((function(e){e!==dt&&V(e,r)})),gt=!0,vt=!0}n.animateAll((function(){gt=!1,vt=!1,t.options.animation&&pt.forEach((function(e){q(e)})),t.options.sort&&_t()}))}},dragOver:function(e){var t=e.target,n=e.completed,r=e.cancel;gt&&~pt.indexOf(t)&&(n(!1),r())},revert:function(e){var t=e.fromSortable,n=e.rootEl,r=e.sortable,i=e.dragRect;pt.length>1&&(pt.forEach((function(e){r.addAnimationState({target:e,rect:gt?T(e):i}),q(e),e.fromRect=i,t.removeAnimationState(e)})),gt=!1,function(e,t){pt.forEach((function(n,r){var i=t.children[n.sortableIndex+(e?Number(r):0)];i?t.insertBefore(n,i):t.appendChild(n)}))}(!this.options.removeCloneOnHide,n))},dragOverCompleted:function(e){var t=e.sortable,n=e.isOwner,r=e.insertion,i=e.activeSortable,o=e.parentEl,a=e.putSortable,l=this.options;if(r){if(n&&i._hideClone(),vt=!1,l.animation&&pt.length>1&&(gt||!n&&!i.options.sort&&!a)){var s=T(dt,!1,!0,!0);pt.forEach((function(e){e!==dt&&(V(e,s),o.appendChild(e))})),gt=!0}if(!n)if(gt||_t(),pt.length>1){var u=ht;i._showClone(t),i.options.animation&&!ht&&u&&mt.forEach((function(e){i.addAnimationState({target:e,rect:ft}),e.fromRect=ft,e.thisAnimationDuration=null}))}else i._showClone(t)}},dragOverAnimationCapture:function(e){var t=e.dragRect,n=e.isOwner,r=e.activeSortable;if(pt.forEach((function(e){e.thisAnimationDuration=null})),r.options.animation&&!n&&r.multiDrag.isMultiDrag){ft=o({},t);var i=S(dt,!0);ft.top-=i.f,ft.left-=i.e}},dragOverAnimationComplete:function(){gt&&(gt=!1,_t())},drop:function(e){var t=e.originalEvent,n=e.rootEl,r=e.parentEl,i=e.sortable,o=e.dispatchSortableEvent,a=e.oldIndex,l=e.putSortable,s=l||this.sortable;if(t){var u=this.options,c=r.children;if(!bt)if(u.multiDragKey&&!this.multiDragKeyDown&&this._deselectMultiDrag(),C(dt,u.selectedClass,!~pt.indexOf(dt)),~pt.indexOf(dt))pt.splice(pt.indexOf(dt),1),ut=null,Y({sortable:i,rootEl:n,name:"deselect",targetEl:dt,originalEvt:t});else{if(pt.push(dt),Y({sortable:i,rootEl:n,name:"select",targetEl:dt,originalEvt:t}),t.shiftKey&&ut&&i.el.contains(ut)){var d,f,h=D(ut),p=D(dt);if(~h&&~p&&h!==p)for(p>h?(f=h,d=p):(f=p,d=h+1);f<d;f++)~pt.indexOf(c[f])||(C(c[f],u.selectedClass,!0),pt.push(c[f]),Y({sortable:i,rootEl:n,name:"select",targetEl:c[f],originalEvt:t}))}else ut=dt;ct=s}if(bt&&this.isMultiDrag){if((r[G].options.sort||r!==n)&&pt.length>1){var m=T(dt),v=D(dt,":not(."+this.options.selectedClass+")");if(!vt&&u.animation&&(dt.thisAnimationDuration=null),s.captureAnimationState(),!vt&&(u.animation&&(dt.fromRect=m,pt.forEach((function(e){if(e.thisAnimationDuration=null,e!==dt){var t=gt?T(e):m;e.fromRect=t,s.addAnimationState({target:e,rect:t})}}))),_t(),pt.forEach((function(e){c[v]?r.insertBefore(e,c[v]):r.appendChild(e),v++})),a===D(dt))){var g=!1;pt.forEach((function(e){e.sortableIndex===D(e)||(g=!0)})),g&&o("update")}pt.forEach((function(e){q(e)})),s.animateAll()}ct=s}(n===r||l&&"clone"!==l.lastPutMode)&&mt.forEach((function(e){e.parentNode&&e.parentNode.removeChild(e)}))}},nullingGlobal:function(){this.isMultiDrag=bt=!1,mt.length=0},destroyGlobal:function(){this._deselectMultiDrag(),b(document,"pointerup",this._deselectMultiDrag),b(document,"mouseup",this._deselectMultiDrag),b(document,"touchend",this._deselectMultiDrag),b(document,"keydown",this._checkKeyDown),b(document,"keyup",this._checkKeyUp)},_deselectMultiDrag:function(e){if(!bt&&ct===this.sortable&&!(e&&_(e.target,this.options.draggable,this.sortable.el,!1)||e&&0!==e.button))for(;pt.length;){var t=pt[0];C(t,this.options.selectedClass,!1),pt.shift(),Y({sortable:this.sortable,rootEl:this.sortable.el,name:"deselect",targetEl:t,originalEvt:e})}},_checkKeyDown:function(e){e.key===this.options.multiDragKey&&(this.multiDragKeyDown=!0)},_checkKeyUp:function(e){e.key===this.options.multiDragKey&&(this.multiDragKeyDown=!1)}},o(e,{pluginName:"multiDrag",utils:{select:function(e){var t=e.parentNode[G];t&&t.options.multiDrag&&!~pt.indexOf(e)&&(ct&&ct!==t&&(ct.multiDrag._deselectMultiDrag(),ct=t),C(e,t.options.selectedClass,!0),pt.push(e))},deselect:function(e){var t=e.parentNode[G],n=pt.indexOf(e);t&&t.options.multiDrag&&~n&&(C(e,t.options.selectedClass,!1),pt.splice(n,1))}},eventProperties:function(){var e=this,t=[],n=[];return pt.forEach((function(r){var i;t.push({multiDragElement:r,index:r.sortableIndex}),i=gt&&r!==dt?-1:gt?D(r,":not(."+e.options.selectedClass+")"):D(r),n.push({multiDragElement:r,index:i})})),{items:s(pt),clones:[].concat(mt),oldIndicies:t,newIndicies:n}},optionListeners:{multiDragKey:function(e){return"ctrl"===(e=e.toLowerCase())?e="Control":e.length>1&&(e=e.charAt(0).toUpperCase()+e.substr(1)),e}}})}function Et(e,t){mt.forEach((function(n,r){var i=t.children[n.sortableIndex+(e?Number(r):0)];i?t.insertBefore(n,i):t.appendChild(n)}))}function _t(){pt.forEach((function(e){e!==dt&&e.parentNode&&e.parentNode.removeChild(e)}))}Ve.mount(new function(){function e(){for(var e in this.defaults={scroll:!0,scrollSensitivity:30,scrollSpeed:10,bubbleScroll:!0},this)"_"===e.charAt(0)&&"function"==typeof this[e]&&(this[e]=this[e].bind(this))}return e.prototype={dragStarted:function(e){var t=e.originalEvent;this.sortable.nativeDraggable?g(document,"dragover",this._handleAutoScroll):this.options.supportPointer?g(document,"pointermove",this._handleFallbackAutoScroll):t.touches?g(document,"touchmove",this._handleFallbackAutoScroll):g(document,"mousemove",this._handleFallbackAutoScroll)},dragOverCompleted:function(e){var t=e.originalEvent;this.options.dragOverBubble||t.rootEl||this._handleAutoScroll(t)},drop:function(){this.sortable.nativeDraggable?b(document,"dragover",this._handleAutoScroll):(b(document,"pointermove",this._handleFallbackAutoScroll),b(document,"touchmove",this._handleFallbackAutoScroll),b(document,"mousemove",this._handleFallbackAutoScroll)),nt(),tt(),clearTimeout(w),w=void 0},nulling:function(){Ke=Qe=Ye=et=Je=Xe=ze=null,Ze.length=0},_handleFallbackAutoScroll:function(e){this._handleAutoScroll(e,!0)},_handleAutoScroll:function(e,t){var n=this,r=(e.touches?e.touches[0]:e).clientX,i=(e.touches?e.touches[0]:e).clientY,o=document.elementFromPoint(r,i);if(Ke=e,t||d||c||h){it(e,this.options,o,t);var a=P(o,!0);!et||Je&&r===Xe&&i===ze||(Je&&nt(),Je=setInterval((function(){var o=P(document.elementFromPoint(r,i),!0);o!==a&&(a=o,tt()),it(e,n.options,o,t)}),10),Xe=r,ze=i)}else{if(!this.options.bubbleScroll||P(o,!0)===I())return void tt();it(e,this.options,P(o,!1),!1)}}},o(e,{pluginName:"scroll",initializeByDefault:!0})}),Ve.mount(lt,at),t.default=Ve}])}));
// /* // * // * ListExecution actions - NOT USED // * // */ // import * as c from './constants'; // // export function defaultAction() { // return { // type: c.DEFAULT_ACTION, // }; // } // // export function listExecutionAction(payload) { // return { // type: c.LIST_EXECUTION_ACTION, // payload // }; // } // // export function listedExecutionAction(payload) { // return { // type: c.LISTED_EXECUTION_ACTION, // payload // }; // } //
import { Rock } from "./rock.js"; import CopperOre from "../../../items/ores/copper-ore.js"; export class CopperRock extends Rock { examineText = "A copper rock."; constructor(scene) { super({ scene: scene, name: "Copper Rock", varName: "copperRock", images: [ { name: "copper-rock", path: "src/assets/sprites/CopperRock.png", scale: 1, }, ], neededClicks: 5, drops: [{ item: CopperOre, rate: 1 }], offsetY: 150, requiredLevels: { mining: 1, }, }); } }
var group__z_half_edge_data_structures = [ [ "ZMeshClasses", "group__z_mesh_classes.html", "group__z_mesh_classes" ] ];
import { primaryColor, warningColor, dangerColor, successColor, infoColor, roseColor } from "../../material/ui-kit"; const badgeStyle = { badge: { marginRight: "3px", borderRadius: "12px", padding: "5px 12px", textTransform: "uppercase", fontSize: "10px", fontWeight: "500", lineHeight: "1", color: "#fff", textAlign: "center", whiteSpace: "nowrap", verticalAlign: "baseline", display: "inline-block" }, primary: { backgroundColor: primaryColor }, warning: { backgroundColor: warningColor }, danger: { backgroundColor: dangerColor }, success: { backgroundColor: successColor }, info: { backgroundColor: infoColor }, rose: { backgroundColor: roseColor }, gray: { backgroundColor: "#6c757d" } }; export default badgeStyle;
(window.webpackJsonp=window.webpackJsonp||[]).push([[131],{742:function(s,n,a){"use strict";a.r(n);var t=a(5),r=Object(t.a)({},(function(){var s=this,n=s.$createElement,a=s._self._c||n;return a("ContentSlotsDistributor",{attrs:{"slot-key":s.$parent.slotKey}},[a("h1",{attrs:{id:"param-batch-job"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#param-batch-job"}},[s._v("#")]),s._v(" param-batch-job")]),s._v(" "),a("ul",[a("li",[s._v("parameter를 받아와서 해당 값을 이용하여 다음으로 실행될 job의 값을 다이나믹하게 넣어 만드는 샘플\n"),a("ul",[a("li",[s._v('meta_required에 원하는 값을 넣고 template에 env "NOMAD_META_메타명(key)"와 같이 넣어주면 된다.')])])])]),s._v(" "),a("div",{staticClass:"language-hcl line-numbers-mode"},[a("pre",{pre:!0,attrs:{class:"language-hcl"}},[a("code",[s._v("job "),a("span",{pre:!0,attrs:{class:"token string"}},[s._v('"24-paramete"')]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("{")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[s._v("datacenters")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("=")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("[")]),a("span",{pre:!0,attrs:{class:"token string"}},[s._v('"dc1"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("]")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[s._v("type")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("=")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[s._v('"batch"')]),s._v("\n\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[s._v("parameterized")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("{")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[s._v("payload")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("=")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[s._v('"forbidden"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[s._v("meta_required")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("=")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("[")]),a("span",{pre:!0,attrs:{class:"token string"}},[s._v('"room_num"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("]")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("}")]),s._v("\n\n group "),a("span",{pre:!0,attrs:{class:"token string"}},[s._v('"run-main-job"')]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("{")]),s._v("\n\n task "),a("span",{pre:!0,attrs:{class:"token string"}},[s._v('"run-main-job"')]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("{")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[s._v("driver")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("=")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[s._v('"raw_exec"')]),s._v("\n\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[s._v("config")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("{")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[s._v("command")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("=")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[s._v('"nomad"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[s._v("# arguments")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[s._v("args")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("=")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("[")]),a("span",{pre:!0,attrs:{class:"token string"}},[s._v('"job"')]),s._v(", "),a("span",{pre:!0,attrs:{class:"token string"}},[s._v('"run"')]),s._v(", "),a("span",{pre:!0,attrs:{class:"token string"}},[s._v('"'),a("span",{pre:!0,attrs:{class:"token interpolation"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("$")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("{")]),s._v("NOMAD_TASK_DIR"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("}")])]),s._v('/room.job"')]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("]")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("}")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[s._v("template")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("{")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[s._v("data")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("=")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token heredoc string"}},[s._v('<<EOH\n\n#####################\n\njob "{{ env "NOMAD_META_room_num" }}" {\n datacenters = ["dc1"]\n\n group "jboss" {\n\n network {\n port "http" {\n to = "8080"\n }\n }\n service {\n port = "http"\n name = "{{ env "NOMAD_META_room_num" }}"\n check {\n type = "tcp"\n interval = "10s"\n timeout = "2s"\n }\n }\n task "http" {\n driver = "docker"\n config {\n image = "jboss/wildfly"\n ports = ["http"]\n }\n resources {\n cpu = 500\n memory = 282\n }\n }\n }\n}\n\nEOH')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[s._v("destination")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("=")]),s._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[s._v('"local/room.job"')]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("}")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("}")]),s._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("}")]),s._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[s._v("}")]),s._v("\n")])]),s._v(" "),a("div",{staticClass:"line-numbers-wrapper"},[a("span",{staticClass:"line-number"},[s._v("1")]),a("br"),a("span",{staticClass:"line-number"},[s._v("2")]),a("br"),a("span",{staticClass:"line-number"},[s._v("3")]),a("br"),a("span",{staticClass:"line-number"},[s._v("4")]),a("br"),a("span",{staticClass:"line-number"},[s._v("5")]),a("br"),a("span",{staticClass:"line-number"},[s._v("6")]),a("br"),a("span",{staticClass:"line-number"},[s._v("7")]),a("br"),a("span",{staticClass:"line-number"},[s._v("8")]),a("br"),a("span",{staticClass:"line-number"},[s._v("9")]),a("br"),a("span",{staticClass:"line-number"},[s._v("10")]),a("br"),a("span",{staticClass:"line-number"},[s._v("11")]),a("br"),a("span",{staticClass:"line-number"},[s._v("12")]),a("br"),a("span",{staticClass:"line-number"},[s._v("13")]),a("br"),a("span",{staticClass:"line-number"},[s._v("14")]),a("br"),a("span",{staticClass:"line-number"},[s._v("15")]),a("br"),a("span",{staticClass:"line-number"},[s._v("16")]),a("br"),a("span",{staticClass:"line-number"},[s._v("17")]),a("br"),a("span",{staticClass:"line-number"},[s._v("18")]),a("br"),a("span",{staticClass:"line-number"},[s._v("19")]),a("br"),a("span",{staticClass:"line-number"},[s._v("20")]),a("br"),a("span",{staticClass:"line-number"},[s._v("21")]),a("br"),a("span",{staticClass:"line-number"},[s._v("22")]),a("br"),a("span",{staticClass:"line-number"},[s._v("23")]),a("br"),a("span",{staticClass:"line-number"},[s._v("24")]),a("br"),a("span",{staticClass:"line-number"},[s._v("25")]),a("br"),a("span",{staticClass:"line-number"},[s._v("26")]),a("br"),a("span",{staticClass:"line-number"},[s._v("27")]),a("br"),a("span",{staticClass:"line-number"},[s._v("28")]),a("br"),a("span",{staticClass:"line-number"},[s._v("29")]),a("br"),a("span",{staticClass:"line-number"},[s._v("30")]),a("br"),a("span",{staticClass:"line-number"},[s._v("31")]),a("br"),a("span",{staticClass:"line-number"},[s._v("32")]),a("br"),a("span",{staticClass:"line-number"},[s._v("33")]),a("br"),a("span",{staticClass:"line-number"},[s._v("34")]),a("br"),a("span",{staticClass:"line-number"},[s._v("35")]),a("br"),a("span",{staticClass:"line-number"},[s._v("36")]),a("br"),a("span",{staticClass:"line-number"},[s._v("37")]),a("br"),a("span",{staticClass:"line-number"},[s._v("38")]),a("br"),a("span",{staticClass:"line-number"},[s._v("39")]),a("br"),a("span",{staticClass:"line-number"},[s._v("40")]),a("br"),a("span",{staticClass:"line-number"},[s._v("41")]),a("br"),a("span",{staticClass:"line-number"},[s._v("42")]),a("br"),a("span",{staticClass:"line-number"},[s._v("43")]),a("br"),a("span",{staticClass:"line-number"},[s._v("44")]),a("br"),a("span",{staticClass:"line-number"},[s._v("45")]),a("br"),a("span",{staticClass:"line-number"},[s._v("46")]),a("br"),a("span",{staticClass:"line-number"},[s._v("47")]),a("br"),a("span",{staticClass:"line-number"},[s._v("48")]),a("br"),a("span",{staticClass:"line-number"},[s._v("49")]),a("br"),a("span",{staticClass:"line-number"},[s._v("50")]),a("br"),a("span",{staticClass:"line-number"},[s._v("51")]),a("br"),a("span",{staticClass:"line-number"},[s._v("52")]),a("br"),a("span",{staticClass:"line-number"},[s._v("53")]),a("br"),a("span",{staticClass:"line-number"},[s._v("54")]),a("br"),a("span",{staticClass:"line-number"},[s._v("55")]),a("br"),a("span",{staticClass:"line-number"},[s._v("56")]),a("br"),a("span",{staticClass:"line-number"},[s._v("57")]),a("br"),a("span",{staticClass:"line-number"},[s._v("58")]),a("br"),a("span",{staticClass:"line-number"},[s._v("59")]),a("br"),a("span",{staticClass:"line-number"},[s._v("60")]),a("br"),a("span",{staticClass:"line-number"},[s._v("61")]),a("br"),a("span",{staticClass:"line-number"},[s._v("62")]),a("br"),a("span",{staticClass:"line-number"},[s._v("63")]),a("br")])])])}),[],!1,null,null,null);n.default=r.exports}}]);
export var DateModels; (function (DateModels) { let SelectType; (function (SelectType) { SelectType[SelectType["None"] = 0] = "None"; SelectType[SelectType["Single"] = 1] = "Single"; SelectType[SelectType["All"] = 2] = "All"; SelectType[SelectType["Only"] = 3] = "Only"; SelectType[SelectType["Start"] = 4] = "Start"; SelectType[SelectType["Middle"] = 5] = "Middle"; SelectType[SelectType["End"] = 6] = "End"; })(SelectType = DateModels.SelectType || (DateModels.SelectType = {})); })(DateModels || (DateModels = {})); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiRGF0YVR5cGVzLmpzIiwic291cmNlUm9vdCI6Ii4uLy4uL2NvbXBvbmVudHMvIiwic291cmNlcyI6WyJjYWxlbmRhci9kYXRlL0RhdGFUeXBlcy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxNQUFNLEtBQVcsVUFBVSxDQWtFMUI7QUFsRUQsV0FBaUIsVUFBVTtJQUN6QixJQUFZLFVBUVg7SUFSRCxXQUFZLFVBQVU7UUFDcEIsMkNBQUksQ0FBQTtRQUNKLCtDQUFNLENBQUE7UUFDTix5Q0FBRyxDQUFBO1FBQ0gsMkNBQUksQ0FBQTtRQUNKLDZDQUFLLENBQUE7UUFDTCwrQ0FBTSxDQUFBO1FBQ04seUNBQUcsQ0FBQTtJQUNMLENBQUMsRUFSVyxVQUFVLEdBQVYscUJBQVUsS0FBVixxQkFBVSxRQVFyQjtBQXlESCxDQUFDLEVBbEVnQixVQUFVLEtBQVYsVUFBVSxRQWtFMUIiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgbmFtZXNwYWNlIERhdGVNb2RlbHMge1xuICBleHBvcnQgZW51bSBTZWxlY3RUeXBlIHtcbiAgICBOb25lLFxuICAgIFNpbmdsZSxcbiAgICBBbGwsXG4gICAgT25seSxcbiAgICBTdGFydCxcbiAgICBNaWRkbGUsXG4gICAgRW5kXG4gIH1cblxuICBleHBvcnQgaW50ZXJmYWNlIExvY2FsZSB7XG4gICAgdGl0bGU6IHN0cmluZztcbiAgICB0b2RheTogc3RyaW5nO1xuICAgIG1vbnRoOiBzdHJpbmc7XG4gICAgeWVhcjogc3RyaW5nO1xuICAgIGFtOiBzdHJpbmc7XG4gICAgcG06IHN0cmluZztcbiAgICBkYXRlRm9ybWF0OiBzdHJpbmc7XG4gICAgZGF0ZVRpbWVGb3JtYXQ6IHN0cmluZztcbiAgICBub0Nob29zZTogc3RyaW5nO1xuICAgIHdlZWs6IHN0cmluZ1tdO1xuICAgIGNsZWFyOiBzdHJpbmc7XG4gICAgc2VsZWN0VGltZTogc3RyaW5nO1xuICAgIHNlbGVjdFN0YXJ0VGltZTogc3RyaW5nO1xuICAgIHNlbGVjdEVuZFRpbWU6IHN0cmluZztcbiAgICBzdGFydDogc3RyaW5nO1xuICAgIGVuZDogc3RyaW5nO1xuICAgIGJlZ2luOiBzdHJpbmc7XG4gICAgb3Zlcjogc3RyaW5nO1xuICAgIGJlZ2luX292ZXI6IHN0cmluZztcbiAgICBjb25maXJtOiBzdHJpbmc7XG4gICAgbW9udGhUaXRsZTogc3RyaW5nO1xuICAgIGxvYWRQcmV2TW9udGg6IHN0cmluZztcbiAgICB5ZXN0ZXJkYXk6IHN0cmluZztcbiAgICBsYXN0V2Vlazogc3RyaW5nO1xuICAgIGxhc3RNb250aDogc3RyaW5nO1xuICB9XG5cbiAgZXhwb3J0IGludGVyZmFjZSBDZWxsRGF0YSB7XG4gICAgdGljazogbnVtYmVyO1xuICAgIGRheU9mTW9udGg6IG51bWJlcjtcbiAgICBzZWxlY3RlZDogU2VsZWN0VHlwZTtcbiAgICBpc0ZpcnN0T2ZNb250aDogYm9vbGVhbjtcbiAgICBpc0xhc3RPZk1vbnRoOiBib29sZWFuO1xuICAgIG91dE9mRGF0ZTogYm9vbGVhbjtcbiAgfVxuXG4gIGV4cG9ydCBpbnRlcmZhY2UgRXh0cmFEYXRhIHtcbiAgICBpbmZvPzogc3RyaW5nO1xuICAgIGRpc2FibGU/OiBib29sZWFuO1xuICAgIGNlbGxDbHM/OiBhbnk7XG4gICAgY2VsbFJlbmRlcj86IGFueTtcbiAgfVxuXG4gIGV4cG9ydCBpbnRlcmZhY2UgTW9udGhEYXRhIHtcbiAgICB0aXRsZTogc3RyaW5nO1xuICAgIGZpcnN0RGF0ZTogRGF0ZTtcbiAgICBsYXN0RGF0ZTogRGF0ZTtcbiAgICB3ZWVrczogRGF0ZU1vZGVscy5DZWxsRGF0YVtdW107XG4gICAgY29tcG9uZW50PzogYW55O1xuICAgIGhlaWdodD86IG51bWJlcjtcbiAgICB5PzogbnVtYmVyO1xuICAgIHVwZGF0ZUxheW91dD86IEZ1bmN0aW9uO1xuICAgIGNvbXBvbmVudFJlZj86IGFueTtcbiAgfVxufVxuIl19
// server.js // load the things we need // var express = require('express'); // var app = express(); // set the view engine to ejs // app.set('view engine', 'ejs'); // app.use(express.static('views')); // use res.render to load up an ejs view file // index page // app.get('/', function(req, res) { // res.render('pages/index'); //}); // login page // app.get('/login', function(req, res){ // res.render('pages/index');res.render('pages/login'); // }); // about page // app.get('/about', function(req, res) { // res.render('pages/about'); // }); // contact page // app.get('/contact', function(req, res){ // res.render('pages/contact') // }); // 404 page // app.get('/*', function(req, res){ // res.render('pages/404'); // }); // app.listen(3000); // console.log('Server draait op poort 3000!');
/** * Created by yydashen on 2018/2/1. */ //二级地区显示 function province() { var regionId=$("#regionId option:selected").val(); $.ajax({ type:'post', url:hotelSelect, data:{'regionId':regionId}, async: false, dataType: 'json', success: function (res) { $('#regionCity').empty(); for(var i=0;i<res.data[0].length;i++) { $('#regionCity').append('<option value="'+res.data[0][i]['REGION_ID']+'">'+res.data[0][i]['REGION_NAME']+'</option>') } } }) } //酒店修改编辑 function Release() { var hotel=$('#form-article-add').serialize(); var hotelId=$('#hotelId').val(); hotel=hotel+'&'+'img='+JSON.stringify(imgTemporary)+'&'+'id='+hotelId; layer.confirm('确定修改!', { btn: ['确定','取消'] //按钮 }, function(){ var index123 = layer.load(); $.ajax({ type: 'post', url: hotelChangeAppend, data: hotel, dataType: 'json', success: function (res) { layer.close(index123); layer.open({ title: 'OK' ,content: '修改成功!' ,yes:function(){ window.location.href=hotelIndex; } }); } }) }, function(){ layer.msg('取消', { time: 20000, //20s后自动关闭 btn: ['修改', '取消'] }); }); }
import setupMirage from 'ember-cli-mirage/test-support/setup-mirage'; import {authenticateSession, invalidateSession} from 'ember-simple-auth/test-support'; import {beforeEach, describe, it} from 'mocha'; import {clickTrigger, selectChoose} from 'ember-power-select/test-support/helpers'; import {currentURL, find, findAll, triggerEvent, visit} from '@ember/test-helpers'; import {expect} from 'chai'; import {setupApplicationTest} from 'ember-mocha'; describe('Acceptance: Content', function () { let hooks = setupApplicationTest(); setupMirage(hooks); it('redirects to signin when not authenticated', async function () { await invalidateSession(); await visit('/'); expect(currentURL()).to.equal('/signin'); }); describe('as admin', function () { let admin, editor, publishedPost, scheduledPost, draftPost, publishedPage, authorPost; beforeEach(async function () { let adminRole = this.server.create('role', {name: 'Administrator'}); admin = this.server.create('user', {roles: [adminRole]}); let editorRole = this.server.create('role', {name: 'Editor'}); editor = this.server.create('user', {roles: [editorRole]}); publishedPost = this.server.create('post', {authors: [admin], status: 'published', title: 'Published Post'}); scheduledPost = this.server.create('post', {authors: [admin], status: 'scheduled', title: 'Scheduled Post'}); draftPost = this.server.create('post', {authors: [admin], status: 'draft', title: 'Draft Post'}); publishedPage = this.server.create('post', {authors: [admin], status: 'published', page: true, title: 'Published Page'}); authorPost = this.server.create('post', {authors: [editor], status: 'published', title: 'Editor Published Post'}); return await authenticateSession(); }); it('displays and filters posts', async function () { await visit('/'); // Not checking request here as it won't be the last request made // Displays all posts + pages expect(findAll('[data-test-post-id]').length, 'all posts count').to.equal(5); // show draft posts await selectChoose('[data-test-type-select]', 'Draft posts'); // API request is correct let [lastRequest] = this.server.pretender.handledRequests.slice(-1); expect(lastRequest.queryParams.filter, '"drafts" request status filter').to.have.string('status:draft'); expect(lastRequest.queryParams.filter, '"drafts" request page filter').to.have.string('page:false'); // Displays draft post expect(findAll('[data-test-post-id]').length, 'drafts count').to.equal(1); expect(find(`[data-test-post-id="${draftPost.id}"]`), 'draft post').to.exist; // show published posts await selectChoose('[data-test-type-select]', 'Published posts'); // API request is correct [lastRequest] = this.server.pretender.handledRequests.slice(-1); expect(lastRequest.queryParams.filter, '"published" request status filter').to.have.string('status:published'); expect(lastRequest.queryParams.filter, '"published" request page filter').to.have.string('page:false'); // Displays three published posts + pages expect(findAll('[data-test-post-id]').length, 'published count').to.equal(2); expect(find(`[data-test-post-id="${publishedPost.id}"]`), 'admin published post').to.exist; expect(find(`[data-test-post-id="${authorPost.id}"]`), 'author published post').to.exist; // show scheduled posts await selectChoose('[data-test-type-select]', 'Scheduled posts'); // API request is correct [lastRequest] = this.server.pretender.handledRequests.slice(-1); expect(lastRequest.queryParams.filter, '"scheduled" request status filter').to.have.string('status:scheduled'); expect(lastRequest.queryParams.filter, '"scheduled" request page filter').to.have.string('page:false'); // Displays scheduled post expect(findAll('[data-test-post-id]').length, 'scheduled count').to.equal(1); expect(find(`[data-test-post-id="${scheduledPost.id}"]`), 'scheduled post').to.exist; // show pages await selectChoose('[data-test-type-select]', 'Pages'); // API request is correct [lastRequest] = this.server.pretender.handledRequests.slice(-1); expect(lastRequest.queryParams.filter, '"pages" request status filter').to.have.string('status:[draft,scheduled,published]'); expect(lastRequest.queryParams.filter, '"pages" request page filter').to.have.string('page:true'); // Displays page expect(findAll('[data-test-post-id]').length, 'pages count').to.equal(1); expect(find(`[data-test-post-id="${publishedPage.id}"]`), 'page post').to.exist; // show all posts await selectChoose('[data-test-type-select]', 'All posts'); // API request is correct [lastRequest] = this.server.pretender.handledRequests.slice(-1); expect(lastRequest.queryParams.filter, '"all" request status filter').to.have.string('status:[draft,scheduled,published]'); expect(lastRequest.queryParams.filter, '"all" request page filter').to.have.string('page:[true,false]'); // show all posts by editor await selectChoose('[data-test-author-select]', editor.name); // API request is correct [lastRequest] = this.server.pretender.handledRequests.slice(-1); expect(lastRequest.queryParams.filter, '"editor" request status filter').to.have.string('status:[draft,scheduled,published]'); expect(lastRequest.queryParams.filter, '"editor" request page filter').to.have.string('page:[true,false]'); expect(lastRequest.queryParams.filter, '"editor" request filter param').to.have.string(`authors:${editor.slug}`); // Displays editor post // TODO: implement "filter" param support and fix mirage post->author association // expect(find('[data-test-post-id]').length, 'editor post count').to.equal(1); // expect(find(`[data-test-post-id="${authorPost.id}"]`), 'author post').to.exist; // TODO: test tags dropdown // Double-click on a post opens editor await triggerEvent(`[data-test-post-id="${authorPost.id}"]`, 'dblclick'); expect(currentURL(), 'url after double-click').to.equal(`/editor/${authorPost.id}`); }); // TODO: skipped due to consistently random failures on Travis // options[0] is undefined // https://github.com/TryGhost/Ghost/issues/10308 it.skip('sorts tags filter alphabetically', async function () { this.server.create('tag', {name: 'B - Second', slug: 'second'}); this.server.create('tag', {name: 'Z - Last', slug: 'last'}); this.server.create('tag', {name: 'A - First', slug: 'first'}); await visit('/'); await clickTrigger('[data-test-tag-select]'); let options = findAll('.ember-power-select-option'); expect(options[0].textContent.trim()).to.equal('All tags'); expect(options[1].textContent.trim()).to.equal('A - First'); expect(options[2].textContent.trim()).to.equal('B - Second'); expect(options[3].textContent.trim()).to.equal('Z - Last'); }); }); describe('as author', function () { let author, authorPost; beforeEach(async function () { let authorRole = this.server.create('role', {name: 'Author'}); author = this.server.create('user', {roles: [authorRole]}); let adminRole = this.server.create('role', {name: 'Administrator'}); let admin = this.server.create('user', {roles: [adminRole]}); // create posts authorPost = this.server.create('post', {authors: [author], status: 'published', title: 'Author Post'}); this.server.create('post', {authors: [admin], status: 'scheduled', title: 'Admin Post'}); return await authenticateSession(); }); it('only fetches the author\'s posts', async function () { await visit('/'); // trigger a filter request so we can grab the posts API request easily await selectChoose('[data-test-type-select]', 'Published posts'); // API request includes author filter let [lastRequest] = this.server.pretender.handledRequests.slice(-1); expect(lastRequest.queryParams.filter).to.have.string(`authors:${author.slug}`); // only author's post is shown expect(findAll('[data-test-post-id]').length, 'post count').to.equal(1); expect(find(`[data-test-post-id="${authorPost.id}"]`), 'author post').to.exist; }); }); describe('as contributor', function () { let contributor, contributorPost; beforeEach(async function () { let contributorRole = this.server.create('role', {name: 'Contributor'}); contributor = this.server.create('user', {roles: [contributorRole]}); let adminRole = this.server.create('role', {name: 'Administrator'}); let admin = this.server.create('user', {roles: [adminRole]}); // Create posts contributorPost = this.server.create('post', {authors: [contributor], status: 'draft', title: 'Contributor Post Draft'}); this.server.create('post', {authors: [contributor], status: 'published', title: 'Contributor Published Post'}); this.server.create('post', {authors: [admin], status: 'scheduled', title: 'Admin Post'}); return await authenticateSession(); }); it('only fetches the contributor\'s draft posts', async function () { await visit('/'); // Ensure the type, tag, and author selectors don't exist expect(find('[data-test-type-select]'), 'type selector').to.not.exist; expect(find('[data-test-tag-select]'), 'tag selector').to.not.exist; expect(find('[data-test-author-select]'), 'author selector').to.not.exist; // Trigger a sort request await selectChoose('[data-test-order-select]', 'Oldest'); // API request includes author filter let [lastRequest] = this.server.pretender.handledRequests.slice(-1); expect(lastRequest.queryParams.filter).to.have.string(`authors:${contributor.slug}`); // only contributor's post is shown expect(findAll('[data-test-post-id]').length, 'post count').to.equal(1); expect(find(`[data-test-post-id="${contributorPost.id}"]`), 'author post').to.exist; }); }); });
import React from "react"; const SearchBar = () => { return <div className="search_bar__container">Search Bar</div>; }; export default SearchBar;
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * This module contains the integration code segment of Siddhi editor. * This will set the options of ACE editor, attach client side parser and attach SiddhiCompletion Engine with the editor */ define(["ace/ace", "jquery", "./constants", "./utils", "./completion-engine", "./token-tooltip", "ace/ext/language_tools", "./debug-rest-client", "log", 'ace/range'], function (ace, $, constants, utils, CompletionEngine, aceTokenTooltip, aceExtLangTools, DebugRESTClient, log, AceRange) { "use strict"; // JS strict mode /* * Map for completion list styles * Update this map to update the styles applied to the completion list popup items */ var completionTypeToStyleMap = {}; completionTypeToStyleMap[constants.SNIPPETS] = "font-style: italic;"; /* * Generating the displayNameToStyleMap from completionTypeToStyleMap * This is done to support defining completion popup styles using the completion type name rather than the display name */ var displayNameToStyleMap = {}; for (var completionType in completionTypeToStyleMap) { if (completionTypeToStyleMap.hasOwnProperty(completionType)) { displayNameToStyleMap[constants.typeToDisplayNameMap[completionType]] = completionTypeToStyleMap[completionType]; } } /* * Loading meta data for the completion engine from the server */ CompletionEngine.loadMetaData(); /** * Siddhi Editor prototype constructor * * @constructor * @param {Object} config The configuration object to be used in the initialization */ function SiddhiEditor(config) { var self = this; var aceEditor = ace.edit(config.divID); // Setting the DivID of the Editor .. Could be <pre> or <div> tags self.realTimeValidation = config.realTimeValidation; new aceTokenTooltip.TokenTooltip(aceEditor); /* * Setting the language mode to siddhi * * Language mode is located at ace-editor/mode/siddhi.js * Highlight style is located at ace-editor/mode/siddhi_highlight_rules.js.js * Folding is located at ace-editor/mode/folding/siddhi.js * Snippets are located at ace-editor/snippets/siddhi.js */ aceEditor.session.setMode(constants.ace.SIDDHI_MODE); // Setting the editor options aceEditor.setReadOnly(config.readOnly); aceEditor.setTheme(config.theme ? "ace/theme/" + config.theme : constants.ace.DEFAULT_THEME); aceEditor.getSession().setUseWrapMode(true); aceEditor.getSession().setTabSize(4); aceEditor.getSession().setUseSoftTabs(true); aceEditor.setShowFoldWidgets(true); aceEditor.setBehavioursEnabled(true); aceEditor.setHighlightSelectedWord(true); aceEditor.setHighlightActiveLine(true); aceEditor.setDisplayIndentGuides(true); aceEditor.setShowPrintMargin(false); aceEditor.setShowFoldWidgets(true); aceEditor.session.setFoldStyle("markbeginend"); aceEditor.setFontSize(12); aceEditor.setOptions({ enableBasicAutocompletion: !config.readOnly && config.autoCompletion, enableSnippets: !config.readOnly && config.autoCompletion, enableLiveAutocompletion: config.autoCompletion, autoScrollEditorIntoView: true, enableMultiselect: false }); // State variables for error checking and highlighting self.state = new State(); self.completionEngine = new CompletionEngine(); self.rawExtensions = CompletionEngine.rawExtensions; // Attaching editor's onChange event handler aceEditor.getSession().on('change', editorChangeHandler); // For adjusting the completer list as required adjustAutoCompletionHandlers(); aceEditor.commands.on('afterExec', function () { adjustAutoCompletionHandlers(); }); // Adding events for adjusting the completions list styles // This is used for showing different styles for different types of completions aceEditor.renderer.on("afterRender", function () { // Checking if a popup is open when the editor is re-rendered if (aceEditor.completer && aceEditor.completer.popup) { // Adding a on after render event for updating the popup styles aceEditor.completer.popup.renderer.on("afterRender", function () { var completionElements = document.querySelectorAll( ".ace_autocomplete > .ace_scroller > .ace_content > .ace_text-layer > .ace_line" ); for (var i = 0; i < completionElements.length; i++) { var element = completionElements[i].getElementsByClassName("ace_rightAlignedText")[0]; if (element && displayNameToStyleMap[element.innerHTML]) { completionElements[i].setAttribute( "style", displayNameToStyleMap[element.innerHTML] ); } } }); } }); /* * Starting a new siddhi worker for running antlr tasks * This is done to isolate the antlr tasks form the main js to solve RequireJS conflicts * Also this will enable the antlr tasks to run without blocking the UI thread */ var siddhiWorker = new SiddhiWorker(new MessageHandler(self)); self.debugger = new Debugger(aceEditor); self.getDebugger = function () { return self.debugger; }; self.getRawExtensions = function () { return self.rawExtensions; }; /** * Returns the ace editor object * Can be used for getting the ace editor object and making custom changes */ self.getAceEditorObject = function () { return aceEditor; }; /** * Returns the content in the ace editor when the method is invoked * * @return {string} Content in the editor when the method is invoked */ self.getContent = function () { return aceEditor.getValue(); }; /** * Sets the content in the ace editor * * @param {string} content Content to set into the ace editor */ self.setContent = function (content) { aceEditor.setValue((content ? content : ""), 1); }; /** * Dynamically select the completers suitable for current context * * @private */ function adjustAutoCompletionHandlers() { // Selecting the completer for current context when auto complete event is fired // SiddhiCompleter needs to be the first completer in the list as it will update the snippets var completerList = [self.completionEngine.SiddhiCompleter, self.completionEngine.SnippetCompleter]; // Adding keyword completor if the cursor is not in front of dot or colon var objectNameRegex = new RegExp("[a-zA-Z_][a-zA-Z_0-9]*\\s*\\.\\s*$", "i"); var namespaceRegex = new RegExp("[a-zA-Z_][a-zA-Z_0-9]*\\s*:\\s*$", "i"); var singleLineCommentRegex = new RegExp("--(?:.(?!\n))*$"); var blockCommentRegex = new RegExp("\\/\\*(?:(?:.|\n)(?!\\*\\/))*$"); // Adding the keyword completor var editorText = aceEditor.getValue(); if (!(objectNameRegex.test(editorText) || namespaceRegex.test(editorText) || singleLineCommentRegex.test(editorText) || blockCommentRegex.test(editorText))) { // todo removing keyword suggestions // completerList.push(aceExtLangTools.keyWordCompleter); } aceEditor.completers = completerList; } /** * Editor change handler * * @private */ function editorChangeHandler() { // Clearing all errors before finding the errors again self.state.semanticErrorList = []; self.state.syntaxErrorList = []; self.unMarkErrors(); siddhiWorker.onEditorChange(aceEditor.getValue().trim()); } /** * Start the timer for checking the semantic errors * After the timer elapses if the user had not typed anything semantic errors will be checked using the server */ self.startCheckForSemanticErrorsTimer = function () { if (config.realTimeValidation) { // If there are no syntax errors and there is a change in parserTree // check for semantic errors if there is no change in the query within 3sec period // 3 seconds delay is added to avoid repeated server calls while user is typing the query. setTimeout(function () { if (Date.now() - self.state.lastEdit >= constants.SERVER_SIDE_VALIDATION_DELAY - 100) { // Check for semantic errors by sending a validate request to the server checkForSemanticErrors(); } }, constants.SERVER_SIDE_VALIDATION_DELAY); } self.state.lastEdit = Date.now(); // Save user's last edit time }; function State() { this.syntaxErrorList = []; // To save the syntax Errors with line numbers this.semanticErrorList = []; // To save semanticErrors with line numbers this.lastEdit = 0; // Last edit time this.errorMarkers = []; // Holds highlighted syntax/semantic error markers } /** * This method send server calls to check the semantic errors * Also retrieves the missing completion engine data from the server if the siddhi app is valid * * @private */ function checkForSemanticErrors() { var editorText = aceEditor.getValue(); // If the user has not typed anything after 3 seconds from his last change, then send the query for // semantic check to check whether the query contains errors or not. submitToServerForSemanticErrorCheck( { siddhiApp: editorText, missingStreams: self.completionEngine.incompleteData.streams, missingInnerStreams: self.completionEngine.incompleteData.partitions, missingAggregationDefinitions: self.completionEngine.incompleteData.aggregationDefinitions }, function (response) { if (response.hasOwnProperty("status") && response.status === "SUCCESS") { /* * Siddhi app is valid */ // Populating the fetched data for incomplete data items into the completion engine's data var streams = getStreamsFromStreamDefinitions(response.streams); for (var streamName in streams) { if (streams.hasOwnProperty(streamName)) { self.completionEngine.streamsList[streamName] = streams[streamName]; } } var aggregationDefinitions = getAggregationsFromAggregationDefinitions(response.aggregationDefinitions); for (var aggregationDefinition in aggregationDefinitions) { if (aggregationDefinitions.hasOwnProperty(aggregationDefinition)) { self.completionEngine.aggregationsList[aggregationDefinition] = aggregationDefinitions[aggregationDefinition]; } } self.completionEngine.partitionsList = []; if (response.innerStreams != undefined) { for (var i = 0; i < response.innerStreams.length; i++) { var innerStreams = getStreamsFromStreamDefinitions(response.innerStreams[i], true); self.completionEngine.partitionsList.push(innerStreams); } } // Updating token tooltips self.completionEngine.clearIncompleteDataLists(); self.unMarkErrors(); } else { /* * Error found in Siddhi app */ if (response.queryContextStartIndex === undefined) { // Update the semanticErrorList self.state.semanticErrorList = [({ row: 0, // Change attribute "text" to "html" if html is sent from server html: utils.wordWrap(response.message, 120), type: "error" })]; // Show the errors in the ace editor gutter aceEditor.session.setAnnotations( self.state.semanticErrorList .concat(self.state.syntaxErrorList) ); } else { // Update the semanticErrorList self.state.semanticErrorList = [({ row: response.queryContextStartIndex[0] - 1, // Change attribute "text" to "html" if html is sent from server html: utils.wordWrap(response.message, 120), type: "error" })]; // Show the errors in the ace editor gutter aceEditor.session.setAnnotations( self.state.semanticErrorList .concat(self.state.syntaxErrorList) ); // Highlight the error self.markError(response); } } siddhiWorker.generateTokenTooltips(); }, siddhiWorker.generateTokenTooltips ); /** * Get the streams list from the stream definitions list returned from the server * This is used for transforming server's stream definitions to completion engine's stream data * * @param {object[]} streamDefinitionsList Stream definitions list returned from the server * @param {boolean} [isInner] Boolean indicating whether the set of stream definitions are inner streams or not * @return {object} Stream data extracted from the stream definitions */ function getStreamsFromStreamDefinitions(streamDefinitionsList, isInner) { var streams = {}; for (var i = 0; i < streamDefinitionsList.length; i++) { var streamDefinition = streamDefinitionsList[i]; var attributes = {}; for (var k = 0; k < streamDefinition.attributeList.length; k++) { attributes[streamDefinition.attributeList[k].name] = streamDefinition.attributeList[k].type; } streams[streamDefinitionsList[i].id] = { attributes: attributes, description: utils.generateDescriptionForStreamOrTable( (isInner ? "Inner " : "") + "Stream", streamDefinitionsList[i].id, attributes ) }; } return streams; } /** * Get the attribute list from the attribute definitions list returned from the server * This is used for transforming server's aggregation definitions to completion engine's aggregation * definition data * * @param {object[]} aggregationDefinitionsList aggregation definitions list returned from the server * @return {object} Aggregation definition data extracted from the aggregation definitions */ function getAggregationsFromAggregationDefinitions(aggregationDefinitionsList) { var aggregationDefinitions = {}; for (var i = 0; i < aggregationDefinitionsList.length; i++) { var aggregationDefinition = aggregationDefinitionsList[i]; var attributes = {}; for (var k = 0; k < aggregationDefinition.attributeList.length; k++) { attributes[aggregationDefinition.attributeList[k].name] = aggregationDefinition.attributeList[k].type; } aggregationDefinitions[aggregationDefinitionsList[i].id] = { attributes: attributes, description: utils.generateDescriptionForAggregation( aggregationDefinitionsList[i].id, attributes ) }; } return aggregationDefinitions; } } /** * Highlights the section with the semantic errors. * @param error */ self.markError = function (error) { if (error.hasOwnProperty("queryContextStartIndex") && error.hasOwnProperty("queryContextEndIndex")) { self.state.errorMarkers.push(aceEditor.session.addMarker( new AceRange.Range(error.queryContextStartIndex[0] - 1, error.queryContextStartIndex[1], error.queryContextEndIndex[0] - 1, error.queryContextEndIndex[1]), "error_line_highlight", "text", true )); } }; /** * Remove previously highlighted semantic errors. */ self.unMarkErrors = function () { for (var i = 0; i < self.state.errorMarkers.length; i++) { if (self.state.errorMarkers[i] !== null) aceEditor.session.removeMarker(self.state.errorMarkers[i]); } }; /** * Submit the siddhi app to server for semantic error checking * Also fetched the incomplete data from the server for the completion engine * * @private * @param {Object} data The siddhi app and the missing data in a java script object * @param {function} callback Callback to be called after successful semantic error check * @param {function} [errorCallback] Callback to be called after errors in semantic error check */ function submitToServerForSemanticErrorCheck(data, callback, errorCallback) { if (data.siddhiApp === "") { return; } $.ajax({ type: "POST", url: constants.SERVER_URL + "validator", data: JSON.stringify(data), success: callback, error: errorCallback }); } return self; } /** * Siddhi Web Worker wrapper prototype * Handles all ANTLR related processing * Automatically starts up the web worker as well * * @param {MessageHandler} messageHandler Message handler object which will handle all incoming messages from the worker * @return {SiddhiWorker} Siddhi worker instance * @constructor */ function SiddhiWorker(messageHandler) { var self = this; var worker; /** * Restart the web worker */ self.restart = function () { if (worker) { worker.terminate(); } worker = new Worker("/editor/js/source-editor/antlr-worker.js"); self.init(); }; /** * Initialize the web worker * Constants are passed into the web worker * Constants are passed in this way because some of the constants are generated values and the generation of which requires the window object */ self.init = function () { worker.postMessage(JSON.stringify({ type: constants.worker.INIT, data: constants })); // Add event receiver to listen to incoming messages from the web worker worker.addEventListener('message', function (event) { messageHandler.handle(JSON.parse(event.data)); }); }; /** * Run on editor's change * Send message to the worker to create the parse tree and generate completion engine data * * @param {string} editorText Text in the editor after the change */ var editorChangeDelayTimer; self.onEditorChange = function (editorText) { clearTimeout(editorChangeDelayTimer); editorChangeDelayTimer = setTimeout(function () { worker.postMessage(JSON.stringify({ type: constants.worker.EDITOR_CHANGE_EVENT, data: editorText })); }, 2000); }; /** * Send message to the worker to start generating token tool tips * The worker will recognize the token tooltip generation points and pass the the relevant data back so that they can be added */ self.generateTokenTooltips = function () { worker.postMessage(JSON.stringify({ type: constants.worker.GENERATE_TOKEN_TOOLTIP })); }; self.restart(); // Starts up the web worker return self; } /** * Siddhi Debugger prototype * Siddhi Debugger is used to debug current query in the editor * * @param {object} aceEditor The Ace Editor object * @return {Debugger} Siddhi Debugger instance * @constructor */ function Debugger(aceEditor) { var self = this; self.__pollingInterval = 1000; self.__pollingLock = false; self.__pollingJob = null; self.__callback = null; self.__onChangeLineNumbers = null; self.__onDebugStopped = null; self.__client = DebugRESTClient; self.siddhiAppName = null; self.streams = null; self.queries = null; self.__validBreakPoints = null; self.__failedStateRequests = 0; self.__isRunning = false; self.siddhiAppName = 'siddhiApp'; self.setSiddhiAppName = function (appName) { self.siddhiAppName = appName; }; self.debug = function (successCallback, errorCallback, async) { if (!self.__isRunning) { self.__client.debug( self.siddhiAppName, function (data) { self.streams = data['streams']; self.queries = data['queries']; if (self.streams === null || self.streams.length === 0) { console.warn("Streams cannot be empty."); } if (self.queries === null || self.queries.length === 0) { console.warn("Queries cannot be empty."); } if (self.streams !== null && self.streams.length > 0 && self.queries !== null && self.queries.length > 0) { console.log("Debugger started : " + self.siddhiAppName); self.__isRunning = true; self.__pollingJob = setInterval(function () { if (!self.__pollingLock) { self.state(); } }, self.__pollingInterval); if (typeof successCallback === 'function') successCallback(self.siddhiAppName, self.streams, self.queries) } }, function (error) { if (typeof errorCallback === 'function') errorCallback(error) }, async ); } else { log.error("Siddhi app is already running.") } }; self.stop = function (successCallback, errorCallback) { if (self.__pollingJob !== null) { clearInterval(self.__pollingJob); } if (self.__isRunning) { self.__client.stop( self.siddhiAppName, function (data) { console.log("Debugger stopped : " + self.siddhiAppName); self.__isRunning = false; if (typeof successCallback === 'function') successCallback(data); if (typeof self.__onDebugStopped === 'function') self.__onDebugStopped() }, function (error) { if (typeof errorCallback === 'function') errorCallback(error); } ); } else { console.log("Debugger has not been started yet.") } }; self.clearInterval = function () { if (self.__pollingJob !== null) { clearInterval(self.__pollingJob); } }; self.acquire = function (lineNo, success) { var breakPoints = self.__validBreakPoints[lineNo]; if (self.__isRunning && breakPoints !== null && breakPoints.length > 0) { for (var i = 0; i < breakPoints.length; i++) { self.__client.acquireBreakPoint( self.siddhiAppName, breakPoints[i]['queryIndex'], breakPoints[i]['terminal'], function (data) { console.info(JSON.stringify(data)); if (typeof success === 'function') success(data) }, function (error) { log.error(JSON.stringify(error)); } ); } } else { log.error("Debugger has not been started yet.") } }; self.release = function (lineNo, success) { var breakPoints = self.__validBreakPoints[lineNo]; if (self.__isRunning && breakPoints !== null && breakPoints.length > 0) { for (var i = 0; i < breakPoints.length; i++) { self.__client.releaseBreakPoint( self.siddhiAppName, breakPoints[i]['queryIndex'], breakPoints[i]['terminal'], function (data) { console.info(JSON.stringify(data)); if (typeof success === 'function') success(data) }, function (error) { log.error(JSON.stringify(error)); } ); } } else { console.log("Debugger has not been started yet.") } }; self.next = function () { if (self.__isRunning) { self.__client.next( self.siddhiAppName, function (data) { console.info(JSON.stringify(data)); if (typeof self.__onBeforeUpdateCallback === 'function') self.__onBeforeUpdateCallback(); self.state(); }, function (error) { log.error(JSON.stringify(error)); } ); } else { log.error("Debugger has not been started yet.") } }; self.play = function () { if (self.__isRunning) { self.__client.play( self.siddhiAppName, function (data) { console.info(JSON.stringify(data)); if (typeof self.__onBeforeUpdateCallback === 'function') self.__onBeforeUpdateCallback(); self.state(); }, function (error) { log.error(JSON.stringify(error)); } ); } else { console.log("Debugger has not been started yet.") } }; self.state = function () { self.__pollingLock = true; if (self.__isRunning) { self.__client.state( self.siddhiAppName, function (data) { if (data.hasOwnProperty('eventState')) { if (typeof self.__callback === 'function') { self.__callback(data); } } self.__pollingLock = false; self.__failedStateRequests = 0; }, function (error) { log.error(JSON.stringify(error)); self.__failedStateRequests += 1; self.__pollingLock = false; if (self.__failedStateRequests >= 5) { console.warn("Backend is unreachable. Hence, stopping debugger."); self.stop(); } } ); } else { console.log("Debugger has not been started yet.") } }; self.sendEvent = function (streamId, event) { if (self.__isRunning) { self.__client.sendEvent( self.siddhiAppName, streamId, event, function (data) { console.info(JSON.stringify(data)); }, function (error) { log.error(JSON.stringify(error)); } ); } else { console.log("Debugger has not been started yet.") } }; self.setOnUpdateCallback = function (onUpdateCallback) { self.__callback = onUpdateCallback; }; self.setOnBeforeUpdateCallback = function (onBeforeUpdateCallback) { self.__onBeforeUpdateCallback = onBeforeUpdateCallback; }; self.setOnDebugStoppedCallback = function (onDebugStopped) { self.__onDebugStopped = onDebugStopped; }; self.setOnChangeLineNumbersCallback = function (onChangeLineNumbers) { self.__onChangeLineNumbers = onChangeLineNumbers; }; self._resetQueryMeta = function () { self.__validBreakPoints = {}; }; self._updateQueryMeta = function (metaData) { self.__validBreakPoints = {}; if (metaData !== null && metaData.length > 0) { for (var i = 0; i < metaData.length; i++) { var inLineNo = metaData[i]['in'] - 1; // breakpoints starts from 0 var outLineNo = metaData[i]['out'] - 1; if (self.__validBreakPoints.hasOwnProperty(inLineNo)) { self.__validBreakPoints[inLineNo].push({ terminal: 'in', queryIndex: i }); } else { self.__validBreakPoints[inLineNo] = [{ terminal: 'in', queryIndex: i }] } if (self.__validBreakPoints.hasOwnProperty(outLineNo)) { self.__validBreakPoints[outLineNo].push({ terminal: 'out', queryIndex: i }); } else { self.__validBreakPoints[outLineNo] = [{ terminal: 'out', queryIndex: i }] } } } if (typeof self.__onChangeLineNumbers === 'function') { self.__onChangeLineNumbers(self.__validBreakPoints); } }; return self; } /** * Message handler prototype * Message handler is used by the siddhi worker * * @param {object} editor The editor object * @return {MessageHandler} Message handler instance * @constructor */ function MessageHandler(editor) { var handler = this; var messageHandlerMap = {}; var tokenTooltipUpdater = new TokenTooltipUpdater(editor); // Generating the map from message types to handler functions messageHandlerMap[constants.worker.PARSE_TREE_GENERATION_COMPLETION] = updateSyntaxErrorList; messageHandlerMap[constants.worker.DATA_POPULATION_COMPLETION] = updateCompletionEngineData; messageHandlerMap[constants.worker.TOKEN_TOOLTIP_POINT_RECOGNITION_COMPLETION] = updateTokenTooltips; /** * Handle an incoming message from the web worker * @param {object} message */ handler.handle = function (message) { messageHandlerMap[message.type](message.data); }; /** * Update the list of syntax errors and add annotations * * @param {object} data Syntax errors data list */ function updateSyntaxErrorList(data) { editor.state.syntaxErrorList = data; editor.getAceEditorObject().session.setAnnotations(data); markSyntaxError(data); } /** * Highlight syntax errors * @param errors */ function markSyntaxError(errors) { if (errors.length > 0) { var error = errors[0]; if (error.type === "error") { var syntax = editor.getAceEditorObject().session.getLine(error.row).substr(error.column) .split(/[^0-9a-zA-Z]+/g)[0]; var syntaxLength = syntax.length; var errorObj = { message: error.text, queryContextStartIndex: [error.row + 1, error.column], queryContextEndIndex: [error.row + 1, error.column + syntaxLength] }; editor.markError(errorObj); } } } /** * Update the completion engine's data using the data generated by the worker * * @param {object} data Completion engine data generated by the worker */ function updateCompletionEngineData(data) { editor.debugger._resetQueryMeta(); editor.debugger._updateQueryMeta(data.debugData); editor.completionEngine.clearData(); // Clear the exiting completion engine data editor.completionEngine.streamsList = data.completionData.streamsList; editor.completionEngine.partitionsList = data.completionData.partitionsList; editor.completionEngine.eventTablesList = data.completionData.eventTablesList; editor.completionEngine.eventTriggersList = data.completionData.eventTriggersList; editor.completionEngine.evalScriptsList = data.completionData.evalScriptsList; editor.completionEngine.eventWindowsList = data.completionData.eventWindowsList; editor.completionEngine.aggregationsList = data.completionData.aggregationsList; editor.completionEngine.updateDescriptions(); editor.completionEngine.incompleteData = data.incompleteData; editor.completionEngine.statementsList = data.statementsList; editor.startCheckForSemanticErrorsTimer(); } /** * Update the token tool tips using the data generated by the worker * * @param {object} data Token tool tip points and information for generating token tool tips */ function updateTokenTooltips(data) { for (var i = 0; i < data.length; i++) { var tooltipType = data[i].type; var tooltipData = data[i].tooltipData; var row = data[i].row; var column = data[i].column; tokenTooltipUpdater.update(tooltipType, tooltipData, row, column); } } return handler; } /** * Token tooltips generator prototype * * @param {object} editor The editor object * @return {TokenTooltipUpdater} Token tooltip generator instance * @constructor */ function TokenTooltipUpdater(editor) { var updater = this; /** * Update the tooltip for the given type using the tool tip data * * @param {string} tooltipType Type of the tool tip to be updated * @param {object} tooltipData Tool tip data from which the tool tip will be generated * @param {int} row The row at which the target token is at * @param {int} column The column at which the target token is at */ updater.update = function (tooltipType, tooltipData, row, column) { switch (tooltipType) { case constants.FUNCTION_OPERATION: updateFunctionOperationTooltip(tooltipData, row, column); break; case constants.SOURCE: updateSourceTooltip(tooltipData, row, column); break; case constants.INNER_STREAMS: updateInnerStreamTooltip(tooltipData, row, column); break; case constants.TRIGGERS: updateTriggerTooltip(tooltipData, row, column); break; case constants.AGGREGATIONS: updateAggregationTooltip(tooltipData, row, column); break; case constants.IO: updateIOToolTip(tooltipData, row, column); break; case constants.MAP: updateMapToolTip(tooltipData, row, column); break; case constants.STORE: updateStoreToolTip(tooltipData, row, column); break; } }; /** * Update the tooltip for a function operation * * @param {object} tooltipData Tool tip data to be added. Should contain the function operation name and the namespace * @param {int} row The row at which the target token is at * @param {int} column The column at which the target token is at */ function updateFunctionOperationTooltip(tooltipData, row, column) { var processorName = tooltipData.processorName; var namespace = tooltipData.namespace; var snippets; if (namespace) { snippets = CompletionEngine.functionOperationSnippets.extensions[namespace]; } else { snippets = CompletionEngine.functionOperationSnippets.inBuilt; } // Adding WindowProcessor/StreamProcessor/Function/additional tool tip var description; if (snippets) { if (snippets.windowProcessors && snippets.windowProcessors[processorName]) { description = snippets.windowProcessors[processorName].description; } else if (snippets.streamProcessors && snippets.streamProcessors[processorName]) { description = snippets.streamProcessors[processorName].description; } else if (snippets.functions && snippets.functions[processorName]) { description = snippets.functions[processorName].description; } else if (editor.completionEngine.evalScriptsList[processorName]) { description = editor.completionEngine.evalScriptsList[processorName].description; } } if (description) { updateTokenTooltip(row, column, description); } } /** * Update the tooltip for a IO connectors source/sink * * @param {object} tooltipData Tool tip data to be added. Should contain the io name and the io namespace * @param {int} row The row at which the target token is at * @param {int} column The column at which the target token is at */ function updateIOToolTip(tooltipData, row, column) { var implementationName = tooltipData.implementationName; var namespace = tooltipData.namespace; var snippets; if (namespace) { snippets = CompletionEngine.functionOperationSnippets.extensions[namespace]; } else { snippets = CompletionEngine.functionOperationSnippets.inBuilt; } // Adding IO source/sink tool tip var description; if (snippets) { if (snippets.sinks && snippets.sinks[implementationName]) { description = snippets.sinks[implementationName].description; } else if (snippets.sources && snippets.sources[implementationName]) { description = snippets.sources[implementationName].description; } } if (description) { updateTokenTooltip(row, column, description); } } /** * Update the tooltip for a Store * * @param {object} tooltipData Tool tip data to be added. Should contain the store name and the store * namespace * @param {int} row The row at which the target token is at * @param {int} column The column at which the target token is at */ function updateStoreToolTip(tooltipData, row, column) { var implementationName = tooltipData.implementationName; var namespace = tooltipData.namespace; var snippets; if (namespace) { snippets = CompletionEngine.functionOperationSnippets.extensions[namespace]; } else { snippets = CompletionEngine.functionOperationSnippets.inBuilt; } // Adding IO source/sink tool tip var description; if (snippets) { if (snippets.stores && snippets.stores[implementationName]) { description = snippets.stores[implementationName].description; } } if (description) { updateTokenTooltip(row, column, description); } } /** * Update the tooltip for a MAP source/sink * * @param {object} tooltipData Tool tip data to be added. Should contain the io name and the io namespace * @param {int} row The row at which the target token is at * @param {int} column The column at which the target token is at */ function updateMapToolTip(tooltipData, row, column) { var implementationName = tooltipData.implementationName; var namespace = tooltipData.namespace; var snippets; if (namespace) { snippets = CompletionEngine.functionOperationSnippets.extensions[namespace]; } else { snippets = CompletionEngine.functionOperationSnippets.inBuilt; } // Adding Map source/sink tool tip var description; if (snippets) { if (snippets.sinkMaps && snippets.sinkMaps[implementationName]) { description = snippets.sinkMaps[implementationName].description; } else if (snippets.sourceMaps && snippets.sourceMaps[implementationName]) { description = snippets.sourceMaps[implementationName].description; } } if (description) { updateTokenTooltip(row, column, description); } } /** * Update the tooltip for a stream/table/window * * @param {object} tooltipData Tool tip data to be added. Should contain the source name * @param {int} row The row at which the target token is at * @param {int} column The column at which the target token is at */ function updateSourceTooltip(tooltipData, row, column) { var sourceName = tooltipData.sourceName; var source; if (editor.completionEngine.streamsList[sourceName]) { source = editor.completionEngine.streamsList[sourceName]; } else if (editor.completionEngine.eventTablesList[sourceName]) { source = editor.completionEngine.eventTablesList[sourceName]; } else if (editor.completionEngine.eventWindowsList[sourceName]) { source = editor.completionEngine.eventWindowsList[sourceName]; } else if (editor.completionEngine.aggregationsList[sourceName]) { source = editor.completionEngine.aggregationsList[sourceName]; } if (source && source.description) { updateTokenTooltip(row, column, source.description); } } /** * Update the tooltip for a inner stream * * @param {object} tooltipData Tool tip data to be added. Should contain the inner stream name and the partition number * @param {int} row The row at which the target token is at * @param {int} column The column at which the target token is at */ function updateInnerStreamTooltip(tooltipData, row, column) { var innerStreamName = tooltipData.sourceName; var partitionNumber = tooltipData.partitionNumber; if (editor.completionEngine.partitionsList[partitionNumber]) { var innerStream = editor.completionEngine.partitionsList[partitionNumber][innerStreamName]; if (innerStream && innerStream.description) { updateTokenTooltip(row, column, innerStream.description); } } } /** * Update the tooltip for a trigger * * @param {object} tooltipData Tool tip data to be added. Should contain the trigger name * @param {int} row The row at which the target token is at * @param {int} column The column at which the target token is at */ function updateTriggerTooltip(tooltipData, row, column) { var triggerName = tooltipData.triggerName; var trigger = editor.completionEngine.eventTriggersList[triggerName]; if (trigger && trigger.description) { updateTokenTooltip(row, column, trigger.description); } } /** * Update the tooltip for an aggregation * * @param {object} tooltipData Tool tip data to be added. Should contain the aggregation name * @param {int} row The row at which the target token is at * @param {int} column The column at which the target token is at */ function updateAggregationTooltip(tooltipData, row, column) { var aggregationName = tooltipData.aggregationName; var aggregation = editor.completionEngine.aggregationsList[aggregationName]; //var details = editor.incompleteData.aggregationsList; if (aggregation && aggregation.description) { updateTokenTooltip(row, column, aggregation.description); } } /** * Add a tooltip at the position specified * * @param {int} tokenRow The row at which the target token is at * @param {int} tokenColumn The column at which the target token is at * @param {string} tooltip Tooltip to be added */ function updateTokenTooltip(tokenRow, tokenColumn, tooltip) { var token = editor.getAceEditorObject().session.getTokenAt(tokenRow, tokenColumn); if (token) { token.tooltip = tooltip; } } return updater; } return SiddhiEditor; });
import {h} from 'preact'; import {saveAs} from 'file-saver'; import Button from './Button'; import NumberRange from './NumberRange'; import styles from './Controls.css'; import Checkbox from './Checkbox'; export default function Controls({ duration, fps, gifSource, quality, showFullImage, showAntiClockwise, dispatch }) { return ( <div class={styles.Controls}> <div class={styles.ControlsLeft}> <Checkbox label={`Show Full Image`} value={showFullImage} onChange={(payload) => dispatch({type: 'setShowFullImage', payload})} /> <Checkbox label={`Reverse direction`} value={showAntiClockwise} onChange={(payload) => dispatch({type: 'setShowAntiClockwise', payload}) } /> <NumberRange label={`Spin Duration: ${duration}ms`} min={200} max={3000} step={100} value={duration} onChange={(payload) => dispatch({type: 'setDuration', payload})} /> <NumberRange label={`Framerate: ${fps}fps`} min={2} max={24} step={1} value={fps} onChange={(payload) => dispatch({type: 'setFps', payload})} /> <NumberRange label={`Quality: ${quality} (lower is better)`} min={1} max={10} step={1} value={quality} onChange={(payload) => dispatch({type: 'setQuality', payload})} /> </div> <div class={styles.ControlsRight}> <Button disabled={!gifSource} onClick={() => saveAs(gifSource, 'spin.gif')} > Download GIF </Button> <Button onClick={() => dispatch({type: 'reset'})}> Upload another image? </Button> </div> </div> ); }
'use strict'; ////////////////// // app // ////////////////// var clickerCalcs = angular.module('trimpCalcApp', []); clickerCalcs.controller('TrimpCalcCtrl', function($scope) { $scope.keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; $scope.keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$"; $scope.weapons = ['Dagger', 'Mace', 'Polearm', 'Battleaxe', 'Greatsword']; $scope.armor = ['Boots', 'Helmet', 'Pants', 'Shoulderguards', 'Breastplate']; $scope.block = ['Shield']; $scope.population = ['Hut', 'House', 'Mansion', 'Hotel', 'Resort', 'Gateway', 'Wormhole']; $scope.show_items = [['Shield', $scope.block], ['Weapons', $scope.weapons], ['Armor', $scope.armor]]; $scope.defaults = newGame(); $scope.base_buildings = $scope.defaults.buildings; $scope.base_equipment = $scope.defaults.equipment; $scope.base_prestige = $scope.defaults.global.prestige; $scope.upgrade_names = $scope.defaults.upgrades; $scope._get_best_item = function(accum, name) { var datum = $scope.data.equipment[name]; if(datum.locked === 1 || datum.purchased === 0) return accum; var cost_per_val = $scope.data.equipment[name].current_price / $scope.data.equipment[name].display_value; if(cost_per_val < accum[1]) return [name, cost_per_val]; else return accum; } $scope._item_price = function(item) { var resource = ''; if(item.name === 'Shield') resource = 'wood'; else resource = 'metal'; return $scope.getItemPrice(item, resource, true); }; $scope._get_display_value = function(item) { if(item.name === 'Shield') { if(item.blockNow) return item.blockCalculated; else return item.healthCalculated; } else if (_.indexOf($scope.weapons, item.name) > -1) { return item.attackCalculated; } else return item.healthCalculated; } $scope._get_total_building_cost = function(name) { var cur = $scope.data.buildings[name]; var costs = _.map(_.keys(cur.cost), function(resource_name) { return parseFloat($scope.getItemPrice(cur, resource_name, false)); }); return _.sum(costs); }; $scope._get_best_building = function(accum, name) { var datum = $scope.data.buildings[name]; if(datum.locked === 1 || datum.purchased === 0) return accum; var cost_per_val = $scope.data.buildings[name].current_price / $scope.data.buildings[name].increase.by; if(cost_per_val < accum[1]) return [name, cost_per_val]; else return accum; } $scope._import_buildings = function() { _.each($scope.population, function(name) { var cur = $scope.data.buildings[name]; var base_data = $scope.base_buildings[name]; cur.cost = base_data.cost; cur.current_price = $scope._get_total_building_cost(name); }); var best_pop = _.reduce($scope.population, $scope._get_best_building, ['', Number.MAX_VALUE], this); $scope.data.buildings[best_pop[0]].is_best = true; }; $scope.import = function(save_data) { $scope.data = JSON.parse(LZString.decompressFromBase64(save_data)); $scope.data.global.prestige = $scope.base_prestige; _.each(_.keys($scope.base_equipment), function(equip_name) { // set defaults; these are zeroed out in the save data var equip_data = $scope.data.equipment[equip_name]; var base_data = $scope.base_equipment[equip_name]; equip_data.cost = base_data.cost; // bring the prestiges up to par if(equip_data.prestige > 1) { for(var i=1,iLen=equip_data.prestige;i<iLen;i++) { $scope.prestigeEquipment(equip_name, true, true); } } // simple displays equip_data.name = equip_name; equip_data.current_price = $scope._item_price(equip_data); equip_data.display_value = Math.max(0, $scope._get_display_value(equip_data)); // calculate prestige values var prestige_value = $scope.getNextPrestigeValue(equip_data); var prestige_cost = $scope.getNextPrestigeCost(equip_data); equip_data.upgrade_efficiency = prestige_cost / prestige_value; equip_data.prestige_surpass = Math.ceil(equip_data.display_value * equip_data.level / prestige_value); // need to incrementally do this, inaccurate past L1 due to scaling cost // equip_data.prestige_cost = prestige_cost * equip_data.prestige_surpass; }); // calculate the best equipment in their classes var best_wep = _.reduce($scope.weapons, $scope._get_best_item, ['', Number.MAX_VALUE], this); $scope.data.equipment[best_wep[0]].is_best = true; var best_armor = _.reduce($scope.armor, $scope._get_best_item, ['', Number.MAX_VALUE], this); $scope.data.equipment[best_armor[0]].is_best = true; $scope._import_buildings(); console.log($scope.data); }; $scope.getItemPrice = function(toBuy, costItem, is_equipment) { if(!toBuy) return 0; var price = 0; var compare = (is_equipment) ? "level" : "purchased"; var thisCost = toBuy.cost[costItem]; if (typeof thisCost[1] !== 'undefined'){ if (thisCost.lastCheckCount != $scope.data.global.buyAmt || thisCost.lastCheckOwned != toBuy[compare]){ for (var x = 0; x < $scope.data.global.buyAmt; x++){ price += $scope.resolvePow(thisCost, toBuy, x); } thisCost.lastCheckCount = $scope.data.global.buyAmt; thisCost.lastCheckAmount = price; thisCost.lastCheckOwned = toBuy[compare]; } else price = thisCost.lastCheckAmount; } else if (typeof thisCost === 'function') { price = thisCost(); } else { price = thisCost * $scope.data.global.buyAmt; } return price; } $scope.resolvePow = function(cost, whatObj, addOwned) { if (!addOwned) addOwned = 0; var compare; if (typeof whatObj.done !== 'undefined') compare = 'done'; if (typeof whatObj.level !== 'undefined') compare = 'level'; if (typeof whatObj.owned !== 'undefined') compare = 'owned'; if (typeof whatObj.purchased !== 'undefined') compare = 'purchased'; return (Math.floor(cost[0] * Math.pow(cost[1], (whatObj[compare] + addOwned)))); } $scope.prestigeEquipment = function(what, fromLoad, noInc) { var equipment = $scope.data.equipment[what]; if (!fromLoad && !noInc) equipment.prestige++; var resource = (what == "Shield") ? "wood" : "metal"; var cost = equipment.cost[resource]; var prestigeMod = 0; if (equipment.prestige >= 4) prestigeMod = (((equipment.prestige - 3) * .85) + 2); else prestigeMod = (equipment.prestige - 1); cost[0] = Math.round(equipment.oc * Math.pow(1.069, ((prestigeMod) * $scope.data.global.prestige.cost) + 1)); cost.lastCheckAmount = null; cost.lastCheckCount = null; cost.lastCheckOwned = null; var stat; if (equipment.blockNow) stat = "block"; else stat = (typeof equipment.health !== 'undefined') ? "health" : "attack"; if (!fromLoad) $scope.data.global[stat] -= (equipment[stat + "Calculated"] * equipment.level); equipment[stat + "Calculated"] = Math.round(equipment[stat] * Math.pow(1.19, ((equipment.prestige - 1) * $scope.data.global.prestige[stat]) + 1)); //No need to touch level if it's newNum if (fromLoad) return; equipment.level = 0; if (document.getElementById(what + "Numeral") !== null) document.getElementById(what + "Numeral").innerHTML = romanNumeral(equipment.prestige); } $scope.getNextPrestigeCost = function(equipment){ var prestigeMod; var nextPrestigeCount = equipment.prestige + 1; if (nextPrestigeCount >= 4) prestigeMod = (((nextPrestigeCount - 3) * .85) + 2); else prestigeMod = (nextPrestigeCount - 1); return Math.round(equipment.oc * Math.pow(1.069, ((prestigeMod) * $scope.data.global.prestige.cost) + 1)); } $scope.getNextPrestigeValue = function(equipment){ var stat; if (equipment.blockNow) stat = "block"; else stat = (typeof equipment.health !== 'undefined') ? "health" : "attack"; var toReturn = Math.round(equipment[stat] * Math.pow(1.19, ((equipment.prestige) * $scope.data.global.prestige[stat]) + 1)); return toReturn; } // initialize tooltip values $(function () { $('[data-toggle="tooltip"]').tooltip() }); // initialize underscore/lodash templates // _.templateSettings.variable = "rc"; });
const express = require('express') const app = express() const PORT = 8888 const bodyParser = require('body-parser') const cors = require('cors') const fs = require('fs') const nodemailer = require('nodemailer') // const { google } = require('googleapis') // const OAuth2 = google.auth.OAuth2 // const OAuth2Client = new OAuth2(process.env.CLIENT_ID, process.env.CLIENT_SECRET) // OAuth2Client.setCredentials({ refresh_token: process.env.REFRESH_TOKEN }) require('dotenv').config() app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })) app.use(cors()) app.use(express.json()) app.get('/apiMail', (req, res) => { res.status(200).send({ datapoint1: "🍌", message: "What you wanna GET GET GET???", sent: true }) }) app.post('/apiMail', (req, res) => { const { id } = req.body const { name } = req.body const { lastName } = req.body const { email } = req.body const { phone } = req.body const { message } = req.body // SAVE POST TO DATABASE if (!name && !lastName && !email && !phone && !message) { res.status(418).send({ message: 'no complex form data has been sent!' }) } console.log(`Form with id of: ${id} has been submitted.`) let resObj = { id: `${id}`, Name: ` 🍌 ${name}`, LastName: ` 🍕 ${lastName}`, Email: ` 💌${email}`, Phone: ` 📞 ${phone}`, Message: ` 📑 ${message}`, } // const db = 'db.json' const db=[] let database = 'db.json' let sendData = JSON.stringify(resObj) res.send(sendData) function pushMail() { // SEND POST IN EMAIL console.log('from the sendMail function') // const accessToken = OAuth2Client.getAccessToken() let transport = nodemailer.createTransport({ service: 'gmail', // name: '127.0.0.1', host: 'smtp.gmail.com', port: 587, logger: true, debug: true, tls: { rejectUnauthorized: false }, // auth: { // type: 'OAuth2', // user: process.env.USER, // clientId: process.env.CLIENT_ID, // clientSecret: process.env.CLIENT_SECRET, // refreshToken: process.env.REFRESH_TOKEN, // accessToken: accessToken // }, auth: { user: process.env.USER, pass: process.env.PASS, }, }) let mailOptions = { from: `${email}`, to: 'cattoday.info@gmail.com', subject: `Message from ${name}`, html: ` <h3>Informations</h3> <ul> <li>Name: ${name}</li> <li>Email: ${email}</li> <li>Phone: ${phone}</li> </ul> <h3>Message:</h3> <br> <p> ${message} </p> ` } // transport.sendMail(mailOptions, function (error, result) { // if (error) { // console.log('Error happened: ', error) // } else { // console.log('Success: ', result) // // saveToDb() // } // transport.close() // }) function saveToDb(db, resObj) { db.push(resObj) fs.readFile(database, (err,db)=>{ if (err) throw err fs.appendFile(database, db, err => { if (err) throw err; console.log('File successfully written to database.') }) }) // fs.readFile(db, (err, data) => { // if (err) throw err // if (data.length == 0) { // fs.appendFile(db, '[' + sendData + ',', err => { // if (err) throw err; // console.log('File successfully written to empty database.') // }) // } else { // fs.appendFile(db, sendData + ',', err => { // if (err) throw err; // console.log('File successfully written to database.') // }) // } // }) } saveToDb(db, resObj) } // SEND MAIL AND SAVE TO JSON pushMail() }) app.listen( PORT, () => console.log(`it's alive on http:localhost:${PORT}`) )
import React from "react"; import { Link } from "react-router-dom"; // JavaScript plugin that hides or shows a component based on your scroll import Headroom from "headroom.js"; // reactstrap components import { Button, Collapse, DropdownToggle, DropdownMenu, DropdownItem, UncontrolledDropdown, NavbarBrand, Navbar, NavItem, Nav, Container, UncontrolledTooltip, } from "reactstrap"; // core components function WhiteNavbar() { const [bodyClick, setBodyClick] = React.useState(false); const [collapseOpen, setCollapseOpen] = React.useState(false); React.useEffect(() => { let headroom = new Headroom(document.getElementById("navbar-main")); // initialise headroom.init(); }); return ( <> {bodyClick ? ( <div id="bodyClick" onClick={() => { document.documentElement.classList.toggle("nav-open"); setBodyClick(false); setCollapseOpen(false); }} /> ) : null} <Navbar className="fixed-top" expand="lg" id="navbar-main"> <Container> <div className="navbar-translate"> <NavbarBrand id="navbar-brand" to="/index" tag={Link}> Paper Kit PRO React </NavbarBrand> <UncontrolledTooltip placement="bottom" target="navbar-brand"> Paper Kit PRO React </UncontrolledTooltip> <button className="navbar-toggler" id="navigation" type="button" onClick={() => { document.documentElement.classList.toggle("nav-open"); setBodyClick(true); setCollapseOpen(true); }} > <span className="navbar-toggler-bar bar1" /> <span className="navbar-toggler-bar bar2" /> <span className="navbar-toggler-bar bar3" /> </button> </div> <Collapse navbar isOpen={collapseOpen}> <Nav className="ml-auto" navbar> <UncontrolledDropdown nav inNavbar> <DropdownToggle className="mr-2" color="default" caret nav> Components </DropdownToggle> <DropdownMenu className="dropdown-danger" right> <DropdownItem to="/index" tag={Link}> All Components </DropdownItem> <DropdownItem to="/presentation" tag={Link}> Presentation </DropdownItem> <DropdownItem href="https://demos.creative-tim.com/paper-kit-pro-react/#/documentation/introduction?ref=pkpr-white-navbar" target="_blank" > Documentation </DropdownItem> </DropdownMenu> </UncontrolledDropdown> <UncontrolledDropdown nav inNavbar> <DropdownToggle className="mr-2" color="default" caret nav> Sections </DropdownToggle> <DropdownMenu className="dropdown-danger" right> <DropdownItem to="/sections#headers" tag={Link}> <i className="nc-icon nc-tile-56" /> Headers </DropdownItem> <DropdownItem to="/sections#features" tag={Link}> <i className="nc-icon nc-settings" /> Features </DropdownItem> <DropdownItem to="/sections#blogs" tag={Link}> <i className="nc-icon nc-bullet-list-67" /> Blogs </DropdownItem> <DropdownItem to="/sections#teams" tag={Link}> <i className="nc-icon nc-single-02" /> Teams </DropdownItem> <DropdownItem to="/sections#projects" tag={Link}> <i className="nc-icon nc-calendar-60" /> Projects </DropdownItem> <DropdownItem to="/sections#pricing" tag={Link}> <i className="nc-icon nc-money-coins" /> Pricing </DropdownItem> <DropdownItem to="/sections#testimonials" tag={Link}> <i className="nc-icon nc-badge" /> Testimonials </DropdownItem> <DropdownItem to="/sections#contact-us" tag={Link}> <i className="nc-icon nc-mobile" /> Contact Us </DropdownItem> </DropdownMenu> </UncontrolledDropdown> <UncontrolledDropdown nav inNavbar> <DropdownToggle color="default" caret nav> Examples </DropdownToggle> <DropdownMenu className="dropdown-danger" right> <DropdownItem to="/about-us" tag={Link}> <i className="nc-icon nc-bank" /> About-us </DropdownItem> <DropdownItem to="/add-product" tag={Link}> <i className="nc-icon nc-basket" /> Add Product </DropdownItem> <DropdownItem to="/blog-post" tag={Link}> <i className="nc-icon nc-badge" /> Blog Post </DropdownItem> <DropdownItem to="/blog-posts" tag={Link}> <i className="nc-icon nc-bullet-list-67" /> Blog Posts </DropdownItem> <DropdownItem to="/contact-us" tag={Link}> <i className="nc-icon nc-mobile" /> Contact Us </DropdownItem> <DropdownItem to="/discover" tag={Link}> <i className="nc-icon nc-world-2" /> Discover </DropdownItem> <DropdownItem to="/e-commerce" tag={Link}> <i className="nc-icon nc-send" /> Ecommerce </DropdownItem> <DropdownItem to="/landing-page" tag={Link}> <i className="nc-icon nc-spaceship" /> Landing Page </DropdownItem> <DropdownItem to="/login-page" tag={Link}> <i className="nc-icon nc-lock-circle-open" /> Login Page </DropdownItem> <DropdownItem to="/product-page" tag={Link}> <i className="nc-icon nc-album-2" /> Product Page </DropdownItem> <DropdownItem to="/profile-page" tag={Link}> <i className="nc-icon nc-single-02" /> Profile Page </DropdownItem> <DropdownItem to="/register-page" tag={Link}> <i className="nc-icon nc-bookmark-2" /> Register Page </DropdownItem> <DropdownItem to="/search-with-sidebar" tag={Link}> <i className="nc-icon nc-zoom-split" /> Search Page </DropdownItem> <DropdownItem to="/settings" tag={Link}> <i className="nc-icon nc-settings-gear-65" /> Settings Page </DropdownItem> <DropdownItem to="/twitter-redesign" tag={Link}> <i className="nc-icon nc-tie-bow" /> Twitter </DropdownItem> </DropdownMenu> </UncontrolledDropdown> <NavItem> <Button className="btn-round" color="danger" href="https://www.creative-tim.com/product/paper-kit-pro-react?ref=pkpr-white-navbar" target="_blank" > <i className="nc-icon nc-cart-simple" /> Buy Now </Button> </NavItem> </Nav> </Collapse> </Container> </Navbar> </> ); } export default WhiteNavbar;
import _ from 'lodash'; import { database } from 'lib/db'; /** * @param {Object[]} tagObject the tag to be added. * @returns {boolean} tags number of tags modified */ export async function addTag(tagObject) { await database('tags').insert(tagObject); return true; } /** * Fetches direct meta data of tags from the tags database table * @param {string} queryField - Indicates which field to query by * @param {string[]} queryParams - Array of parameters of type queryField of articles to fetch * @param {string[]} columns - Which columns of the articles table to fetch * @returns {Promise<Object[]>} */ export function tagQuery(queryField, queryParams, columns) { // In order to be able to identify the rows we get back we need to include the queryField if (!columns.includes(queryField)) { columns.push(queryField); } return database .select(...columns) .from('tags') .whereIn(queryField, queryParams); } /** * Update tags given a json graph. * @param {Object} jsonGraphArg - the json graph to update */ export function updateTags(jsonGraphArg) { _.forEach(jsonGraphArg, async (tagObject, slug) => { await database('tags') .where('slug', '=', slug) .update(tagObject) .then(data => { if (data !== 1) { throw new Error(`Problems updating tag with slug: ${slug}`); } }) .catch(e => { throw e; }); }); }
/*! Summernote v0.8.12 | (c) 2013- Alan Hong and other contributors | MIT license */ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r=t();for(var o in r)("object"==typeof exports?exports:e)[o]=r[o]}}(window,function(){return function(e){var t={};function r(o){if(t[o])return t[o].exports;var n=t[o]={i:o,l:!1,exports:{}};return e[o].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=e,r.c=t,r.d=function(e,t,o){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:o})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(r.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)r.d(o,n,function(t){return e[t]}.bind(null,n));return o},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=49)}({49:function(e,t){var r;(r=jQuery).extend(r.summernote.lang,{"zh-TW":{font:{bold:"粗體",italic:"斜體",underline:"底線",clear:"清除格式",height:"行高",name:"字體",strikethrough:"刪除線",subscript:"下標",superscript:"上標",size:"字號"},image:{image:"圖片",insert:"插入圖片",resizeFull:"縮放至100%",resizeHalf:"縮放至 50%",resizeQuarter:"縮放至 25%",floatLeft:"靠左浮動",floatRight:"靠右浮動",floatNone:"取消浮動",shapeRounded:"形狀: 圓角",shapeCircle:"形狀: 圓",shapeThumbnail:"形狀: 縮略圖",shapeNone:"形狀: 無",dragImageHere:"將圖片拖曳至此處",dropImage:"Drop image or Text",selectFromFiles:"從本機上傳",maximumFileSize:"文件大小最大值",maximumFileSizeError:"文件大小超出最大值。",url:"圖片網址",remove:"移除圖片",original:"Original"},video:{video:"影片",videoLink:"影片連結",insert:"插入影片",url:"影片網址",providers:"(優酷, Instagram, DailyMotion, Youtube等)"},link:{link:"連結",insert:"插入連結",unlink:"取消連結",edit:"編輯連結",textToDisplay:"顯示文字",url:"連結網址",openInNewWindow:"在新視窗開啟"},table:{table:"表格",addRowAbove:"Add row above",addRowBelow:"Add row below",addColLeft:"Add column left",addColRight:"Add column right",delRow:"Delete row",delCol:"Delete column",delTable:"Delete table"},hr:{insert:"水平線"},style:{style:"樣式",p:"一般",blockquote:"引用區塊",pre:"程式碼區塊",h1:"標題 1",h2:"標題 2",h3:"標題 3",h4:"標題 4",h5:"標題 5",h6:"標題 6"},lists:{unordered:"項目清單",ordered:"編號清單"},options:{help:"幫助",fullscreen:"全螢幕",codeview:"原始碼"},paragraph:{paragraph:"段落",outdent:"取消縮排",indent:"增加縮排",left:"靠右對齊",center:"靠中對齊",right:"靠右對齊",justify:"左右對齊"},color:{recent:"字型顏色",more:"更多",background:"背景",foreground:"前景",transparent:"透明",setTransparent:"透明",reset:"重設",resetToDefault:"默認"},shortcut:{shortcuts:"快捷鍵",close:"關閉",textFormatting:"文字格式",action:"動作",paragraphFormatting:"段落格式",documentStyle:"文件格式",extraKeys:"額外按鍵"},help:{insertParagraph:"Insert Paragraph",undo:"Undoes the last command",redo:"Redoes the last command",tab:"Tab",untab:"Untab",bold:"Set a bold style",italic:"Set a italic style",underline:"Set a underline style",strikethrough:"Set a strikethrough style",removeFormat:"Clean a style",justifyLeft:"Set left align",justifyCenter:"Set center align",justifyRight:"Set right align",justifyFull:"Set full align",insertUnorderedList:"Toggle unordered list",insertOrderedList:"Toggle ordered list",outdent:"Outdent on current paragraph",indent:"Indent on current paragraph",formatPara:"Change current block's format as a paragraph(P tag)",formatH1:"Change current block's format as H1",formatH2:"Change current block's format as H2",formatH3:"Change current block's format as H3",formatH4:"Change current block's format as H4",formatH5:"Change current block's format as H5",formatH6:"Change current block's format as H6",insertHorizontalRule:"Insert horizontal rule","linkDialog.show":"Show Link Dialog"},history:{undo:"復原",redo:"取消復原"},specialChar:{specialChar:"SPECIAL CHARACTERS",select:"Select Special characters"}}})}})});
import { SET_DEVICES_LIST, SET_DEVICE_ITEM, SET_FORMDATA_CONNECT, SET_FORMDATA_DETAIL, SET_FORMDATA_REMARK, SET_FORMDATA_FILES, SET_FORMDATA_CLEAR, } from '../mutation-types' import weui from 'weui.js' import { fetchList, fetchDevice, maintainDevice, } from '@/api/devices' const state = { list: [], item: { images: {}, information: {}, parameters: [], }, formData: { connection: null, detail: null, remark: null, files: null, }, } const getters = { imageList: state => (key)=> { const images = state.item.images if (state.item.images.hasOwnProperty(key)) { return images[key] } else { return [] } }, information: state => state.item.information, parameters: state=> state.item.parameters, getItemById: state => (id) => { return state.list.find(dev => dev.id === id) }, validForm: state => { if (!state.formData.connection) { weui.topTips('请输入联系方式', { duration: 1500, }) return false } else if (!state.formData.detail) { weui.topTips('请输入故障描述', { duration: 1500, }) return false } return true }, getPostData: state => { const data = new URLSearchParams() const { connection, detail, remark, files } = state.formData data.append('name', connection.name) data.append('phone', connection.phone) data.append('descibe', detail) data.append('remark', remark) if (files && files.length) { for (let index = 0, len = files.length; index < len; index++) { data.append('file-image' + index, files) } } return data }, } const mutations = { [SET_DEVICES_LIST] (state, { list, }) { state.list = list }, [SET_DEVICE_ITEM] (state, { item, }) { state.item = item }, [SET_FORMDATA_CONNECT] (state, value) { state.formData.connection = value }, [SET_FORMDATA_DETAIL] (state, value) { state.formData.detail = value }, [SET_FORMDATA_REMARK] (state, value) { state.formData.remark = value }, [SET_FORMDATA_FILES] (state, value) { state.formData.files = value }, [SET_FORMDATA_CLEAR] (state) { Object.keys(state.formData).forEach(key => { state.formData[key] = null }) }, } const actions = { getDevices ({ commit, }) { fetchList().then(data => { commit('SET_DEVICES_LIST', { list: data.items, }) }) }, getDevice({ commit, }, id) { fetchDevice(id).then(device => { commit('SET_DEVICE_ITEM', { item: device, }) }) }, submit({ getters, commit, }) { return new Promise((resolve, reject) => { maintainDevice(getters.getPostData) .then(data => { commit(SET_FORMDATA_CLEAR) resolve(data) }) .catch(err => reject(err)) }) }, } export default { state, actions, getters, mutations, }
const lines = gets(); const salary = Number(lines); let percent; if (salary <= 400.0) { percent = 15.0; } else if (salary <= 800.0) { percent = 12.0; } else if (salary <= 1200.0) { percent = 10.0; } else if (salary <= 2000.0) { percent = 7.0; } else { percent = 4.0; } const reajust = (percent / 100.0) * salary; const newSalary = salary + reajust; console.log("Novo salario: " + newSalary.toFixed(2)); console.log("Reajuste ganho: " + reajust.toFixed(2)); console.log("Em percentual: " + percent + " %");
export const projects = [ { title: "Apvocate", type: "Business", client: "Apvocate Limited", description: "Built using React and React-Native and is actively maintained. Helping businesses to work with their loyal customers to achieve even more success through advocacy.", techStack: "React, React-Native, Redux, Firebase, Mocha, Cloud functions, Enzyme, Facebook API, Twitter API", extra: "Part of freeCodeCamp Organisation.", link: "https://apvocate.com", github: { name: null, githubHref: null } }, { title: "Eagles", type: "Remote", client: "Sagelodx LTD", description: "Desktop platform to help kids learn mordern computer science in a friendly hybrid visual and textbased environment .", techStack: "Electron, React, Redux, Canvas, Node.js, Expressjs, SQlite, Firebase", extra: null, link: "https://sagelodx.com", github: { name: null, githubHref: null } }, { title: "Last Man Standing", type: "Remote", client: "GGRA and Studio24", description: "Platform to aide the Annual Last Man Standing competition in an attempt to break the guiness book of world record", techStack: "PHP, Laravel, Javascript, Paystack SDK, Mysql", extra: null, link: "http://ggra.com.ng", github: { name: null, githubHref: null } }, { title: "LMS Support", type: "Remote", client: "GGRA", description: "Platform to support contestants competing for the lastman standing competition by making donations.", techStack: "PHP, Laravel, Javascript, Paystack SDK, Mysql", extra: null, link: "http://lmssupport.com.ng", github: { name: null, githubHref: null } }, { title: "Shriambey.com", type: "Remote", client: "Shir Jai Ambey Inc.", description: "Front End Developer for creating and managing website including layout selection, contact form, site organization & server deployment.", techStack: "Node.js, Expressjs, Angularjs, Bootstrap", extra: null, link: "http://www.shriambey.com/", github: { name: null, githubHref: null } }, { title: "Gatsby Starter CeeVee", type: "Open Source", client: null, description: "Gatsby Starter Kit/Theme, single-page, based on the Ceevee site template, design by Styleshout. Responsive Design.", techStack: "Reactjs, Gatsbyjs", extra: null, link: "http://gatsby-starter-ceevee.surge.sh/", github: { name: "Github", githubHref: "https://github.com/amandeepmittal/gatsby-starter-ceevee" } }, { title: "Gatsby Starter Product Guy", type: "Open Source", client: null, description: "Gatsby Starter Kit/Theme, single-page, for Makers and Product Hunters. Using Typography.js easy to switch fonts. Responsive Design.", techStack: "Reactjs, Gatsbyjs, GraphQL", extra: null, link: "http://gatsby-starter-product-guy.surge.sh/", github: { name: "Github", githubHref: "https://github.com/amandeepmittal/gatsby-starter-product-guy" } } ]; export const sideProjects = [ { title: "Portfolio v3", type: "Open Source", client: null, description: "Responsive Portfolio Wesbite Desgined using Gatsbyjs, Reactjs and 💅 styled-components. Currently, using it as a personal website.", techStack: "Reactjs, Gatsbyjs, styled-components", extra: null, link: "http://portfolio-v3.surge.sh/", github: { name: "Github", githubHref: "https://github.com/amandeepmittal/gatsby-portfolio-v3" } }, { title: "Portfolio v2", type: "Open Source", client: null, description: "Responsive Portfolio Wesbite Desgined using Materialize CSS. Previously used it as a personal website.", techStack: "HTML, Materialize CSS", extra: null, link: "http://portfolio-v2.surge.sh/", github: { name: "Github", githubHref: "https://github.com/amandeepmittal/portfolio-v2" } }, { title: "Awesome-Vulcanjs", type: "Open Source", client: null, description: "A Directory listing Vulcanjs related resources. Helpful if you are getting started.", techStack: "Markdown", extra: null, link: "http://vulcanjs.org/", github: { name: "Github", githubHref: "https://github.com/amandeepmittal/awesome-vulcan" } }, { title: "Awesome-Twitter-Bots", type: "Open Source", client: null, description: "A Directory listing Twitter Bots built using Node.js.", techStack: "Markdown", extra: null, link: "https://github.com/amandeepmittal/awesome-twitter-bots", github: { name: "Github", githubHref: "https://github.com/amandeepmittal/awesome-twitter-bots" } }, { title: "Bitli", type: "Open Source", client: null, description: "Fullstack Application. A URL Shortner Service.", techStack: "Meteorjs, Reactjs, MongoDB, Bootstrap, Heroku", extra: null, link: "http://bitli.herokuapp.com/", github: { name: "Github", githubHref: "https://github.com/amandeepmittal/meteor-bitli" } }, { title: "MEAN Stack News Twitter Bot", type: "Open Source", client: null, description: "Twitter Bot built using Node.js and actively maintained.", techStack: "Node.js, Twitter API", extra: "This twitter bot shares everything related to MEAN Stack and Ionic Framework on the basis of pre-defined hashtags and user handlers.", link: "https://twitter.com/nodejstweet", github: { name: "Github", githubHref: "https://github.com/amandeepmittal/nodejs-tweet" } }, { title: "React Youtube Search", type: "Open Source", client: null, description: "Youtube API search with React. Used Github-Pages to deploy.", techStack: "Reactjs, YouTube API", extra: null, link: "http://www.amanhimself.me/react-youtube-search/", github: { name: "Github", githubHref: "https://github.com/amandeepmittal/react-youtube-search" } } ]; export const OSS = [ { link: "https://github.com/nodejs/nodejs.org/commits?author=amandeepmittal", description: "Contributor to Node.js Foundation's website project to form a self-publishing, community-managed version." }, { link: "https://github.com/freeCodeCamp/100DaysOfCode-twitter-bot", description: "Creator of freeCodeCamp's #100DaysOfCode campaign Twitter bot." }, { link: "http://www.amanhimself.me/codestats.net/users/amanmittal", description: "Developed command line utility for Code::Stats." }, { link: "https://guide.freecodecamp.org/", description: "Contributor to freeCodeCamp Guides." } ];
var _ = require('lodash'); var $ = require('jquery'); jQuery = $; // this is for old backward compatability of bootrap modules var ko = require('knockout'); var dndPageScroll = require('dnd-page-scroll'); require('./bootstrap'); require('./jquery-ui'); require('./knockout-bindings'); var components = require('ungit-components'); var Server = require('./server'); var programEvents = require('ungit-program-events'); var navigation = require('ungit-navigation'); var storage = require('ungit-storage'); var adBlocker = require('just-detect-adblock'); // Request animation frame polyfill and init tooltips (function () { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; window.cancelRequestAnimationFrame = window[vendors[x] + 'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function (callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function () { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function (id) { clearTimeout(id); }; $(document).tooltip({ selector: '[data-toggle="tooltip"]', }); })(); ko.bindingHandlers.autocomplete = { init: (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) => { const setAutoCompleteOptions = (sources) => { $(element) .autocomplete({ classes: { 'ui-autocomplete': 'dropdown-menu', }, source: sources, minLength: 0, messages: { noResults: '', results: () => {}, }, }) .data('ui-autocomplete')._renderItem = function (ul, item) { return $('<li></li>').append($('<a>').text(item.label)).appendTo(ul); }; }; const handleKeyEvent = (event) => { const value = $(element).val(); const lastChar = value.slice(-1); if (lastChar == ungit.config.fileSeparator) { // When file separator is entered, list what is in given path, and rest auto complete options server .getPromise('/fs/listDirectories', { term: value }) .then((directoryList) => { const currentDir = directoryList.shift(); $(element).val( currentDir.endsWith(ungit.config.fileSeparator) ? currentDir : currentDir + ungit.config.fileSeparator ); setAutoCompleteOptions(directoryList); $(element).autocomplete('search', value); }) .catch((err) => { if ( !err.errorSummary.startsWith('ENOENT: no such file or directory') && err.errorCode !== 'read-dir-failed' ) { throw err; } }); } else if (event.keyCode === 13) { // enter key is struck, navigate to the path event.preventDefault(); navigation.browseTo(`repository?path=${encodeURIComponent(value)}`); } else if (value === '' && storage.getItem('repositories')) { // if path is emptied out, show save path options const folderNames = JSON.parse(storage.getItem('repositories')).map((value) => { return { value: value, label: value.substring(value.lastIndexOf(ungit.config.fileSeparator) + 1), }; }); setAutoCompleteOptions(folderNames); $(element).autocomplete('search', ''); } return true; }; ko.utils.registerEventHandler(element, 'keyup', _.debounce(handleKeyEvent, 100)); }, }; // Used to catch when a user was tabbed away and re-visits the page. // If fs.watch worked better on Windows (i.e. on subdirectories) we wouldn't need this (function detectReActivity() { var lastMoved = Date.now(); document.addEventListener('mousemove', function () { // If the user didn't move for 3 sec and then moved again, it's likely it's a tab-back if (Date.now() - lastMoved > 3000) { console.log('Fire change event due to re-activity'); programEvents.dispatch({ event: 'working-tree-changed' }); } lastMoved = Date.now(); }); })(); function WindowTitle() { this.path = 'ungit'; this.crash = false; } WindowTitle.prototype.update = function () { var title = this.path .replace(/\\/g, '/') .split('/') .filter(function (x) { return x; }) .reverse() .join(' < '); if (this.crash) title = ':( ungit crash ' + title; document.title = title; }; var windowTitle = new WindowTitle(); windowTitle.update(); var AppContainerViewModel = function () { this.content = ko.observable(); }; exports.AppContainerViewModel = AppContainerViewModel; AppContainerViewModel.prototype.templateChooser = function (data) { if (!data) return ''; return data.template; }; var app, appContainer, server; exports.start = function () { server = new Server(); appContainer = new AppContainerViewModel(); app = components.create('app', { appContainer: appContainer, server: server }); programEvents.add(function (event) { if (event.event == 'disconnected' || event.event == 'git-crash-error') { console.error(`ungit crash: ${event.event}`, event.error); const err = event.event == 'disconnected' && adBlocker.isDetected() ? 'adblocker' : event.event; appContainer.content(components.create('crash', err)); windowTitle.crash = true; windowTitle.update(); } else if (event.event == 'connected') { appContainer.content(app); windowTitle.crash = false; windowTitle.update(); } if (app.onProgramEvent) { app.onProgramEvent(event); } }); if (ungit.config.authentication) { var authenticationScreen = components.create('login', { server: server }); appContainer.content(authenticationScreen); authenticationScreen.loggedIn.add(function () { server.initSocket(); }); } else { server.initSocket(); } Raven.TraceKit.report.subscribe(function (event, err) { programEvents.dispatch({ event: 'raven-crash', error: err || event.event }); }); var prevTimestamp = 0; var updateAnimationFrame = function (timestamp) { var delta = timestamp - prevTimestamp; prevTimestamp = timestamp; if (app.updateAnimationFrame) app.updateAnimationFrame(delta); window.requestAnimationFrame(updateAnimationFrame); }; window.requestAnimationFrame(updateAnimationFrame); ko.applyBindings(appContainer); // routing navigation.crossroads.addRoute('/', function () { app.content(components.create('home', { app: app })); windowTitle.path = 'ungit'; windowTitle.update(); }); navigation.crossroads.addRoute('/repository{?query}', function (query) { programEvents.dispatch({ event: 'navigated-to-path', path: query.path }); app.content(components.create('path', { server: server, path: query.path })); windowTitle.path = query.path; windowTitle.update(); }); navigation.init(); }; $(document).ready(function () { dndPageScroll.default(); // Automatic page scrolling on drag-n-drop: http://www.planbox.com/blog/news/updates/html5-drag-and-drop-scrolling-the-page.html });
THREE.TransformControls = function (camera, domElement) { if (domElement === undefined) { console.warn( 'THREE.TransformControls: The second parameter "domElement" is now mandatory.' ); domElement = document; } THREE.Object3D.call(this); this.visible = false; this.domElement = domElement; var _gizmo = new THREE.TransformControlsGizmo(); this.add(_gizmo); var _plane = new THREE.TransformControlsPlane(); this.add(_plane); var scope = this; // Define properties with getters/setter // Setting the defined property will automatically trigger change event // Defined properties are passed down to gizmo and plane defineProperty("camera", camera); defineProperty("object", undefined); defineProperty("enabled", true); defineProperty("axis", null); defineProperty("mode", "translate"); defineProperty("translationSnap", null); defineProperty("rotationSnap", null); defineProperty("scaleSnap", null); defineProperty("space", "world"); defineProperty("size", 1); defineProperty("dragging", false); defineProperty("showX", true); defineProperty("showY", true); defineProperty("showZ", true); var changeEvent = { type: "change" }; var mouseDownEvent = { type: "mouseDown" }; var mouseUpEvent = { type: "mouseUp", mode: scope.mode }; var objectChangeEvent = { type: "objectChange" }; // Reusable utility variables var raycaster = new THREE.Raycaster(); function intersectObjectWithRay(object, raycaster, includeInvisible) { var allIntersections = raycaster.intersectObject(object, true); for (var i = 0; i < allIntersections.length; i++) { if (allIntersections[i].object.visible || includeInvisible) { return allIntersections[i]; } } return false; } var _tempVector = new THREE.Vector3(); var _tempVector2 = new THREE.Vector3(); var _tempQuaternion = new THREE.Quaternion(); var _unit = { X: new THREE.Vector3(1, 0, 0), Y: new THREE.Vector3(0, 1, 0), Z: new THREE.Vector3(0, 0, 1), }; var pointStart = new THREE.Vector3(); var pointEnd = new THREE.Vector3(); var offset = new THREE.Vector3(); var rotationAxis = new THREE.Vector3(); var startNorm = new THREE.Vector3(); var endNorm = new THREE.Vector3(); var rotationAngle = 0; var cameraPosition = new THREE.Vector3(); var cameraQuaternion = new THREE.Quaternion(); var cameraScale = new THREE.Vector3(); var parentPosition = new THREE.Vector3(); var parentQuaternion = new THREE.Quaternion(); var parentQuaternionInv = new THREE.Quaternion(); var parentScale = new THREE.Vector3(); var worldPositionStart = new THREE.Vector3(); var worldQuaternionStart = new THREE.Quaternion(); var worldScaleStart = new THREE.Vector3(); var worldPosition = new THREE.Vector3(); var worldQuaternion = new THREE.Quaternion(); var worldQuaternionInv = new THREE.Quaternion(); var worldScale = new THREE.Vector3(); var eye = new THREE.Vector3(); var positionStart = new THREE.Vector3(); var quaternionStart = new THREE.Quaternion(); var scaleStart = new THREE.Vector3(); // TODO: remove properties unused in plane and gizmo defineProperty("worldPosition", worldPosition); defineProperty("worldPositionStart", worldPositionStart); defineProperty("worldQuaternion", worldQuaternion); defineProperty("worldQuaternionStart", worldQuaternionStart); defineProperty("cameraPosition", cameraPosition); defineProperty("cameraQuaternion", cameraQuaternion); defineProperty("pointStart", pointStart); defineProperty("pointEnd", pointEnd); defineProperty("rotationAxis", rotationAxis); defineProperty("rotationAngle", rotationAngle); defineProperty("eye", eye); { domElement.addEventListener("pointerdown", onPointerDown, false); domElement.addEventListener("pointermove", onPointerHover, false); scope.domElement.ownerDocument.addEventListener( "pointerup", onPointerUp, false ); } this.dispose = function () { domElement.removeEventListener("pointerdown", onPointerDown); domElement.removeEventListener("pointermove", onPointerHover); scope.domElement.ownerDocument.removeEventListener( "pointermove", onPointerMove ); scope.domElement.ownerDocument.removeEventListener( "pointerup", onPointerUp ); this.traverse(function (child) { if (child.geometry) child.geometry.dispose(); if (child.material) child.material.dispose(); }); }; // Set current object this.attach = function (object) { this.object = object; this.visible = true; return this; }; // Detatch from object this.detach = function () { this.object = undefined; this.visible = false; this.axis = null; return this; }; // Defined getter, setter and store for a property function defineProperty(propName, defaultValue) { var propValue = defaultValue; Object.defineProperty(scope, propName, { get: function () { return propValue !== undefined ? propValue : defaultValue; }, set: function (value) { if (propValue !== value) { propValue = value; _plane[propName] = value; _gizmo[propName] = value; scope.dispatchEvent({ type: propName + "-changed", value: value }); scope.dispatchEvent(changeEvent); } }, }); scope[propName] = defaultValue; _plane[propName] = defaultValue; _gizmo[propName] = defaultValue; } // updateMatrixWorld updates key transformation variables this.updateMatrixWorld = function () { if (this.object !== undefined) { this.object.updateMatrixWorld(); if (this.object.parent === null) { console.error( "TransformControls: The attached 3D object must be a part of the scene graph." ); } else { this.object.parent.matrixWorld.decompose( parentPosition, parentQuaternion, parentScale ); } this.object.matrixWorld.decompose( worldPosition, worldQuaternion, worldScale ); parentQuaternionInv.copy(parentQuaternion).invert(); worldQuaternionInv.copy(worldQuaternion).invert(); } this.camera.updateMatrixWorld(); this.camera.matrixWorld.decompose( cameraPosition, cameraQuaternion, cameraScale ); eye.copy(cameraPosition).sub(worldPosition).normalize(); THREE.Object3D.prototype.updateMatrixWorld.call(this); }; this.pointerHover = function (pointer) { if (this.object === undefined || this.dragging === true) return; raycaster.setFromCamera(pointer, this.camera); var intersect = intersectObjectWithRay(_gizmo.picker[this.mode], raycaster); if (intersect) { this.axis = intersect.object.name; } else { this.axis = null; } }; this.pointerDown = function (pointer) { if ( this.object === undefined || this.dragging === true || pointer.button !== 0 ) return; if (this.axis !== null) { raycaster.setFromCamera(pointer, this.camera); var planeIntersect = intersectObjectWithRay(_plane, raycaster, true); if (planeIntersect) { var space = this.space; if (this.mode === "scale") { space = "local"; } else if ( this.axis === "E" || this.axis === "XYZE" || this.axis === "XYZ" ) { space = "world"; } if (space === "local" && this.mode === "rotate") { var snap = this.rotationSnap; if (this.axis === "X" && snap) this.object.rotation.x = Math.round(this.object.rotation.x / snap) * snap; if (this.axis === "Y" && snap) this.object.rotation.y = Math.round(this.object.rotation.y / snap) * snap; if (this.axis === "Z" && snap) this.object.rotation.z = Math.round(this.object.rotation.z / snap) * snap; } this.object.updateMatrixWorld(); this.object.parent.updateMatrixWorld(); positionStart.copy(this.object.position); quaternionStart.copy(this.object.quaternion); scaleStart.copy(this.object.scale); this.object.matrixWorld.decompose( worldPositionStart, worldQuaternionStart, worldScaleStart ); pointStart.copy(planeIntersect.point).sub(worldPositionStart); } this.dragging = true; mouseDownEvent.mode = this.mode; this.dispatchEvent(mouseDownEvent); } }; this.pointerMove = function (pointer) { var axis = this.axis; var mode = this.mode; var object = this.object; var space = this.space; if (mode === "scale") { space = "local"; } else if (axis === "E" || axis === "XYZE" || axis === "XYZ") { space = "world"; } if ( object === undefined || axis === null || this.dragging === false || pointer.button !== -1 ) return; raycaster.setFromCamera(pointer, this.camera); var planeIntersect = intersectObjectWithRay(_plane, raycaster, true); if (!planeIntersect) return; pointEnd.copy(planeIntersect.point).sub(worldPositionStart); if (mode === "translate") { // Apply translate offset.copy(pointEnd).sub(pointStart); if (space === "local" && axis !== "XYZ") { offset.applyQuaternion(worldQuaternionInv); } if (axis.indexOf("X") === -1) offset.x = 0; if (axis.indexOf("Y") === -1) offset.y = 0; if (axis.indexOf("Z") === -1) offset.z = 0; if (space === "local" && axis !== "XYZ") { offset.applyQuaternion(quaternionStart).divide(parentScale); } else { offset.applyQuaternion(parentQuaternionInv).divide(parentScale); } object.position.copy(offset).add(positionStart); // Apply translation snap if (this.translationSnap) { if (space === "local") { object.position.applyQuaternion( _tempQuaternion.copy(quaternionStart).invert() ); if (axis.search("X") !== -1) { object.position.x = Math.round(object.position.x / this.translationSnap) * this.translationSnap; } if (axis.search("Y") !== -1) { object.position.y = Math.round(object.position.y / this.translationSnap) * this.translationSnap; } if (axis.search("Z") !== -1) { object.position.z = Math.round(object.position.z / this.translationSnap) * this.translationSnap; } object.position.applyQuaternion(quaternionStart); } if (space === "world") { if (object.parent) { object.position.add( _tempVector.setFromMatrixPosition(object.parent.matrixWorld) ); } if (axis.search("X") !== -1) { object.position.x = Math.round(object.position.x / this.translationSnap) * this.translationSnap; } if (axis.search("Y") !== -1) { object.position.y = Math.round(object.position.y / this.translationSnap) * this.translationSnap; } if (axis.search("Z") !== -1) { object.position.z = Math.round(object.position.z / this.translationSnap) * this.translationSnap; } if (object.parent) { object.position.sub( _tempVector.setFromMatrixPosition(object.parent.matrixWorld) ); } } } } else if (mode === "scale") { if (axis.search("XYZ") !== -1) { var d = pointEnd.length() / pointStart.length(); if (pointEnd.dot(pointStart) < 0) d *= -1; _tempVector2.set(d, d, d); } else { _tempVector.copy(pointStart); _tempVector2.copy(pointEnd); _tempVector.applyQuaternion(worldQuaternionInv); _tempVector2.applyQuaternion(worldQuaternionInv); _tempVector2.divide(_tempVector); if (axis.search("X") === -1) { _tempVector2.x = 1; } if (axis.search("Y") === -1) { _tempVector2.y = 1; } if (axis.search("Z") === -1) { _tempVector2.z = 1; } } // Apply scale object.scale.copy(scaleStart).multiply(_tempVector2); if (this.scaleSnap) { if (axis.search("X") !== -1) { object.scale.x = Math.round(object.scale.x / this.scaleSnap) * this.scaleSnap || this.scaleSnap; } if (axis.search("Y") !== -1) { object.scale.y = Math.round(object.scale.y / this.scaleSnap) * this.scaleSnap || this.scaleSnap; } if (axis.search("Z") !== -1) { object.scale.z = Math.round(object.scale.z / this.scaleSnap) * this.scaleSnap || this.scaleSnap; } } } else if (mode === "rotate") { offset.copy(pointEnd).sub(pointStart); var ROTATION_SPEED = 5 / worldPosition.distanceTo( _tempVector.setFromMatrixPosition(this.camera.matrixWorld) ); if (axis === "E") { rotationAxis.copy(eye); rotationAngle = pointEnd.angleTo(pointStart); startNorm.copy(pointStart).normalize(); endNorm.copy(pointEnd).normalize(); rotationAngle *= endNorm.cross(startNorm).dot(eye) < 0 ? 1 : -1; } else if (axis === "XYZE") { rotationAxis.copy(offset).cross(eye).normalize(); rotationAngle = offset.dot(_tempVector.copy(rotationAxis).cross(this.eye)) * ROTATION_SPEED; } else if (axis === "X" || axis === "Y" || axis === "Z") { rotationAxis.copy(_unit[axis]); _tempVector.copy(_unit[axis]); if (space === "local") { _tempVector.applyQuaternion(worldQuaternion); } rotationAngle = offset.dot(_tempVector.cross(eye).normalize()) * ROTATION_SPEED; } // Apply rotation snap if (this.rotationSnap) rotationAngle = Math.round(rotationAngle / this.rotationSnap) * this.rotationSnap; this.rotationAngle = rotationAngle; // Apply rotate if (space === "local" && axis !== "E" && axis !== "XYZE") { object.quaternion.copy(quaternionStart); object.quaternion .multiply( _tempQuaternion.setFromAxisAngle(rotationAxis, rotationAngle) ) .normalize(); } else { rotationAxis.applyQuaternion(parentQuaternionInv); object.quaternion.copy( _tempQuaternion.setFromAxisAngle(rotationAxis, rotationAngle) ); object.quaternion.multiply(quaternionStart).normalize(); } } this.dispatchEvent(changeEvent); this.dispatchEvent(objectChangeEvent); }; this.pointerUp = function (pointer) { if (pointer.button !== 0) return; if (this.dragging && this.axis !== null) { mouseUpEvent.mode = this.mode; this.dispatchEvent(mouseUpEvent); } this.dragging = false; this.axis = null; }; // normalize mouse / touch pointer and remap {x,y} to view space. function getPointer(event) { if (scope.domElement.ownerDocument.pointerLockElement) { return { x: 0, y: 0, button: event.button, }; } else { var pointer = event.changedTouches ? event.changedTouches[0] : event; var rect = domElement.getBoundingClientRect(); return { x: ((pointer.clientX - rect.left) / rect.width) * 2 - 1, y: (-(pointer.clientY - rect.top) / rect.height) * 2 + 1, button: event.button, }; } } // mouse / touch event handlers function onPointerHover(event) { if (!scope.enabled) return; switch (event.pointerType) { case "mouse": case "pen": scope.pointerHover(getPointer(event)); break; } } function onPointerDown(event) { if (!scope.enabled) return; scope.domElement.style.touchAction = "none"; // disable touch scroll scope.domElement.ownerDocument.addEventListener( "pointermove", onPointerMove, false ); scope.pointerHover(getPointer(event)); scope.pointerDown(getPointer(event)); } function onPointerMove(event) { if (!scope.enabled) return; scope.pointerMove(getPointer(event)); } function onPointerUp(event) { if (!scope.enabled) return; scope.domElement.style.touchAction = ""; scope.domElement.ownerDocument.removeEventListener( "pointermove", onPointerMove, false ); scope.pointerUp(getPointer(event)); } // TODO: deprecate this.getMode = function () { return scope.mode; }; this.setMode = function (mode) { scope.mode = mode; }; this.setTranslationSnap = function (translationSnap) { scope.translationSnap = translationSnap; }; this.setRotationSnap = function (rotationSnap) { scope.rotationSnap = rotationSnap; }; this.setScaleSnap = function (scaleSnap) { scope.scaleSnap = scaleSnap; }; this.setSize = function (size) { scope.size = size; }; this.setSpace = function (space) { scope.space = space; }; this.update = function () { console.warn( "THREE.TransformControls: update function has no more functionality and therefore has been deprecated." ); }; }; THREE.TransformControls.prototype = Object.assign( Object.create(THREE.Object3D.prototype), { constructor: THREE.TransformControls, isTransformControls: true, } ); THREE.TransformControlsGizmo = function () { "use strict"; THREE.Object3D.call(this); this.type = "TransformControlsGizmo"; // shared materials var gizmoMaterial = new THREE.MeshBasicMaterial({ depthTest: false, depthWrite: false, transparent: true, side: THREE.DoubleSide, fog: false, toneMapped: false, }); var gizmoLineMaterial = new THREE.LineBasicMaterial({ depthTest: false, depthWrite: false, transparent: true, linewidth: 1, fog: false, toneMapped: false, }); // Make unique material for each axis/color var matInvisible = gizmoMaterial.clone(); matInvisible.opacity = 0.15; var matHelper = gizmoMaterial.clone(); matHelper.opacity = 0.33; var matRed = gizmoMaterial.clone(); matRed.color.set(0xff0000); var matGreen = gizmoMaterial.clone(); matGreen.color.set(0x00ff00); var matBlue = gizmoMaterial.clone(); matBlue.color.set(0x0000ff); var matWhiteTransparent = gizmoMaterial.clone(); matWhiteTransparent.opacity = 0.25; var matYellowTransparent = matWhiteTransparent.clone(); matYellowTransparent.color.set(0xffff00); var matCyanTransparent = matWhiteTransparent.clone(); matCyanTransparent.color.set(0x00ffff); var matMagentaTransparent = matWhiteTransparent.clone(); matMagentaTransparent.color.set(0xff00ff); var matYellow = gizmoMaterial.clone(); matYellow.color.set(0xffff00); var matLineRed = gizmoLineMaterial.clone(); matLineRed.color.set(0xff0000); var matLineGreen = gizmoLineMaterial.clone(); matLineGreen.color.set(0x00ff00); var matLineBlue = gizmoLineMaterial.clone(); matLineBlue.color.set(0x0000ff); var matLineCyan = gizmoLineMaterial.clone(); matLineCyan.color.set(0x00ffff); var matLineMagenta = gizmoLineMaterial.clone(); matLineMagenta.color.set(0xff00ff); var matLineYellow = gizmoLineMaterial.clone(); matLineYellow.color.set(0xffff00); var matLineGray = gizmoLineMaterial.clone(); matLineGray.color.set(0x787878); var matLineYellowTransparent = matLineYellow.clone(); matLineYellowTransparent.opacity = 0.25; // reusable geometry var arrowGeometry = new THREE.CylinderBufferGeometry( 0, 0.05, 0.2, 12, 1, false ); var scaleHandleGeometry = new THREE.BoxBufferGeometry(0.125, 0.125, 0.125); var lineGeometry = new THREE.BufferGeometry(); lineGeometry.setAttribute( "position", new THREE.Float32BufferAttribute([0, 0, 0, 1, 0, 0], 3) ); var CircleGeometry = function (radius, arc) { var geometry = new THREE.BufferGeometry(); var vertices = []; for (var i = 0; i <= 64 * arc; ++i) { vertices.push( 0, Math.cos((i / 32) * Math.PI) * radius, Math.sin((i / 32) * Math.PI) * radius ); } geometry.setAttribute( "position", new THREE.Float32BufferAttribute(vertices, 3) ); return geometry; }; // Special geometry for transform helper. If scaled with position vector it spans from [0,0,0] to position var TranslateHelperGeometry = function () { var geometry = new THREE.BufferGeometry(); geometry.setAttribute( "position", new THREE.Float32BufferAttribute([0, 0, 0, 1, 1, 1], 3) ); return geometry; }; // Gizmo definitions - custom hierarchy definitions for setupGizmo() function var gizmoTranslate = { X: [ [ new THREE.Mesh(arrowGeometry, matRed), [1, 0, 0], [0, 0, -Math.PI / 2], null, "fwd", ], [ new THREE.Mesh(arrowGeometry, matRed), [1, 0, 0], [0, 0, Math.PI / 2], null, "bwd", ], [new THREE.Line(lineGeometry, matLineRed)], ], Y: [ [new THREE.Mesh(arrowGeometry, matGreen), [0, 1, 0], null, null, "fwd"], [ new THREE.Mesh(arrowGeometry, matGreen), [0, 1, 0], [Math.PI, 0, 0], null, "bwd", ], [new THREE.Line(lineGeometry, matLineGreen), null, [0, 0, Math.PI / 2]], ], Z: [ [ new THREE.Mesh(arrowGeometry, matBlue), [0, 0, 1], [Math.PI / 2, 0, 0], null, "fwd", ], [ new THREE.Mesh(arrowGeometry, matBlue), [0, 0, 1], [-Math.PI / 2, 0, 0], null, "bwd", ], [new THREE.Line(lineGeometry, matLineBlue), null, [0, -Math.PI / 2, 0]], ], XYZ: [ [ new THREE.Mesh( new THREE.OctahedronBufferGeometry(0.1, 0), matWhiteTransparent.clone() ), [0, 0, 0], [0, 0, 0], ], ], XY: [ [ new THREE.Mesh( new THREE.PlaneBufferGeometry(0.295, 0.295), matYellowTransparent.clone() ), [0.15, 0.15, 0], ], [ new THREE.Line(lineGeometry, matLineYellow), [0.18, 0.3, 0], null, [0.125, 1, 1], ], [ new THREE.Line(lineGeometry, matLineYellow), [0.3, 0.18, 0], [0, 0, Math.PI / 2], [0.125, 1, 1], ], ], YZ: [ [ new THREE.Mesh( new THREE.PlaneBufferGeometry(0.295, 0.295), matCyanTransparent.clone() ), [0, 0.15, 0.15], [0, Math.PI / 2, 0], ], [ new THREE.Line(lineGeometry, matLineCyan), [0, 0.18, 0.3], [0, 0, Math.PI / 2], [0.125, 1, 1], ], [ new THREE.Line(lineGeometry, matLineCyan), [0, 0.3, 0.18], [0, -Math.PI / 2, 0], [0.125, 1, 1], ], ], XZ: [ [ new THREE.Mesh( new THREE.PlaneBufferGeometry(0.295, 0.295), matMagentaTransparent.clone() ), [0.15, 0, 0.15], [-Math.PI / 2, 0, 0], ], [ new THREE.Line(lineGeometry, matLineMagenta), [0.18, 0, 0.3], null, [0.125, 1, 1], ], [ new THREE.Line(lineGeometry, matLineMagenta), [0.3, 0, 0.18], [0, -Math.PI / 2, 0], [0.125, 1, 1], ], ], }; var pickerTranslate = { X: [ [ new THREE.Mesh( new THREE.CylinderBufferGeometry(0.2, 0, 1, 4, 1, false), matInvisible ), [0.6, 0, 0], [0, 0, -Math.PI / 2], ], ], Y: [ [ new THREE.Mesh( new THREE.CylinderBufferGeometry(0.2, 0, 1, 4, 1, false), matInvisible ), [0, 0.6, 0], ], ], Z: [ [ new THREE.Mesh( new THREE.CylinderBufferGeometry(0.2, 0, 1, 4, 1, false), matInvisible ), [0, 0, 0.6], [Math.PI / 2, 0, 0], ], ], XYZ: [ [ new THREE.Mesh( new THREE.OctahedronBufferGeometry(0.2, 0), matInvisible ), ], ], XY: [ [ new THREE.Mesh(new THREE.PlaneBufferGeometry(0.4, 0.4), matInvisible), [0.2, 0.2, 0], ], ], YZ: [ [ new THREE.Mesh(new THREE.PlaneBufferGeometry(0.4, 0.4), matInvisible), [0, 0.2, 0.2], [0, Math.PI / 2, 0], ], ], XZ: [ [ new THREE.Mesh(new THREE.PlaneBufferGeometry(0.4, 0.4), matInvisible), [0.2, 0, 0.2], [-Math.PI / 2, 0, 0], ], ], }; var helperTranslate = { START: [ [ new THREE.Mesh(new THREE.OctahedronBufferGeometry(0.01, 2), matHelper), null, null, null, "helper", ], ], END: [ [ new THREE.Mesh(new THREE.OctahedronBufferGeometry(0.01, 2), matHelper), null, null, null, "helper", ], ], DELTA: [ [ new THREE.Line(TranslateHelperGeometry(), matHelper), null, null, null, "helper", ], ], X: [ [ new THREE.Line(lineGeometry, matHelper.clone()), [-1e3, 0, 0], null, [1e6, 1, 1], "helper", ], ], Y: [ [ new THREE.Line(lineGeometry, matHelper.clone()), [0, -1e3, 0], [0, 0, Math.PI / 2], [1e6, 1, 1], "helper", ], ], Z: [ [ new THREE.Line(lineGeometry, matHelper.clone()), [0, 0, -1e3], [0, -Math.PI / 2, 0], [1e6, 1, 1], "helper", ], ], }; var gizmoRotate = { X: [ [new THREE.Line(CircleGeometry(1, 0.5), matLineRed)], [ new THREE.Mesh(new THREE.OctahedronBufferGeometry(0.04, 0), matRed), [0, 0, 0.99], null, [1, 3, 1], ], ], Y: [ [ new THREE.Line(CircleGeometry(1, 0.5), matLineGreen), null, [0, 0, -Math.PI / 2], ], [ new THREE.Mesh(new THREE.OctahedronBufferGeometry(0.04, 0), matGreen), [0, 0, 0.99], null, [3, 1, 1], ], ], Z: [ [ new THREE.Line(CircleGeometry(1, 0.5), matLineBlue), null, [0, Math.PI / 2, 0], ], [ new THREE.Mesh(new THREE.OctahedronBufferGeometry(0.04, 0), matBlue), [0.99, 0, 0], null, [1, 3, 1], ], ], E: [ [ new THREE.Line(CircleGeometry(1.25, 1), matLineYellowTransparent), null, [0, Math.PI / 2, 0], ], [ new THREE.Mesh( new THREE.CylinderBufferGeometry(0.03, 0, 0.15, 4, 1, false), matLineYellowTransparent ), [1.17, 0, 0], [0, 0, -Math.PI / 2], [1, 1, 0.001], ], [ new THREE.Mesh( new THREE.CylinderBufferGeometry(0.03, 0, 0.15, 4, 1, false), matLineYellowTransparent ), [-1.17, 0, 0], [0, 0, Math.PI / 2], [1, 1, 0.001], ], [ new THREE.Mesh( new THREE.CylinderBufferGeometry(0.03, 0, 0.15, 4, 1, false), matLineYellowTransparent ), [0, -1.17, 0], [Math.PI, 0, 0], [1, 1, 0.001], ], [ new THREE.Mesh( new THREE.CylinderBufferGeometry(0.03, 0, 0.15, 4, 1, false), matLineYellowTransparent ), [0, 1.17, 0], [0, 0, 0], [1, 1, 0.001], ], ], XYZE: [ [ new THREE.Line(CircleGeometry(1, 1), matLineGray), null, [0, Math.PI / 2, 0], ], ], }; var helperRotate = { AXIS: [ [ new THREE.Line(lineGeometry, matHelper.clone()), [-1e3, 0, 0], null, [1e6, 1, 1], "helper", ], ], }; var pickerRotate = { X: [ [ new THREE.Mesh( new THREE.TorusBufferGeometry(1, 0.1, 4, 24), matInvisible ), [0, 0, 0], [0, -Math.PI / 2, -Math.PI / 2], ], ], Y: [ [ new THREE.Mesh( new THREE.TorusBufferGeometry(1, 0.1, 4, 24), matInvisible ), [0, 0, 0], [Math.PI / 2, 0, 0], ], ], Z: [ [ new THREE.Mesh( new THREE.TorusBufferGeometry(1, 0.1, 4, 24), matInvisible ), [0, 0, 0], [0, 0, -Math.PI / 2], ], ], E: [ [ new THREE.Mesh( new THREE.TorusBufferGeometry(1.25, 0.1, 2, 24), matInvisible ), ], ], XYZE: [ [ new THREE.Mesh( new THREE.SphereBufferGeometry(0.7, 10, 8), matInvisible ), ], ], }; var gizmoScale = { X: [ [ new THREE.Mesh(scaleHandleGeometry, matRed), [0.8, 0, 0], [0, 0, -Math.PI / 2], ], [new THREE.Line(lineGeometry, matLineRed), null, null, [0.8, 1, 1]], ], Y: [ [new THREE.Mesh(scaleHandleGeometry, matGreen), [0, 0.8, 0]], [ new THREE.Line(lineGeometry, matLineGreen), null, [0, 0, Math.PI / 2], [0.8, 1, 1], ], ], Z: [ [ new THREE.Mesh(scaleHandleGeometry, matBlue), [0, 0, 0.8], [Math.PI / 2, 0, 0], ], [ new THREE.Line(lineGeometry, matLineBlue), null, [0, -Math.PI / 2, 0], [0.8, 1, 1], ], ], XY: [ [ new THREE.Mesh(scaleHandleGeometry, matYellowTransparent), [0.85, 0.85, 0], null, [2, 2, 0.2], ], [ new THREE.Line(lineGeometry, matLineYellow), [0.855, 0.98, 0], null, [0.125, 1, 1], ], [ new THREE.Line(lineGeometry, matLineYellow), [0.98, 0.855, 0], [0, 0, Math.PI / 2], [0.125, 1, 1], ], ], YZ: [ [ new THREE.Mesh(scaleHandleGeometry, matCyanTransparent), [0, 0.85, 0.85], null, [0.2, 2, 2], ], [ new THREE.Line(lineGeometry, matLineCyan), [0, 0.855, 0.98], [0, 0, Math.PI / 2], [0.125, 1, 1], ], [ new THREE.Line(lineGeometry, matLineCyan), [0, 0.98, 0.855], [0, -Math.PI / 2, 0], [0.125, 1, 1], ], ], XZ: [ [ new THREE.Mesh(scaleHandleGeometry, matMagentaTransparent), [0.85, 0, 0.85], null, [2, 0.2, 2], ], [ new THREE.Line(lineGeometry, matLineMagenta), [0.855, 0, 0.98], null, [0.125, 1, 1], ], [ new THREE.Line(lineGeometry, matLineMagenta), [0.98, 0, 0.855], [0, -Math.PI / 2, 0], [0.125, 1, 1], ], ], XYZX: [ [ new THREE.Mesh( new THREE.BoxBufferGeometry(0.125, 0.125, 0.125), matWhiteTransparent.clone() ), [1.1, 0, 0], ], ], XYZY: [ [ new THREE.Mesh( new THREE.BoxBufferGeometry(0.125, 0.125, 0.125), matWhiteTransparent.clone() ), [0, 1.1, 0], ], ], XYZZ: [ [ new THREE.Mesh( new THREE.BoxBufferGeometry(0.125, 0.125, 0.125), matWhiteTransparent.clone() ), [0, 0, 1.1], ], ], }; var pickerScale = { X: [ [ new THREE.Mesh( new THREE.CylinderBufferGeometry(0.2, 0, 0.8, 4, 1, false), matInvisible ), [0.5, 0, 0], [0, 0, -Math.PI / 2], ], ], Y: [ [ new THREE.Mesh( new THREE.CylinderBufferGeometry(0.2, 0, 0.8, 4, 1, false), matInvisible ), [0, 0.5, 0], ], ], Z: [ [ new THREE.Mesh( new THREE.CylinderBufferGeometry(0.2, 0, 0.8, 4, 1, false), matInvisible ), [0, 0, 0.5], [Math.PI / 2, 0, 0], ], ], XY: [ [ new THREE.Mesh(scaleHandleGeometry, matInvisible), [0.85, 0.85, 0], null, [3, 3, 0.2], ], ], YZ: [ [ new THREE.Mesh(scaleHandleGeometry, matInvisible), [0, 0.85, 0.85], null, [0.2, 3, 3], ], ], XZ: [ [ new THREE.Mesh(scaleHandleGeometry, matInvisible), [0.85, 0, 0.85], null, [3, 0.2, 3], ], ], XYZX: [ [ new THREE.Mesh( new THREE.BoxBufferGeometry(0.2, 0.2, 0.2), matInvisible ), [1.1, 0, 0], ], ], XYZY: [ [ new THREE.Mesh( new THREE.BoxBufferGeometry(0.2, 0.2, 0.2), matInvisible ), [0, 1.1, 0], ], ], XYZZ: [ [ new THREE.Mesh( new THREE.BoxBufferGeometry(0.2, 0.2, 0.2), matInvisible ), [0, 0, 1.1], ], ], }; var helperScale = { X: [ [ new THREE.Line(lineGeometry, matHelper.clone()), [-1e3, 0, 0], null, [1e6, 1, 1], "helper", ], ], Y: [ [ new THREE.Line(lineGeometry, matHelper.clone()), [0, -1e3, 0], [0, 0, Math.PI / 2], [1e6, 1, 1], "helper", ], ], Z: [ [ new THREE.Line(lineGeometry, matHelper.clone()), [0, 0, -1e3], [0, -Math.PI / 2, 0], [1e6, 1, 1], "helper", ], ], }; // Creates an Object3D with gizmos described in custom hierarchy definition. var setupGizmo = function (gizmoMap) { var gizmo = new THREE.Object3D(); for (var name in gizmoMap) { for (var i = gizmoMap[name].length; i--; ) { var object = gizmoMap[name][i][0].clone(); var position = gizmoMap[name][i][1]; var rotation = gizmoMap[name][i][2]; var scale = gizmoMap[name][i][3]; var tag = gizmoMap[name][i][4]; // name and tag properties are essential for picking and updating logic. object.name = name; object.tag = tag; if (position) { object.position.set(position[0], position[1], position[2]); } if (rotation) { object.rotation.set(rotation[0], rotation[1], rotation[2]); } if (scale) { object.scale.set(scale[0], scale[1], scale[2]); } object.updateMatrix(); var tempGeometry = object.geometry.clone(); tempGeometry.applyMatrix4(object.matrix); object.geometry = tempGeometry; object.renderOrder = Infinity; object.position.set(0, 0, 0); object.rotation.set(0, 0, 0); object.scale.set(1, 1, 1); gizmo.add(object); } } return gizmo; }; // Reusable utility variables var tempVector = new THREE.Vector3(0, 0, 0); var tempEuler = new THREE.Euler(); var alignVector = new THREE.Vector3(0, 1, 0); var zeroVector = new THREE.Vector3(0, 0, 0); var lookAtMatrix = new THREE.Matrix4(); var tempQuaternion = new THREE.Quaternion(); var tempQuaternion2 = new THREE.Quaternion(); var identityQuaternion = new THREE.Quaternion(); var unitX = new THREE.Vector3(1, 0, 0); var unitY = new THREE.Vector3(0, 1, 0); var unitZ = new THREE.Vector3(0, 0, 1); // Gizmo creation this.gizmo = {}; this.picker = {}; this.helper = {}; this.add((this.gizmo["translate"] = setupGizmo(gizmoTranslate))); this.add((this.gizmo["rotate"] = setupGizmo(gizmoRotate))); this.add((this.gizmo["scale"] = setupGizmo(gizmoScale))); this.add((this.picker["translate"] = setupGizmo(pickerTranslate))); this.add((this.picker["rotate"] = setupGizmo(pickerRotate))); this.add((this.picker["scale"] = setupGizmo(pickerScale))); this.add((this.helper["translate"] = setupGizmo(helperTranslate))); this.add((this.helper["rotate"] = setupGizmo(helperRotate))); this.add((this.helper["scale"] = setupGizmo(helperScale))); // Pickers should be hidden always this.picker["translate"].visible = false; this.picker["rotate"].visible = false; this.picker["scale"].visible = false; // updateMatrixWorld will update transformations and appearance of individual handles this.updateMatrixWorld = function () { var space = this.space; if (this.mode === "scale") space = "local"; // scale always oriented to local rotation var quaternion = space === "local" ? this.worldQuaternion : identityQuaternion; // Show only gizmos for current transform mode this.gizmo["translate"].visible = this.mode === "translate"; this.gizmo["rotate"].visible = this.mode === "rotate"; this.gizmo["scale"].visible = this.mode === "scale"; this.helper["translate"].visible = this.mode === "translate"; this.helper["rotate"].visible = this.mode === "rotate"; this.helper["scale"].visible = this.mode === "scale"; var handles = []; handles = handles.concat(this.picker[this.mode].children); handles = handles.concat(this.gizmo[this.mode].children); handles = handles.concat(this.helper[this.mode].children); for (var i = 0; i < handles.length; i++) { var handle = handles[i]; // hide aligned to camera handle.visible = true; handle.rotation.set(0, 0, 0); handle.position.copy(this.worldPosition); var factor; if (this.camera.isOrthographicCamera) { factor = (this.camera.top - this.camera.bottom) / this.camera.zoom; } else { factor = this.worldPosition.distanceTo(this.cameraPosition) * Math.min( (1.9 * Math.tan((Math.PI * this.camera.fov) / 360)) / this.camera.zoom, 7 ); } handle.scale.set(1, 1, 1).multiplyScalar((factor * this.size) / 7); // TODO: simplify helpers and consider decoupling from gizmo if (handle.tag === "helper") { handle.visible = false; if (handle.name === "AXIS") { handle.position.copy(this.worldPositionStart); handle.visible = !!this.axis; if (this.axis === "X") { tempQuaternion.setFromEuler(tempEuler.set(0, 0, 0)); handle.quaternion.copy(quaternion).multiply(tempQuaternion); if ( Math.abs( alignVector .copy(unitX) .applyQuaternion(quaternion) .dot(this.eye) ) > 0.9 ) { handle.visible = false; } } if (this.axis === "Y") { tempQuaternion.setFromEuler(tempEuler.set(0, 0, Math.PI / 2)); handle.quaternion.copy(quaternion).multiply(tempQuaternion); if ( Math.abs( alignVector .copy(unitY) .applyQuaternion(quaternion) .dot(this.eye) ) > 0.9 ) { handle.visible = false; } } if (this.axis === "Z") { tempQuaternion.setFromEuler(tempEuler.set(0, Math.PI / 2, 0)); handle.quaternion.copy(quaternion).multiply(tempQuaternion); if ( Math.abs( alignVector .copy(unitZ) .applyQuaternion(quaternion) .dot(this.eye) ) > 0.9 ) { handle.visible = false; } } if (this.axis === "XYZE") { tempQuaternion.setFromEuler(tempEuler.set(0, Math.PI / 2, 0)); alignVector.copy(this.rotationAxis); handle.quaternion.setFromRotationMatrix( lookAtMatrix.lookAt(zeroVector, alignVector, unitY) ); handle.quaternion.multiply(tempQuaternion); handle.visible = this.dragging; } if (this.axis === "E") { handle.visible = false; } } else if (handle.name === "START") { handle.position.copy(this.worldPositionStart); handle.visible = this.dragging; } else if (handle.name === "END") { handle.position.copy(this.worldPosition); handle.visible = this.dragging; } else if (handle.name === "DELTA") { handle.position.copy(this.worldPositionStart); handle.quaternion.copy(this.worldQuaternionStart); tempVector .set(1e-10, 1e-10, 1e-10) .add(this.worldPositionStart) .sub(this.worldPosition) .multiplyScalar(-1); tempVector.applyQuaternion( this.worldQuaternionStart.clone().invert() ); handle.scale.copy(tempVector); handle.visible = this.dragging; } else { handle.quaternion.copy(quaternion); if (this.dragging) { handle.position.copy(this.worldPositionStart); } else { handle.position.copy(this.worldPosition); } if (this.axis) { handle.visible = this.axis.search(handle.name) !== -1; } } // If updating helper, skip rest of the loop continue; } // Align handles to current local or world rotation handle.quaternion.copy(quaternion); if (this.mode === "translate" || this.mode === "scale") { // Hide translate and scale axis facing the camera var AXIS_HIDE_TRESHOLD = 0.99; var PLANE_HIDE_TRESHOLD = 0.2; var AXIS_FLIP_TRESHOLD = 0.0; if (handle.name === "X" || handle.name === "XYZX") { if ( Math.abs( alignVector.copy(unitX).applyQuaternion(quaternion).dot(this.eye) ) > AXIS_HIDE_TRESHOLD ) { handle.scale.set(1e-10, 1e-10, 1e-10); handle.visible = false; } } if (handle.name === "Y" || handle.name === "XYZY") { if ( Math.abs( alignVector.copy(unitY).applyQuaternion(quaternion).dot(this.eye) ) > AXIS_HIDE_TRESHOLD ) { handle.scale.set(1e-10, 1e-10, 1e-10); handle.visible = false; } } if (handle.name === "Z" || handle.name === "XYZZ") { if ( Math.abs( alignVector.copy(unitZ).applyQuaternion(quaternion).dot(this.eye) ) > AXIS_HIDE_TRESHOLD ) { handle.scale.set(1e-10, 1e-10, 1e-10); handle.visible = false; } } if (handle.name === "XY") { if ( Math.abs( alignVector.copy(unitZ).applyQuaternion(quaternion).dot(this.eye) ) < PLANE_HIDE_TRESHOLD ) { handle.scale.set(1e-10, 1e-10, 1e-10); handle.visible = false; } } if (handle.name === "YZ") { if ( Math.abs( alignVector.copy(unitX).applyQuaternion(quaternion).dot(this.eye) ) < PLANE_HIDE_TRESHOLD ) { handle.scale.set(1e-10, 1e-10, 1e-10); handle.visible = false; } } if (handle.name === "XZ") { if ( Math.abs( alignVector.copy(unitY).applyQuaternion(quaternion).dot(this.eye) ) < PLANE_HIDE_TRESHOLD ) { handle.scale.set(1e-10, 1e-10, 1e-10); handle.visible = false; } } // Flip translate and scale axis ocluded behind another axis if (handle.name.search("X") !== -1) { if ( alignVector.copy(unitX).applyQuaternion(quaternion).dot(this.eye) < AXIS_FLIP_TRESHOLD ) { if (handle.tag === "fwd") { handle.visible = false; } else { handle.scale.x *= -1; } } else if (handle.tag === "bwd") { handle.visible = false; } } if (handle.name.search("Y") !== -1) { if ( alignVector.copy(unitY).applyQuaternion(quaternion).dot(this.eye) < AXIS_FLIP_TRESHOLD ) { if (handle.tag === "fwd") { handle.visible = false; } else { handle.scale.y *= -1; } } else if (handle.tag === "bwd") { handle.visible = false; } } if (handle.name.search("Z") !== -1) { if ( alignVector.copy(unitZ).applyQuaternion(quaternion).dot(this.eye) < AXIS_FLIP_TRESHOLD ) { if (handle.tag === "fwd") { handle.visible = false; } else { handle.scale.z *= -1; } } else if (handle.tag === "bwd") { handle.visible = false; } } } else if (this.mode === "rotate") { // Align handles to current local or world rotation tempQuaternion2.copy(quaternion); alignVector .copy(this.eye) .applyQuaternion(tempQuaternion.copy(quaternion).invert()); if (handle.name.search("E") !== -1) { handle.quaternion.setFromRotationMatrix( lookAtMatrix.lookAt(this.eye, zeroVector, unitY) ); } if (handle.name === "X") { tempQuaternion.setFromAxisAngle( unitX, Math.atan2(-alignVector.y, alignVector.z) ); tempQuaternion.multiplyQuaternions(tempQuaternion2, tempQuaternion); handle.quaternion.copy(tempQuaternion); } if (handle.name === "Y") { tempQuaternion.setFromAxisAngle( unitY, Math.atan2(alignVector.x, alignVector.z) ); tempQuaternion.multiplyQuaternions(tempQuaternion2, tempQuaternion); handle.quaternion.copy(tempQuaternion); } if (handle.name === "Z") { tempQuaternion.setFromAxisAngle( unitZ, Math.atan2(alignVector.y, alignVector.x) ); tempQuaternion.multiplyQuaternions(tempQuaternion2, tempQuaternion); handle.quaternion.copy(tempQuaternion); } } // Hide disabled axes handle.visible = handle.visible && (handle.name.indexOf("X") === -1 || this.showX); handle.visible = handle.visible && (handle.name.indexOf("Y") === -1 || this.showY); handle.visible = handle.visible && (handle.name.indexOf("Z") === -1 || this.showZ); handle.visible = handle.visible && (handle.name.indexOf("E") === -1 || (this.showX && this.showY && this.showZ)); // highlight selected axis handle.material._opacity = handle.material._opacity || handle.material.opacity; handle.material._color = handle.material._color || handle.material.color.clone(); handle.material.color.copy(handle.material._color); handle.material.opacity = handle.material._opacity; if (!this.enabled) { handle.material.opacity *= 0.5; handle.material.color.lerp(new THREE.Color(1, 1, 1), 0.5); } else if (this.axis) { if (handle.name === this.axis) { handle.material.opacity = 1.0; handle.material.color.lerp(new THREE.Color(1, 1, 1), 0.5); } else if ( this.axis.split("").some(function (a) { return handle.name === a; }) ) { handle.material.opacity = 1.0; handle.material.color.lerp(new THREE.Color(1, 1, 1), 0.5); } else { handle.material.opacity *= 0.25; handle.material.color.lerp(new THREE.Color(1, 1, 1), 0.5); } } } THREE.Object3D.prototype.updateMatrixWorld.call(this); }; }; THREE.TransformControlsGizmo.prototype = Object.assign( Object.create(THREE.Object3D.prototype), { constructor: THREE.TransformControlsGizmo, isTransformControlsGizmo: true, } ); THREE.TransformControlsPlane = function () { "use strict"; THREE.Mesh.call( this, new THREE.PlaneBufferGeometry(100000, 100000, 2, 2), new THREE.MeshBasicMaterial({ visible: false, wireframe: true, side: THREE.DoubleSide, transparent: true, opacity: 0.1, toneMapped: false, }) ); this.type = "TransformControlsPlane"; var unitX = new THREE.Vector3(1, 0, 0); var unitY = new THREE.Vector3(0, 1, 0); var unitZ = new THREE.Vector3(0, 0, 1); var tempVector = new THREE.Vector3(); var dirVector = new THREE.Vector3(); var alignVector = new THREE.Vector3(); var tempMatrix = new THREE.Matrix4(); var identityQuaternion = new THREE.Quaternion(); this.updateMatrixWorld = function () { var space = this.space; this.position.copy(this.worldPosition); if (this.mode === "scale") space = "local"; // scale always oriented to local rotation unitX .set(1, 0, 0) .applyQuaternion( space === "local" ? this.worldQuaternion : identityQuaternion ); unitY .set(0, 1, 0) .applyQuaternion( space === "local" ? this.worldQuaternion : identityQuaternion ); unitZ .set(0, 0, 1) .applyQuaternion( space === "local" ? this.worldQuaternion : identityQuaternion ); // Align the plane for current transform mode, axis and space. alignVector.copy(unitY); switch (this.mode) { case "translate": case "scale": switch (this.axis) { case "X": alignVector.copy(this.eye).cross(unitX); dirVector.copy(unitX).cross(alignVector); break; case "Y": alignVector.copy(this.eye).cross(unitY); dirVector.copy(unitY).cross(alignVector); break; case "Z": alignVector.copy(this.eye).cross(unitZ); dirVector.copy(unitZ).cross(alignVector); break; case "XY": dirVector.copy(unitZ); break; case "YZ": dirVector.copy(unitX); break; case "XZ": alignVector.copy(unitZ); dirVector.copy(unitY); break; case "XYZ": case "E": dirVector.set(0, 0, 0); break; } break; case "rotate": default: // special case for rotate dirVector.set(0, 0, 0); } if (dirVector.length() === 0) { // If in rotate mode, make the plane parallel to camera this.quaternion.copy(this.cameraQuaternion); } else { tempMatrix.lookAt(tempVector.set(0, 0, 0), dirVector, alignVector); this.quaternion.setFromRotationMatrix(tempMatrix); } THREE.Object3D.prototype.updateMatrixWorld.call(this); }; }; THREE.TransformControlsPlane.prototype = Object.assign( Object.create(THREE.Mesh.prototype), { constructor: THREE.TransformControlsPlane, isTransformControlsPlane: true, } );
// Copyright (C) 2017 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- description: | Collection of assertion functions used throughout test262 defines: [assert] ---*/ function assert(mustBeTrue, message) { if (mustBeTrue === true) { return; } if (message === undefined) { message = 'Expected true but got ' + assert._toString(mustBeTrue); } throw (message); } assert._isSameValue = function (a, b) { if (a === b) { // Handle +/-0 vs. -/+0 return a !== 0 || 1 / a === 1 / b; } // Handle NaN vs. NaN return a !== a && b !== b; }; assert.sameValue = function (actual, expected, message) { try { if (assert._isSameValue(actual, expected)) { return; } } catch (error) { throw (message + ' (_isSameValue operation threw) ' + error); } if (message === undefined) { message = ''; } else { message += ' '; } message += 'Expected SameValue(«' + assert._toString(actual) + '», «' + assert._toString(expected) + '») to be true'; throw (message); }; assert.notSameValue = function (actual, unexpected, message) { if (!assert._isSameValue(actual, unexpected)) { return; } if (message === undefined) { message = ''; } else { message += ' '; } message += 'Expected SameValue(«' + assert._toString(actual) + '», «' + assert._toString(unexpected) + '») to be false'; throw (message); }; assert.throws = function (expectedErrorConstructor, func, message) { if (typeof func !== "function") { throw ('assert.throws requires two arguments: the error constructor ' + 'and a function to run'); } if (message === undefined) { message = ''; } else { message += ' '; } try { func(); } catch (thrown) { if (typeof thrown !== 'object' || thrown === null) { message += 'Thrown value was not an object!'; throw (message); } else if (thrown.constructor !== expectedErrorConstructor) { message += 'Expected a ' + expectedErrorConstructor.name + ' but got a ' + thrown.constructor.name; throw (message); } return; } message += 'Expected a ' + expectedErrorConstructor.name + ' to be thrown but no exception was thrown at all'; throw (message); }; assert._toString = function (value) { try { if (value === 0 && 1 / value === -Infinity) { return '-0'; } return String(value); } catch (err) { if (err.name === 'TypeError') { return Object.prototype.toString.call(value); } throw err; } }; // Copyright (C) 2017 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- description: | Collection of functions used to safely verify the correctness of property descriptors. defines: - verifyProperty - verifyEqualTo - verifyWritable - verifyNotWritable - verifyEnumerable - verifyNotEnumerable - verifyConfigurable - verifyNotConfigurable ---*/ // @ts-check /** * @param {object} obj * @param {string|symbol} name * @param {PropertyDescriptor|undefined} desc * @param {object} [options] * @param {boolean} [options.restore] */ function verifyProperty(obj, name, desc, options) { assert( arguments.length > 2, 'verifyProperty should receive at least 3 arguments: obj, name, and descriptor' ); var originalDesc = Object.getOwnPropertyDescriptor(obj, name); var nameStr = String(name); // Allows checking for undefined descriptor if it's explicitly given. if (desc === undefined) { assert.sameValue( originalDesc, undefined, "obj['" + nameStr + "'] descriptor should be undefined" ); // desc and originalDesc are both undefined, problem solved; return true; } assert( Object.prototype.hasOwnProperty.call(obj, name), "obj should have an own property " + nameStr ); assert.notSameValue( desc, null, "The desc argument should be an object or undefined, null" ); assert.sameValue( typeof desc, "object", "The desc argument should be an object or undefined, " + String(desc) ); var failures = []; if (Object.prototype.hasOwnProperty.call(desc, 'value')) { if (!isSameValue(desc.value, originalDesc.value)) { failures.push("descriptor value should be " + desc.value); } } if (Object.prototype.hasOwnProperty.call(desc, 'enumerable')) { if (desc.enumerable !== originalDesc.enumerable || desc.enumerable !== isEnumerable(obj, name)) { failures.push('descriptor should ' + (desc.enumerable ? '' : 'not ') + 'be enumerable'); } } if (Object.prototype.hasOwnProperty.call(desc, 'writable')) { if (desc.writable !== originalDesc.writable || desc.writable !== isWritable(obj, name)) { failures.push('descriptor should ' + (desc.writable ? '' : 'not ') + 'be writable'); } } if (Object.prototype.hasOwnProperty.call(desc, 'configurable')) { if (desc.configurable !== originalDesc.configurable || desc.configurable !== isConfigurable(obj, name)) { failures.push('descriptor should ' + (desc.configurable ? '' : 'not ') + 'be configurable'); } } assert(!failures.length, failures.join('; ')); if (options && options.restore) { Object.defineProperty(obj, name, originalDesc); } return true; } function isConfigurable(obj, name) { var hasOwnProperty = Object.prototype.hasOwnProperty; try { delete obj[name]; } catch (e) { if (!(e instanceof TypeError)) { throw ("Expected TypeError, got " + e) } } return !hasOwnProperty.call(obj, name); } function isEnumerable(obj, name) { var stringCheck = false; if (typeof name === "string") { for (var x in obj) { if (x === name) { stringCheck = true; break; } } } else { // skip it if name is not string, works for Symbol names. stringCheck = true; } return stringCheck && Object.prototype.hasOwnProperty.call(obj, name) && Object.prototype.propertyIsEnumerable.call(obj, name); } function isSameValue(a, b) { if (a === 0 && b === 0) return 1 / a === 1 / b; if (a !== a && b !== b) return true; return a === b; } var __isArray = Array.isArray; function isWritable(obj, name, verifyProp, value) { var unlikelyValue = __isArray(obj) && name === "length" ? Math.pow(2, 32) - 1 : "unlikelyValue"; var newValue = value || unlikelyValue; var hadValue = Object.prototype.hasOwnProperty.call(obj, name); var oldValue = obj[name]; var writeSucceeded; try { obj[name] = newValue; } catch (e) { if (!(e instanceof TypeError)) { throw ("Expected TypeError, got " + e); } } writeSucceeded = isSameValue(obj[verifyProp || name], newValue); // Revert the change only if it was successful (in other cases, reverting // is unnecessary and may trigger exceptions for certain property // configurations) if (writeSucceeded) { if (hadValue) { obj[name] = oldValue; } else { delete obj[name]; } } return writeSucceeded; } function verifyEqualTo(obj, name, value) { if (!isSameValue(obj[name], value)) { throw ("Expected obj[" + String(name) + "] to equal " + value + ", actually " + obj[name]); } } function verifyWritable(obj, name, verifyProp, value) { if (!verifyProp) { assert(Object.getOwnPropertyDescriptor(obj, name).writable, "Expected obj[" + String(name) + "] to have writable:true."); } if (!isWritable(obj, name, verifyProp, value)) { throw ("Expected obj[" + String(name) + "] to be writable, but was not."); } } function verifyNotWritable(obj, name, verifyProp, value) { if (!verifyProp) { assert(!Object.getOwnPropertyDescriptor(obj, name).writable, "Expected obj[" + String(name) + "] to have writable:false."); } if (isWritable(obj, name, verifyProp)) { throw ("Expected obj[" + String(name) + "] NOT to be writable, but was."); } } function verifyEnumerable(obj, name) { assert(Object.getOwnPropertyDescriptor(obj, name).enumerable, "Expected obj[" + String(name) + "] to have enumerable:true."); if (!isEnumerable(obj, name)) { throw ("Expected obj[" + String(name) + "] to be enumerable, but was not."); } } function verifyNotEnumerable(obj, name) { assert(!Object.getOwnPropertyDescriptor(obj, name).enumerable, "Expected obj[" + String(name) + "] to have enumerable:false."); if (isEnumerable(obj, name)) { throw ("Expected obj[" + String(name) + "] NOT to be enumerable, but was."); } } function verifyConfigurable(obj, name) { assert(Object.getOwnPropertyDescriptor(obj, name).configurable, "Expected obj[" + String(name) + "] to have configurable:true."); if (!isConfigurable(obj, name)) { throw ("Expected obj[" + String(name) + "] to be configurable, but was not."); } } function verifyNotConfigurable(obj, name) { assert(!Object.getOwnPropertyDescriptor(obj, name).configurable, "Expected obj[" + String(name) + "] to have configurable:false."); if (isConfigurable(obj, name)) { throw ("Expected obj[" + String(name) + "] NOT to be configurable, but was."); } } function Test262Error(message) { this.message = message || ""; } Test262Error.prototype.toString = function () { return "Test262Error: " + this.message; }; // Copyright (C) 2017 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- description: | Compare the contents of two arrays defines: [compareArray] ---*/ function compareArray(a, b) { if (b.length !== a.length) { return false; } for (var i = 0; i < a.length; i++) { if (!compareArray.isSameValue(b[i], a[i])) { return false; } } return true; } compareArray.isSameValue = function (a, b) { if (a === 0 && b === 0) return 1 / a === 1 / b; if (a !== a && b !== b) return true; return a === b; }; compareArray.format = function (array) { return "[" + array.map(String).join(', ') + "]"; }; assert.compareArray = function (actual, expected, message) { assert(actual != null, "First argument shouldn't be nullish. " + message); assert(expected != null, "Second argument shouldn't be nullish. " + message); var format = compareArray.format; assert( compareArray(actual, expected), "Expected " + format(actual) + " and " + format(expected) + " to have the same contents. " + message ); }; // Copyright (C) 2015 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es6id: 9.2.2 description: > [[Construct]] ( argumentsList, newTarget) ... 13. If result.[[type]] is return, then ... b. If kind is "base", return NormalCompletion(thisArgument). ... ... `return this;` ---*/ var calls = 0; class Base { constructor() { this.prop = 1; calls++; } } class Derived extends Base { constructor() { super(); return this; } } var object = new Derived(); // super is called assert.sameValue(calls, 1, "The value of `calls` is `1`, because `super()`"); // The this object was returned. assert.sameValue(object.prop, 1); assert.sameValue(object instanceof Derived, true); assert.sameValue(object instanceof Base, true);
const menu = document.querySelectorAll(".menu-mobile") const menumobile = document.querySelector(".menu-mobile") const menuHamburguer = document.querySelector(".menu-hamburguer") const menuShow = document.querySelectorAll('.menu-toggle ul li a') menuHamburguer.addEventListener('click', ()=> { for(const element of menu){ element.classList.toggle('show') } esconder() }) const header = document.querySelector('#header') const navHeight = header.offsetHeight window.addEventListener('scroll', function () { if (window.scrollY >= navHeight) { // scroll é maior que a altura do header header.classList.add('scroll') } else { // menor que a altura do header header.classList.remove('scroll') } }) for (const link of menuShow){ link.addEventListener('click', ()=> { menumobile.classList.remove('show') esconder() }) } function esconder() { if(menumobile.classList.contains('show')){ document.body.style.overflow = 'hidden' } else { document.body.style.overflow = 'initial' } }
/*! * OpenUI5 * (c) Copyright 2009-2020 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ /** * Initialization Code and shared classes of library sap.ui.ux3. */ sap.ui.define([ 'sap/ui/core/library', // library dependency 'sap/ui/commons/library'], // library dependency function() { "use strict"; /** * Controls that implement the SAP User Experience (UX) Guidelines 3.0 * * @namespace * @name sap.ui.ux3 * @author SAP SE * @version 1.84.11 * @public * @deprecated Since 1.38 */ // delegate further initialization of this library to the Core sap.ui.getCore().initLibrary({ name : "sap.ui.ux3", version: "1.84.11", dependencies : ["sap.ui.core","sap.ui.commons"], types: [ "sap.ui.ux3.ActionBarSocialActions", "sap.ui.ux3.ExactOrder", "sap.ui.ux3.FeederType", "sap.ui.ux3.FollowActionState", "sap.ui.ux3.NotificationBarStatus", "sap.ui.ux3.ShellDesignType", "sap.ui.ux3.ShellHeaderType", "sap.ui.ux3.ThingViewerHeaderType", "sap.ui.ux3.VisibleItemCountMode" ], interfaces: [ "sap.ui.ux3.DataSetView" ], controls: [ "sap.ui.ux3.ActionBar", "sap.ui.ux3.CollectionInspector", "sap.ui.ux3.DataSet", "sap.ui.ux3.DataSetSimpleView", "sap.ui.ux3.Exact", "sap.ui.ux3.ExactArea", "sap.ui.ux3.ExactBrowser", "sap.ui.ux3.ExactList", "sap.ui.ux3.FacetFilter", "sap.ui.ux3.FacetFilterList", "sap.ui.ux3.Feed", "sap.ui.ux3.FeedChunk", "sap.ui.ux3.Feeder", "sap.ui.ux3.NavigationBar", "sap.ui.ux3.NotificationBar", "sap.ui.ux3.Overlay", "sap.ui.ux3.OverlayContainer", "sap.ui.ux3.OverlayDialog", "sap.ui.ux3.QuickView", "sap.ui.ux3.Shell", "sap.ui.ux3.ThingInspector", "sap.ui.ux3.ThingViewer", "sap.ui.ux3.ToolPopup" ], elements: [ "sap.ui.ux3.Collection", "sap.ui.ux3.DataSetItem", "sap.ui.ux3.ExactAttribute", "sap.ui.ux3.NavigationItem", "sap.ui.ux3.Notifier", "sap.ui.ux3.ThingAction", "sap.ui.ux3.ThingGroup" ] }); /** * Enumeration of available standard actions for 'sap.ui.ux3.ActionBar'. To be used as parameters for function 'sap.ui.ux3.ActionBar.getSocialAction'. * * @enum {string} * @public * @experimental Since version 1.2. * API is not yet finished and might change completely * @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel * @deprecated Since 1.38 */ sap.ui.ux3.ActionBarSocialActions = { /** * Standard action 'Create an update' (Feed) * @public */ Update : "Update", /** * Standard action 'Follow/Unfollow' * @public */ Follow : "Follow", /** * Standard action 'Mark for Follow up' * @public */ Flag : "Flag", /** * Standards action 'Mark as Favorite' * @public */ Favorite : "Favorite", /** * Standard action 'Open Thing Inspector' * @public */ Open : "Open" }; /** * * Marker interface for controls which are suitable as view rendering for a DataSet. * * * @author SAP SE * @name sap.ui.ux3.DataSetView * @interface * @public * @ui5-metamodel This interface also will be described in the UI5 (legacy) designtime metamodel * @deprecated Since 1.38 */ /** * Defines the order of the sub lists of a list in the ExactBrowser. * * @author SAP SE * @enum {string} * @public * @since 1.7.1 * @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel * @deprecated Since 1.38 */ sap.ui.ux3.ExactOrder = { /** * The order of the sub lists is defined by the selection order of the user. * @public */ Select : "Select", /** * The order of the sub lists is defined by order of the defined sub attributes. * @public */ Fixed : "Fixed" }; /** * Type of a Feeder. * * @enum {string} * @public * @experimental Since version 1.2. * The whole Feed/Feeder API is still under discussion, significant changes are likely. Especially text presentation (e.g. @-references and formatted text) is not final. Also the Feed model topic is still open. * @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel * @deprecated Since 1.38 */ sap.ui.ux3.FeederType = { /** * large Feeder * @public */ Large : "Large", /** * medium feeder * @public */ Medium : "Medium", /** * comment feeder (small) * @public */ Comment : "Comment" }; /** * Defines the states of the follow action * * @enum {string} * @public * @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel * @deprecated Since 1.38 */ sap.ui.ux3.FollowActionState = { /** * follow state * @public */ Follow : "Follow", /** * hold state * @public */ Hold : "Hold", /** * default state * @public */ Default : "Default" }; /** * This entries are used to set the visibility status of a NotificationBar * * @author SAP * @enum {string} * @public * @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel * @deprecated Since 1.38 */ sap.ui.ux3.NotificationBarStatus = { /** * Default height for the bar * @public */ Default : "Default", /** * Bar should be minimized * @public */ Min : "Min", /** * Bar should be maximized * @public */ Max : "Max", /** * Bar should not be visible * @public */ None : "None" }; /** * Available shell design types. * * @author SAP SE * @enum {string} * @public * @since 1.12.0 * @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel * @deprecated Since 1.38 */ sap.ui.ux3.ShellDesignType = { /** * The standard Shell design (dark). * @public */ Standard : "Standard", /** * * A lighter design. Should be used in combination with the Standard header * type. * * @public */ Light : "Light", /** * * An even lighter design. It borrows most of its properties from the Light * design and just changes a few details like the header colors in order to * have a blue design within gold reflection. * * @public */ Crystal : "Crystal" }; /** * Available shell header display types. * * @author SAP SE * @enum {string} * @public * @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel * @deprecated Since 1.38 */ sap.ui.ux3.ShellHeaderType = { /** * The standard Shell header. * @public */ Standard : "Standard", /** * Only the branding area is visible. Top-level navigation bar, header items, title and icon are not shown. * @public */ BrandOnly : "BrandOnly", /** * Like the Standard Area but without top-level navigation bar. * @public */ NoNavigation : "NoNavigation", /** * Like the Standard Area but with a leaner top-level navigation bar. * @public */ SlimNavigation : "SlimNavigation" }; /** * Available ThingViewer header display types. * * @author SAP SE * @enum {string} * @public * @since 1.16.3 * @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel * @deprecated Since 1.38 */ sap.ui.ux3.ThingViewerHeaderType = { /** * The standard ThingViewer header. * @public */ Standard : "Standard", /** * The header content is displayed horizontally above the facet content * @public */ Horizontal : "Horizontal" }; /** * VisibleItemCountMode of the FacetFilter defines if the FacetFilter takes the whole available height (Auto) in the surrounding container, or is so high as needed to show 5 Items ("Fixed " - default). * * @enum {string} * @public * @ui5-metamodel This enumeration also will be described in the UI5 (legacy) designtime metamodel * @deprecated Since 1.38 */ sap.ui.ux3.VisibleItemCountMode = { /** * The FacetFilter always has as many items in the FacetFilterList as defined in the visibleItemCount property. * @public */ Fixed : "Fixed", /** * The FacetFilter automatically fills the height of the surrounding container. The visibleItemCount property is automatically changed accordingly. * @public */ Auto : "Auto" }; return sap.ui.ux3; });
// Creare's 'Implied Consent' EU Cookie Law Banner v:2.4 // Conceived by Robert Kent, James Bavington & Tom Foyster // Modified by Simon Freytag for syntax, namespace, jQuery and Bootstrap C = { // Number of days before the cookie expires, and the banner reappears cookieDuration : 14, // Name of our cookie cookieName: 'complianceCookie', // Value of cookie cookieValue: 'on', // Message banner title bannerTitle: "Cookies:", // Message banner message bannerMessage: "Nous utilisons des cookies pour vous garantir la meilleure expérience sur notre site. Si vous continuez à utiliser ce dernier, nous considérerons que vous acceptez l'utilisation des cookies.", // Message banner dismiss button bannerButton: "OK", // Link to your cookie policy. bannerLinkURL: "/legal-docs/data-protection.html", // Link text bannerLinkText: "Read more", // Text alignment alertAlign: "center", // Link text buttonClass: "btn-success btn-xs", createDiv: function () { var banner = $( '<div class="alert alert-success alert-dismissible text-'+ this.alertAlign +' fade in" ' + 'role="alert" style="position: fixed; bottom: 0; width: 100%; ' + 'margin-bottom: 0"><strong>' + this.bannerTitle + '</strong> ' + this.bannerMessage + ' <button type="button" class="btn ' + this.buttonClass + '" onclick="C.createCookie(C.cookieName, C.cookieValue' + ', C.cookieDuration)" data-dismiss="alert" aria-label="Close">' + this.bannerButton + '</button></div>' ) $("body").append(banner) }, createCookie: function(name, value, days) { //console.log("Create cookie") var expires = "" if (days) { var date = new Date() date.setTime(date.getTime() + (days*24*60*60*1000)) expires = "; expires=" + date.toGMTString() } document.cookie = name + "=" + value + expires + "; path=/"; }, checkCookie: function(name) { var nameEQ = name + "=" var ca = document.cookie.split(';') for(var i = 0; i < ca.length; i++) { var c = ca[i] while (c.charAt(0)==' ') c = c.substring(1, c.length) if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length) } return null }, init: function() { if (this.checkCookie(this.cookieName) != this.cookieValue) this.createDiv() } } $(document).ready(function() { C.init() })
var classprzeszkoda = [ [ "Czy_Kolizja", "classprzeszkoda.html#a59708f9e085f59fbdd993aa9e0fb25db", null ] ];
/*jshint eqeqeq:false */ (function (window) { 'use strict'; /** * Creates a new client side storage object and will create an empty * collection if no collection already exists. * * @param {string} name The name of our DB we want to use * @param {function} callback Our fake DB uses callbacks because in * real life you probably would be making AJAX calls */ function Store(name, callback) { callback = callback || function () { }; this._dbName = name; if (!localStorage[name]) { var data = { todos: [] }; localStorage[name] = JSON.stringify(data); } callback.call(this, JSON.parse(localStorage[name])); } /** * Finds items based on a query given as a JS object * * @param {object} query The query to match against (i.e. {foo: 'bar'}) * @param {function} callback The callback to fire when the query has * completed running * * @example * db.find({foo: 'bar', hello: 'world'}, function (data) { * // data will return any items that have foo: bar and * // hello: world in their properties * }); */ Store.prototype.find = function (query, callback) { if (!callback) { return; } var todos = JSON.parse(localStorage[this._dbName]).todos; callback.call(this, todos.filter(function (todo) { for (var q in query) { if (query[q] !== todo[q]) { return false; } } return true; })); }; /** * Will retrieve all data from the collection * * @param {function} callback The callback to fire upon retrieving data */ Store.prototype.findAll = function (callback) { callback = callback || function () { }; callback.call(this, JSON.parse(localStorage[this._dbName]).todos); }; /** * Will save the given data to the DB. If no item exists it will create a new * item, otherwise it'll simply update an existing item's properties * * @param {object} updateData The data to save back into the DB * @param {function} callback The callback to fire after saving * @param {number} id An optional param to enter an ID of an item to update */ Store.prototype.save = function (updateData, callback, id) { var data = JSON.parse(localStorage[this._dbName]); var todos = data.todos; callback = callback || function () { }; // Generate an ID var newId = Date.now(); // var charset = "0123456789"; // for (var i = 0; i < 6; i++) { // newId += charset.charAt(Math.floor(Math.random() * charset.length)); // } // If an ID was actually given, find the item and update each property if (id) { for (var i = 0; i < todos.length; i++) { if (todos[i].id === id) { for (var key in updateData) { todos[i][key] = updateData[key]; } break; } } localStorage[this._dbName] = JSON.stringify(data); callback.call(this, todos); } else { // Assign an ID updateData.id = parseInt(newId); todos.push(updateData); localStorage[this._dbName] = JSON.stringify(data); callback.call(this, [updateData]); } }; /** * Will remove an item from the Store based on its ID * * @param {number} id The ID of the item you want to remove * @param {function} callback The callback to fire after saving */ Store.prototype.remove = function (id, callback) { var data = JSON.parse(localStorage[this._dbName]); var todos = data.todos; var todoId; for (var i = 0; i < todos.length; i++) { if (todos[i].id == id) { todoId = todos[i].id; } } for (var i = 0; i < todos.length; i++) { if (todos[i].id == todoId) { todos.splice(i, 1); } } localStorage[this._dbName] = JSON.stringify(data); callback.call(this, todos); }; /** * Will drop all storage and start fresh * * @param {function} callback The callback to fire after dropping the data */ Store.prototype.drop = function (callback) { var data = { todos: [] }; localStorage[this._dbName] = JSON.stringify(data); callback.call(this, data.todos); }; // Export to window window.app = window.app || {}; window.app.Store = Store; })(window);
import SimpleSchema from 'simpl-schema'; import BaseCollection from '/imports/api/base/BaseCollection'; import { Interests } from '/imports/api/interest/InterestCollection'; import { check } from 'meteor/check'; import { Meteor } from 'meteor/meteor'; import { _ } from 'meteor/underscore'; import { Tracker } from 'meteor/tracker'; import { Roles } from 'meteor/alanning:roles'; /** @module Profile */ /** * Profiles provide portfolio data for a user. * @extends module:Base~BaseCollection */ class ProfileCollection extends BaseCollection { /** * Creates the Profile collection. */ constructor() { super('Profile', new SimpleSchema({ username: { type: String }, // Remainder are optional first_name: { type: String, optional: true }, last_name: { type: String, optional: true }, bio: { type: String, optional: true }, interests: { type: Array, optional: true }, 'interests.$': { type: String }, image: { type: SimpleSchema.RegEx.Url, optional: true }, groups_id: { type: Array, optional: true }, 'groups_id.$': { type: Number } }, { tracker: Tracker })); } /** * Defines a new Profile. * @example * Profiles.define({ first_name: 'Philip', * last_name: 'Johnson', * username: 'johnson', * bio: 'I have been a professor of computer science at UH since 1990.', * interests: ['Application Development', 'Software Engineering', 'Databases'], * title: 'Professor of Information and Computer Sciences', * picture: 'http://philipmjohnson.org/headshot.jpg', * github: 'https://github.com/philipmjohnson', * facebook: 'https://facebook.com/philipmjohnson', * instagram: 'https://instagram.com/philipmjohnson' }); * @param { Object } description Object with required key username. * Remaining keys are optional. * Username must be unique for all users. It should be the UH email account. * Interests is an array of defined interest ids. * @throws { Meteor.Error } If a user with the supplied username already exists, or * if one or more interests are not defined, or if github, facebook, and instagram are not URLs. * @returns The newly created docID. */ define({ first_name = '', last_name = '', user_role = [], username, bio = '', interests = [], image= '', groups_id = [] }) { // make sure required fields are OK. const checkPattern = { first_name: String, last_name: String, bio: String, username: String, image: String }; check({ first_name, last_name, username, bio, image }, checkPattern); if (this.find({ username }).count() > 0) { throw new Meteor.Error(`${username} is previously defined in another Profile`); } // Throw an error if any of the passed Interest names are not defined. Interests.assertNames(interests); // Throw an error if there are duplicates in the passed interest names. if (interests.length !== _.uniq(interests).length) { throw new Meteor.Error(`${interests} contains duplicates`); } return this._collection.insert({ first_name, last_name, username, bio, interests, image, groups_id }); } /** * Returns an object representing the Profile docID in a format acceptable to define(). * @param docID The docID of a Profile. * @returns { Object } An object representing the definition of docID. */ dumpOne(docID) { const doc = this.findDoc(docID); const first_name = doc.first_name; const last_name = doc.last_name; const username = doc.username; const bio = doc.bio; const interests = doc.interests; const image = doc.image; const groups_id = doc.groups_id; return { first_name, last_name, username, bio, interests, image, groups_id }; } } /** * Provides the singleton instance of this class to all other entities. */ export const Profiles = new ProfileCollection();
var assert = require('assert') var Address = require('./address') var crypto = require('./crypto') var convert = require('./convert') var Network = require('./network') var Opcode = require('./opcode') function Script(data) { this.buffer = data || [] if(!Array.isArray(this.buffer)) { throw new Error('expect Script to be initialized with Array, but got ' + data) } this.parse() } Script.fromHex = function(data) { return new Script(convert.hexToBytes(data)) } Script.fromPubKey = function(str) { var script = new Script() var s = str.split(' ') for (var i in s) { if (Opcode.map.hasOwnProperty(s[i])) { script.writeOp(Opcode.map[s[i]]) } else { script.writeBytes(convert.hexToBytes(s[i])) } } return script } Script.fromScriptSig = function(str) { var script = new Script() var s = str.split(' ') for (var i in s) { if (Opcode.map.hasOwnProperty(s[i])) { script.writeOp(Opcode.map[s[i]]) } else { script.writeBytes(convert.hexToBytes(s[i])) } } return script } /** * Update the parsed script representation. * * Each Script object stores the script in two formats. First as a raw byte * array and second as an array of 'chunks', such as opcodes and pieces of * data. * * This method updates the chunks cache. Normally this is called by the * constructor and you don't need to worry about it. However, if you change * the script buffer manually, you should update the chunks using this method. */ Script.prototype.parse = function() { var self = this this.chunks = [] // Cursor var i = 0 // Read n bytes and store result as a chunk function readChunk(n) { self.chunks.push(self.buffer.slice(i, i + n)) i += n } while (i < this.buffer.length) { var opcode = this.buffer[i++] if (opcode >= 0xF0) { // Two byte opcode opcode = (opcode << 8) | this.buffer[i++] } var len if (opcode > 0 && opcode < Opcode.map.OP_PUSHDATA1) { // Read some bytes of data, opcode value is the length of data readChunk(opcode) } else if (opcode == Opcode.map.OP_PUSHDATA1) { len = this.buffer[i++] readChunk(len) } else if (opcode == Opcode.map.OP_PUSHDATA2) { len = (this.buffer[i++] << 8) | this.buffer[i++] readChunk(len) } else if (opcode == Opcode.map.OP_PUSHDATA4) { len = (this.buffer[i++] << 24) | (this.buffer[i++] << 16) | (this.buffer[i++] << 8) | this.buffer[i++] readChunk(len) } else { this.chunks.push(opcode) } } } /** * Compare the script to known templates of scriptPubKey. * * This method will compare the script to a small number of standard script * templates and return a string naming the detected type. * * Currently supported are: * Pubkeyhash (address) * Paying to a Bitcoin address which is the hash of a pubkey. * OP_DUP OP_HASH160 [pubKeyHash] OP_EQUALVERIFY OP_CHECKSIG * * Pubkey * Paying to a public key directly. * [pubKey] OP_CHECKSIG * * Scripthash (P2SH) * Paying to an address which is the hash of a script * OP_HASH160 [Scripthash] OP_EQUAL * * Multisig * Paying to multiple pubkeys and require a number of the signatures * m [pubkey] [pubkey] [pubkey] n OP_CHECKMULTISIG * * Nulldata * Provably prune-able outputs * OP_RETURN [data] * * Nonstandard: * Any other script (no template matched). * * https://github.com/bitcoin/bitcoin/blob/19e5b9d2dfcac4efadba636745485d9660fb1abe/src/script.cpp#L75 */ Script.prototype.getOutType = function() { if (isPubkeyhash.call(this)) { return 'pubkeyhash' } else if (isPubkey.call(this)) { return 'pubkey' } else if (isScripthash.call(this)) { return 'scripthash' } else if (isMultisig.call(this)) { return 'multisig' } else if (isNulldata.call(this)) { return 'nulldata' } else { return 'nonstandard' } } function isPubkeyhash() { return this.chunks.length == 5 && this.chunks[0] == Opcode.map.OP_DUP && this.chunks[1] == Opcode.map.OP_HASH160 && Array.isArray(this.chunks[2]) && this.chunks[2].length === 20 && this.chunks[3] == Opcode.map.OP_EQUALVERIFY && this.chunks[4] == Opcode.map.OP_CHECKSIG } function isPubkey() { return this.chunks.length === 2 && Array.isArray(this.chunks[0]) && this.chunks[1] === Opcode.map.OP_CHECKSIG } function isScripthash() { return this.chunks[this.chunks.length - 1] == Opcode.map.OP_EQUAL && this.chunks[0] == Opcode.map.OP_HASH160 && Array.isArray(this.chunks[1]) && this.chunks[1].length === 20 && this.chunks.length == 3 } function isMultisig() { return this.chunks.length > 3 && // m is a smallint isSmallIntOp(this.chunks[0]) && // n is a smallint isSmallIntOp(this.chunks[this.chunks.length - 2]) && // n greater or equal to m this.chunks[0] <= this.chunks[this.chunks.length - 2] && // n cannot be 0 this.chunks[this.chunks.length - 2] !== Opcode.map.OP_0 && // n is the size of chunk length minus 3 (m, n, OP_CHECKMULTISIG) this.chunks.length - 3 === this.chunks[this.chunks.length - 2] - Opcode.map.OP_RESERVED && // last chunk is OP_CHECKMULTISIG this.chunks[this.chunks.length - 1] == Opcode.map.OP_CHECKMULTISIG } function isNulldata() { return this.chunks[0] === Opcode.map.OP_RETURN } function isSmallIntOp(opcode) { return ((opcode == Opcode.map.OP_0) || ((opcode >= Opcode.map.OP_1) && (opcode <= Opcode.map.OP_16))) } /** * Returns the address corresponding to this output in hash160 form. * Assumes strange scripts are P2SH */ Script.prototype.toScriptHash = function() { if(isPubkeyhash.call(this)) { return this.chunks[2] } if(isScripthash.call(this)) { return crypto.hash160(this.buffer) } return crypto.hash160(this.buffer) } Script.prototype.getToAddress = function(network) { network = network || Network.bitcoin if(isPubkeyhash.call(this)) { return new Address(new Buffer(this.chunks[2]), network.pubKeyHash) } assert(isScripthash.call(this)) return new Address(new Buffer(this.chunks[1]), network.scriptHash) } Script.prototype.getFromAddress = function(version) { version = version || Network.bitcoin.pubKeyHash return new Address(this.simpleInHash(), version) } /** * Compare the script to known templates of scriptSig. * * This method will compare the script to a small number of standard script * templates and return a string naming the detected type. * * WARNING: Use this method with caution. It merely represents a heuristic * based on common transaction formats. A non-standard transaction could * very easily match one of these templates by accident. * * Currently supported are: * Address: * Paying to a Bitcoin address which is the hash of a pubkey. * [sig] [pubKey] * * Pubkey: * Paying to a public key directly. * [sig] * * Multisig: * Paying to M-of-N public keys. * * Nonstandard: * Any other script (no template matched). */ Script.prototype.getInType = function() { if (this.chunks.length == 1 && Array.isArray(this.chunks[0])) { // Direct IP to IP transactions only have the signature in their scriptSig. // TODO: We could also check that the length of the data is correct. return 'pubkey' } else if (this.chunks.length == 2 && Array.isArray(this.chunks[0]) && Array.isArray(this.chunks[1])) { return 'pubkeyhash' } else if (this.chunks[0] == Opcode.map.OP_0 && this.chunks.slice(1).reduce(function(t, chunk, i) { return t && Array.isArray(chunk) && (chunk[0] == 48 || i == this.chunks.length - 1) }, true)) { return 'multisig' } else { return 'nonstandard' } } /** * Returns the affected public key for this input. * * This currently only works with payToPubKeyHash transactions. It will also * work in the future for standard payToScriptHash transactions that use a * single public key. * * However for multi-key and other complex transactions, this will only return * one of the keys or raise an error. Therefore, it is recommended for indexing * purposes to use Script#simpleInHash or Script#simpleOutHash instead. * * @deprecated */ Script.prototype.simpleInPubKey = function() { switch (this.getInType()) { case 'pubkeyhash': return this.chunks[1] case 'pubkey': // TODO: Theoretically, we could recover the pubkey from the sig here. // See https://bitcointalk.org/?topic=6430.0 throw new Error('Script does not contain pubkey') default: throw new Error('Encountered non-standard scriptSig') } } /** * Returns the affected address hash for this input. * * For standard transactions, this will return the hash of the pubKey that * can spend this output. * * In the future, for standard payToScriptHash inputs, this will return the * scriptHash. * * Note: This function provided for convenience. If you have the corresponding * scriptPubKey available, you are urged to use Script#simpleOutHash instead * as it is more reliable for non-standard payToScriptHash transactions. * * This method is useful for indexing transactions. */ Script.prototype.simpleInHash = function() { return crypto.hash160(this.simpleInPubKey()) } /** * Old name for Script#simpleInHash. * * @deprecated */ Script.prototype.simpleInPubKeyHash = Script.prototype.simpleInHash /** * Add an op code to the script. */ Script.prototype.writeOp = function(opcode) { this.buffer.push(opcode) this.chunks.push(opcode) } /** * Add a data chunk to the script. */ Script.prototype.writeBytes = function(data) { // FIXME: Script module doesn't support buffers yet if (Buffer.isBuffer(data)) data = Array.prototype.slice.call(data); assert(Array.isArray(data), "Expect a byte array. Got" + data) if (data.length < Opcode.map.OP_PUSHDATA1) { this.buffer.push(data.length) } else if (data.length <= 0xff) { this.buffer.push(Opcode.map.OP_PUSHDATA1) this.buffer.push(data.length) } else if (data.length <= 0xffff) { this.buffer.push(Opcode.map.OP_PUSHDATA2) this.buffer.push(data.length & 0xff) this.buffer.push((data.length >>> 8) & 0xff) } else { this.buffer.push(Opcode.map.OP_PUSHDATA4) this.buffer.push(data.length & 0xff) this.buffer.push((data.length >>> 8) & 0xff) this.buffer.push((data.length >>> 16) & 0xff) this.buffer.push((data.length >>> 24) & 0xff) } this.buffer = this.buffer.concat(data) this.chunks.push(data) } /** * Create an output for an address */ Script.createOutputScript = function(address, network) { assert(address instanceof Address) network = network || Network.bitcoin var script = new Script() // Standard pay-to-script-hash if (address.version === network.scriptHash) { script.writeOp(Opcode.map.OP_HASH160) script.writeBytes(address.hash) script.writeOp(Opcode.map.OP_EQUAL) return script } assert.strictEqual(address.version, network.pubKeyHash, 'Unknown address type') // Standard pay-to-pubkey-hash script.writeOp(Opcode.map.OP_DUP) script.writeOp(Opcode.map.OP_HASH160) script.writeBytes(address.hash) script.writeOp(Opcode.map.OP_EQUALVERIFY) script.writeOp(Opcode.map.OP_CHECKSIG) return script } /** * Extract pubkeys from a multisig script */ Script.prototype.extractPubkeys = function() { return this.chunks.filter(function(chunk) { return(chunk[0] == 4 && chunk.length == 65 || chunk[0] < 4 && chunk.length == 33) }) } // m [pubKeys ...] n OP_CHECKMULTISIG Script.createMultisigOutputScript = function(m, pubKeys) { var script = new Script() pubKeys = pubKeys.sort() script.writeOp(Opcode.map.OP_1 + m - 1) for (var i = 0; i < pubKeys.length; ++i) { script.writeBytes(pubKeys[i]) } script.writeOp(Opcode.map.OP_1 + pubKeys.length - 1) script.writeOp(Opcode.map.OP_CHECKMULTISIG) return script } // {signature} {pubKey} Script.createPubKeyHashScriptSig = function(signature, pubKey) { var script = new Script() script.writeBytes(signature) script.writeBytes(pubKey.toBuffer()) return script } // OP_0 [signatures ...] Script.createMultisigScriptSig = function(signatures) { var inScript = new Script() inScript.writeOp(Opcode.map.OP_0) signatures.map(function(sig) { inScript.writeBytes(sig) }) return inScript } // <scriptSig> {serialized scriptPubKey script} Script.createP2SHScriptSig = function(scriptSig, scriptPubKey) { var inScript = new Script(scriptSig.buffer) inScript.writeBytes(scriptPubKey.buffer) return inScript } // [signatures ...] {m [pubKeys ...] n OP_CHECKSIG} Script.createP2SHMultisigScriptSig = function(signatures, scriptPubKey) { assert(isMultisig.call(scriptPubKey)) var m = scriptPubKey.chunks[0] var k = m - (Opcode.map.OP_1 - 1) assert(k <= signatures.length, 'Not enough signatures provided') var scriptSig = Script.createMultisigScriptSig(signatures) return Script.createP2SHScriptSig(scriptSig, scriptPubKey) } Script.prototype.clone = function() { return new Script(this.buffer) } module.exports = Script
$(function() { $('.play-video').on('click', function(event) { event.preventDefault(); var $that = $(this), type = $that.data('type'), videoUrl = $that.attr('href'), $video; if (type === 'youtube') { $video = '<iframe id="video-player" src="'+videoUrl+'?rel=0&amp;showinfo=0&amp;controls=1&amp;autoplay=1" frameborder="0" allowfullscreen></iframe>'; } else if (type === 'vimeo') { $video = '<iframe id="video-player" src="'+videoUrl+'?autoplay=1&color=ffffff&title=0&byline=0&portrait=0&badge=0&embedded=true" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>'; } else if (type === 'dailymotion') { $video = '<iframe id="video-player" src="'+videoUrl+'?autoplay=1&color=ffffff&title=0&byline=0&portrait=0&badge=0" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>'; } else { $video = '<video id="video-player" controls autoplay> <source src="'+videoUrl+'">Your browser does not support the video tag.</video>'; } $('.video-container').find('#video-player').remove(); $('.video-container').prepend($video); $('.video-container').fadeIn(); }); $('.video-close').on('click', function(event) { event.preventDefault(); $('.video-container').fadeOut(600, function() { $('#video-player').remove(); }); }); });
var express = require('express'); var path = require('path'); var gameRouter = express.Router(); module.exports = function () { gameRouter.route('/') .get(function (req, res) { res.sendFile(path.join(__dirname, '../views/play.html')); }); return gameRouter; };
var classhou_1_1precondition__violation = [ [ "precondition_violation", "classhou_1_1precondition__violation.html#a99c5e409fa31753a4ee3cb769b54b9a1", null ] ];
const smallCups = document.querySelectorAll('.cup-small'); const liters = document.getElementById('liters'); const percentage = document.getElementById('percentage'); const remained = document.getElementById('remained'); updateBigCup(); smallCups.forEach((cup, idx) => { cup.addEventListener('click', () => { highlightCups(idx); }); }); function highlightCups(idx) { if (idx === 7 && smallCups[idx].classList.contains('full')) idx--; if ( smallCups[idx].classList.contains('full') && !smallCups[idx].nextElementSibling.classList.contains('full') ) { idx--; } smallCups.forEach((cup, idx2) => { if (idx2 <= idx) { cup.classList.add('full'); } else { cup.classList.remove('full'); } }); updateBigCup(); } function updateBigCup() { const fullCups = document.querySelectorAll('.cup-small.full').length; const totalCups = smallCups.length; if (fullCups === 0) { percentage.style.visibility = 'hidden'; percentage.style.height = 0; } else { percentage.style.visibility = 'visible'; percentage.style.height = `${(fullCups / totalCups) * 330}px`; percentage.innerText = `${(fullCups / totalCups) * 100}%`; } if (fullCups === totalCups) { remained.style.visibility = 'hidden'; remained.style.height = 0; } else { remained.style.visibility = 'visible'; liters.innerText = `${2 - (250 * fullCups) / 1000}L`; } }
var HeatTiles = require('./src/index'); // Globally expose HeatTiles in the browser if(typeof window !== 'undefined') { window.HeatTiles = HeatTiles; } // AMD Support if(typeof define === 'function' && define.amd) { define([], function() { return HeatTiles; }); } // CommonJS Support module.exports = HeatTiles;
const fs = require('fs') const turf = require('@turf/turf') const geohash = require('ngeohash'); const highzoomStream = fs.createWriteStream("./wind_highzoom.geojsonld"); const midzoomStream = fs.createWriteStream("./wind_midzoom.geojsonld"); const lowzoomStream = fs.createWriteStream("./wind_lowzoom.geojsonld"); let lowZoomDistance = 180000 let midZoomDistance = 20000 let highZoomDistance = 6000 // number of steps to use in the animation const steps = 25; function waitOpen(stream) { return new Promise(resolve => { stream.once('open', async function(fd) { resolve() }) }) } async function run() { await Promise.all([ waitOpen(lowzoomStream), ]) process( lowzoomStream, ) } run() async function process( lowzoomStream, ) { const filedata = fs.readFileSync('./data/weather_16.json', 'utf8').toString().split("\n") const hashmap = {} let i = 0; for(const line of filedata) { i++; let json; try { json = JSON.parse(line) } catch (err) { // last line is empty if (line != '') { console.warn(`Unable to JSON parse ${line}`) } break } const lat = json.city.coord.lat const lon = json.city.coord.lon const midZoomHash = geohash.encode(lat, lon, 4); let midZoom = false if (!hashmap[midZoomHash]) { hashmap[midZoomHash] = json midZoom = true } const lowZoomHash = geohash.encode(lat, lon, 3); let lowZoom = false if (!hashmap[lowZoomHash]) { hashmap[lowZoomHash] = json lowZoom = true } if (lowZoom) { await writePointsAlongLine(lowzoomStream, json, lowZoomDistance) } if (midZoom) { await writePointsAlongLine(midzoomStream, json, midZoomDistance) } await writePointsAlongLine(highzoomStream, json, highZoomDistance) } } async function writePointsAlongLine(stream, json, distance) { const windDeg = json.wind.deg const city = json.city.name const lat = json.city.coord.lat const lon = json.city.coord.lon const windDistance = distance // meters of wind distance const oppositeBearing = windDeg + 180 const originBearing = oppositeBearing > 360 ? oppositeBearing - 360 : oppositeBearing const origin = turf.destination( turf.point([ lon, lat, ]), windDistance / 2 / 1000, originBearing, ) const dest = turf.destination( turf.point([ lon, lat, ]), windDistance / 2 / 1000, windDeg, ) const feature = { "type": "FeatureCollection", "features": [ origin, turf.point([ lon, lat, ]), dest, ] } const features = makePoints( origin.geometry.coordinates, dest.geometry.coordinates, ) feature.features = feature.features.concat(features) for (const v of features) { v.properties.distance = distance let writeResult = stream.write( JSON.stringify(v) ) if (writeResult===false) { await new Promise(resolve => stream.once('drain', resolve)) } writeResult = stream.write('\n') if (writeResult===false) { await new Promise(resolve => stream.once('drain', resolve)) } } } function makePoints(origin, dest) { const line = turf.lineString([ dest, origin, ]) // Calculate the distance in kilometers between route start/end point. const lineDistance = turf.length(line); const arc = []; let j = 1; // Draw an arc between the `origin` & `destination` of the two points for (let i = 0; i < lineDistance; i += lineDistance / steps) { const segment = turf.along(line, i); segment.properties = { value: j, } arc.push(segment); j++ } return arc }
import { logoutSaga, checkAuthTimeoutSaga, authUserSaga, authCheckStateSaga } from './auth'; import { fetchOrdersSaga, purchaseBurgerSaga } from './order'; import { initIngredientsSaga } from './burgerBuilder'; import { takeEvery, all } from 'redux-saga/effects'; import { AUTH_INITIATE_LOGOUT, AUTH_CHECK_TIMEOUT, INIT_INGREDIENTS, AUTH_CHECK_STATE, PURCHASE_BURGER, AUTH_USER, FETCH_ORDERS, } from '../actions/actionTypes'; export function* watchAuth() { yield all([ takeEvery(AUTH_INITIATE_LOGOUT, logoutSaga), takeEvery(AUTH_CHECK_TIMEOUT, checkAuthTimeoutSaga), takeEvery(AUTH_USER, authUserSaga), takeEvery(AUTH_CHECK_STATE, authCheckStateSaga), ]); } export function* watchBurgerBuilder() { yield takeEvery(INIT_INGREDIENTS, initIngredientsSaga); } export function* watchOrder() { yield all([ takeEvery(PURCHASE_BURGER, purchaseBurgerSaga), takeEvery(FETCH_ORDERS, fetchOrdersSaga), ]); }
/* * @license FusionCharts JavaScript Library * Copyright FusionCharts Technologies LLP * License Information at <http://www.fusioncharts.com/license> * * @author FusionCharts Technologies LLP * @version fusioncharts/3.3.1-sr3.21100 * @id fusionmaps.Belgium.20.10-30-2012 06:07:26 */ FusionCharts(["private","modules.renderer.js-belgium",function(){var p=this,k=p.hcLib,n=k.chartAPI,h=k.moduleCmdQueue,a=k.injectModuleDependency,i="M",j="L",c="Z",f="Q",b="left",q="right",t="center",v="middle",o="top",m="bottom",s="maps",l=false&&!/fusioncharts\.com$/i.test(location.hostname),r=!!n.geo,d,e,u,g; d=[{name:"Belgium",revision:20,creditLabel:l,standaloneInit:true,baseWidth:390,baseHeight:320,baseScaleFactor:10,entities:{"05":{outlines:[[i,3423,1848,f,3415,1839,3406,1839,3392,1838,3375,1812,3296,1824,3288,1801,j,3278,1801,f,3275,1810,3270,1823,j,3270,1878,f,3273,1879,3280,1878,3287,1878,3289,1887,3294,1886,3294,1892,3294,1898,3277,1913,3269,1920,3233,1919,3205,1917,3185,1920,3176,1929,3158,1929,3145,1929,3146,1912,3145,1903,3154,1891,j,3154,1876,f,3149,1873,3135,1859,3120,1843,3120,1839,3129,1835,3129,1812,3129,1801,3125,1799,3117,1793,3118,1787,j,3114,1787,f,3100,1784,3097,1785,3094,1775,3076,1774,j,3068,1764,f,3054,1762,3053,1762,3039,1757,3033,1748,3021,1733,3013,1733,3006,1734,3001,1728,2996,1721,2992,1722,2970,1723,2959,1721,2924,1686,2921,1686,2914,1693,2912,1695,j,2877,1695,f,2873,1690,2874,1685,j,2857,1684,f,2835,1684,2835,1696,2835,1706,2843,1718,2842,1736,2828,1736,2815,1735,2809,1752,2809,1752,2810,1753,2817,1763,2819,1770,2818,1771,2819,1771,2818,1778,2817,1792,2806,1802,2807,1809,2808,1814,2795,1824,2782,1833,2782,1840,j,2796,1855,f,2797,1855,2817,1862,j,2817,1883,2787,1913,f,2760,1935,2759,1941,j,2741,1941,f,2738,1946,2738,1956,j,2688,1956,f,2687,1955,2683,1965,j,2664,1980,f,2651,1988,2651,1999,2651,2008,2664,2021,2677,2034,2677,2039,2676,2049,2688,2060,2694,2065,2706,2075,2715,2079,2715,2087,2715,2090,2697,2104,2679,2118,2679,2124,2679,2133,2686,2137,2686,2138,2670,2158,2664,2162,2658,2162,j,2640,2162,f,2629,2162,2622,2169,2614,2176,2610,2177,2569,2177,2567,2177,2512,2176,2512,2161,j,2506,2161,f,2504,2163,2500,2167,2497,2170,2497,2179,2497,2201,2495,2203,2481,2211,2483,2219,2483,2220,2476,2238,2448,2258,2439,2268,2430,2275,2432,2285,2432,2294,2431,2311,2431,2317,2443,2329,2445,2331,2447,2352,j,2476,2353,f,2478,2348,2478,2345,j,2499,2345,f,2501,2351,2506,2357,2519,2353,2527,2361,2535,2368,2534,2379,2533,2391,2540,2400,2548,2410,2548,2419,2548,2451,2520,2465,j,2473,2505,f,2459,2519,2454,2525,j,2434,2544,f,2430,2546,2430,2577,2428,2605,2425,2609,j,2426,2622,2427,2622,2438,2622,2438,2636,2436,2637,2436,2647,2448,2649,2448,2662,2476,2662,2476,2667,2475,2673,2514,2673,2514,2686,2539,2686,2539,2700,2552,2700,2552,2725,f,2567,2725,2568,2729,j,2568,2751,2587,2751,2587,2762,f,2608,2755,2603,2778,j,2617,2778,2617,2790,2720,2790,2720,2802,f,2724,2803,2733,2803,j,2735,2814,2748,2814,2748,2830,2759,2830,2759,2856,2758,2857,2746,2857,2746,2904,2773,2904,2772,2894,f,2781,2894,2784,2893,j,2784,2882,f,2786,2881,2792,2881,j,2798,2881,2798,2892,2837,2892,2837,2908,2851,2908,f,2848,2914,2852,2918,2857,2923,2863,2921,j,2863,2958,2875,2958,2875,2968,f,2883,2966,2887,2970,2886,2973,2889,2980,2889,2980,2877,2984,j,2877,2998,2890,2998,2890,3062,f,2894,3063,2901,3063,j,2901,3072,2928,3072,f,2930,3068,2930,3061,j,2980,3061,2980,3035,3019,3035,3019,3045,3058,3045,3058,3008,3070,3008,3070,2997,3076,2997,f,3087,2999,3109,2997,3126,2997,3124,3007,3162,3007,3173,3008,3184,3008,3188,3009,j,3188,2983,3226,2984,3226,2997,3262,2997,3262,2983,3289,2983,3289,2970,3304,2970,3304,2932,3289,2932,3289,2921,3301,2921,3302,2902,3313,2902,3313,2867,3328,2867,3328,2853,3342,2853,3341,2842,3328,2842,3328,2803,3302,2803,3302,2762,3316,2762,f,3313,2749,3300,2751,j,3300,2725,3262,2725,f,3262,2712,3262,2707,3261,2698,3250,2700,j,3250,2672,3238,2672,3238,2660,f,3224,2665,3223,2650,3223,2630,3223,2623,3187,2630,3185,2621,3184,2619,3184,2583,j,3173,2583,3173,2558,3187,2558,3187,2516,3200,2516,3200,2503,3213,2503,3213,2492,3197,2492,f,3201,2479,3191,2479,3178,2480,3173,2478,j,3173,2454,3186,2454,f,3185,2439,3186,2432,3187,2421,3202,2426,j,3202,2387,3210,2387,3210,2378,f,3227,2379,3224,2363,3249,2362,3250,2361,j,3251,2286,3277,2286,3277,2261,3289,2259,3289,2216,f,3287,2206,3288,2201,3288,2192,3300,2197,j,3300,2182,3313,2182,f,3315,2176,3315,2143,j,3327,2143,3327,2130,3367,2130,3367,2118,3381,2118,3381,2054,3417,2054,f,3417,2044,3418,2042,j,3434,2042,f,3436,2029,3436,2017,3436,2003,3434,2001,3425,1992,3426,1987,3427,1981,3417,1974,3412,1969,3412,1955,j,3413,1897,f,3412,1888,3424,1881,3429,1878,3430,1865,f,3430,1850,3423,1848,c]],label:"Luxembourg",shortLabel:"LU",labelPosition:[293.1,237.8],labelAlignment:[t,v]},"03":{outlines:[[i,3417,1177,j,3352,1177,3352,1165,3340,1165,3339,1177,3290,1177,3290,1201,3303,1201,f,3304,1203,3305,1212,j,3305,1224,3288,1224,3288,1229,f,3289,1230,3290,1234,j,3290,1241,3218,1241,3212,1240,3212,1216,3199,1216,3199,1188,3107,1188,3107,1179,f,3110,1142,3099,1139,j,3099,1136,3087,1136,3087,1125,3080,1124,f,3075,1123,3068,1124,3066,1124,3064,1125,3058,1126,3052,1129,j,3044,1129,f,3043,1136,3044,1153,3043,1160,3037,1159,3029,1158,3026,1159,j,3026,1165,3013,1165,f,3014,1175,2998,1171,j,2997,1177,2981,1177,2981,1181,2977,1181,f,2975,1181,2973,1181,j,2973,1188,2957,1188,2957,1193,2939,1193,2939,1199,2928,1199,2928,1207,2921,1207,2921,1222,f,2920,1227,2912,1230,2904,1233,2904,1236,2903,1240,2896,1243,2894,1246,2886,1246,j,2886,1251,2879,1251,f,2880,1242,2874,1241,j,2874,1233,2871,1233,2871,1228,2866,1228,2866,1223,2862,1223,2862,1246,2856,1246,2857,1251,2851,1251,2851,1259,2820,1259,f,2818,1251,2812,1252,j,2812,1246,2805,1246,f,2807,1242,2804,1240,2801,1238,2797,1239,2797,1234,2797,1231,j,2793,1231,2793,1216,2787,1216,2787,1223,2750,1223,2750,1229,f,2742,1228,2742,1236,j,2736,1236,2736,1241,f,2718,1242,2718,1263,2718,1266,2718,1270,j,2715,1270,2715,1263,f,2711,1264,2708,1261,2703,1256,2702,1256,2699,1255,2696,1250,2694,1246,2689,1250,j,2689,1243,2686,1243,f,2684,1245,2682,1245,j,2682,1251,2678,1251,2678,1262,2670,1263,2670,1268,2652,1268,f,2653,1255,2650,1250,j,2645,1250,2645,1256,2641,1256,f,2641,1257,2642,1258,j,2642,1265,f,2600,1265,2585,1265,j,2585,1278,f,2587,1278,2588,1277,j,2592,1277,2592,1284,2599,1285,2599,1293,2591,1293,2591,1298,2557,1298,f,2556,1290,2550,1290,2541,1290,2540,1290,2533,1283,2528,1277,j,2517,1277,2517,1287,2498,1287,f,2495,1281,2489,1281,2482,1281,2481,1280,2477,1278,2475,1273,2474,1269,2468,1270,j,2468,1265,f,2463,1263,2461,1263,j,2461,1236,f,2461,1232,2455,1230,2451,1229,2447,1224,j,2435,1213,f,2434,1235,2434,1247,2433,1259,2441,1272,j,2441,1275,f,2431,1282,2431,1290,j,2432,1319,f,2436,1347,2425,1352,2416,1356,2405,1375,j,2405,1376,f,2419,1381,2418,1400,2417,1403,2428,1409,2432,1413,2439,1422,2459,1440,2458,1451,2458,1456,2468,1465,2475,1470,2472,1483,2472,1485,2480,1496,2479,1510,2481,1516,2485,1529,2507,1528,j,2535,1559,f,2540,1568,2545,1569,2570,1563,2573,1589,2572,1592,2582,1606,2590,1619,2596,1619,j,2601,1619,f,2600,1608,2609,1608,2614,1607,2626,1620,2637,1631,2639,1635,2643,1642,2658,1653,2663,1657,2664,1672,2665,1683,2660,1688,2652,1691,2652,1699,2652,1701,2660,1708,2667,1714,2667,1723,2682,1719,2689,1725,2693,1728,2701,1737,j,2701,1757,2756,1757,2766,1750,f,2771,1749,2784,1750,2805,1749,2809,1752,2815,1735,2828,1736,2842,1736,2843,1718,2835,1706,2835,1696,2835,1684,2857,1684,j,2874,1685,f,2873,1690,2877,1695,j,2912,1695,f,2914,1693,2921,1686,2924,1686,2959,1721,2970,1723,2992,1722,2996,1721,3001,1728,3006,1734,3013,1733,3021,1733,3033,1748,3039,1757,3053,1762,3054,1762,3068,1764,j,3076,1774,f,3094,1775,3097,1785,3100,1784,3114,1787,j,3118,1787,f,3117,1793,3125,1799,3129,1801,3129,1812,3129,1835,3120,1839,3120,1843,3135,1859,3149,1873,3154,1876,j,3154,1891,f,3145,1903,3146,1912,3145,1929,3158,1929,3176,1929,3185,1920,3205,1917,3233,1919,3269,1920,3277,1913,3294,1898,3294,1892,3294,1886,3289,1887,3287,1878,3280,1878,3273,1879,3270,1878,j,3270,1823,f,3275,1810,3278,1801,j,3288,1801,f,3296,1824,3375,1812,3392,1838,3406,1839,3415,1839,3423,1848,3430,1850,3430,1865,3429,1878,3424,1881,3412,1888,3413,1897,j,3412,1955,f,3412,1969,3417,1974,3427,1981,3426,1987,3425,1992,3434,2001,3436,2003,3436,2017,3436,2029,3434,2042,j,3434,2042,3434,2067,3444,2067,3444,2078,3459,2078,3459,2093,3496,2093,3496,2080,3522,2080,3522,2116,3528,2114,3536,2114,3536,2129,3563,2129,3563,2063,3585,2063,3585,2054,f,3590,2052,3598,2052,3603,2050,3601,2042,j,3601,2002,3588,2002,3588,1974,3601,1974,3601,1963,3610,1963,3610,1951,3622,1951,f,3616,1937,3634,1937,3652,1937,3651,1925,j,3691,1925,3691,1885,3704,1885,f,3705,1873,3706,1858,j,3720,1858,f,3721,1849,3722,1845,j,3742,1845,f,3744,1845,3746,1845,3758,1847,3755,1859,j,3765,1859,3765,1845,3791,1845,3791,1834,3807,1834,3808,1831,3808,1797,3791,1795,3791,1791,3793,1790,3793,1781,3781,1781,f,3786,1769,3767,1771,j,3767,1757,3755,1757,3755,1727,3769,1727,3769,1679,3778,1679,3779,1675,3779,1643,3767,1643,3767,1628,f,3749,1629,3751,1616,j,3739,1614,3739,1571,3727,1571,3727,1565,f,3704,1565,3702,1563,j,3702,1551,f,3636,1549,3611,1549,j,3611,1539,f,3595,1542,3596,1524,3599,1503,3597,1497,j,3585,1497,3585,1472,f,3589,1471,3600,1471,j,3600,1459,3613,1459,3613,1445,3640,1445,f,3634,1428,3651,1434,3652,1432,3653,1413,3654,1402,3664,1405,j,3665,1370,f,3649,1371,3641,1370,3625,1370,3625,1358,3604,1358,3587,1356,j,3587,1345,3570,1345,3570,1316,3553,1317,3553,1304,3546,1304,3546,1280,3528,1280,3528,1264,f,3519,1268,3519,1241,j,3508,1241,3508,1228,3507,1228,3504,1228,3457,1228,3457,1216,3442,1216,3442,1203,3430,1203,f,3432,1197,3428,1191,3423,1184,3417,1188,c]],label:"Liege",shortLabel:"LI",labelPosition:[317.4,149],labelAlignment:[t,v]},"04":{outlines:[[i,3320,1175,j,3315,1175,3315,1164,3311,1161,3310,1138,f,3301,1137,3299,1137,3296,1137,3290,1144,j,3283,1144,3283,1148,f,3278,1147,3278,1149,3277,1150,3277,1154,j,3274,1154,3274,1160,3271,1160,3271,1152,3267,1152,3267,1144,3260,1144,f,3258,1147,3258,1149,j,3250,1149,f,3249,1151,3249,1154,j,3242,1154,3242,1161,3239,1161,3239,1158,3235,1158,f,3234,1156,3234,1154,j,3231,1154,f,3232,1151,3229,1150,3226,1149,3226,1146,j,3216,1146,3215,1139,3211,1139,3211,1127,3207,1127,3207,1118,3200,1118,3200,1123,3194,1123,3194,1128,3188,1128,f,3188,1133,3186,1134,3183,1133,3183,1139,j,3178,1139,3178,1148,3175,1148,3175,1161,3172,1161,3172,1153,f,3165,1150,3160,1150,3159,1147,3159,1142,j,3153,1142,3153,1149,3143,1154,3143,1160,f,3141,1161,3138,1167,3135,1173,3130,1174,3125,1174,3121,1177,3120,1177,3108,1188,j,3200,1188,3200,1216,3213,1216,3213,1240,3218,1241,3291,1241,3291,1234,f,3290,1230,3289,1229,j,3289,1224,3306,1224,3306,1212,f,3304,1203,3304,1201,j,3291,1201,3291,1177,3320,1177,c],[i,3037,526,f,3026,525,3025,523,3015,522,3013,518,3003,517,3002,513,3001,511,2991,509,2987,503,2986,503,2984,502,2979,502,2976,497,2970,497,2966,496,2964,494,2961,491,2956,491,2952,491,2949,488,j,2946,484,2946,459,f,2946,459,2946,458,2949,433,2944,427,2928,408,2926,406,2911,393,2906,388,2899,380,2897,381,j,2879,381,2879,375,2872,375,2872,381,2866,381,f,2866,383,2865,388,2860,387,2858,391,2856,394,2857,398,j,2850,398,2850,405,2841,405,f,2841,400,2840,399,j,2831,399,2831,405,f,2826,403,2826,411,j,2823,411,2823,422,2817,422,2817,432,2812,432,2812,439,2807,439,f,2805,435,2800,435,2795,435,2794,433,2791,428,2781,428,2769,420,2767,420,2755,420,2753,417,j,2736,417,2736,438,f,2718,438,2714,438,2713,438,2712,438,2709,438,2699,438,2691,437,2687,435,2686,434,2678,433,2672,433,2670,427,j,2660,427,f,2662,432,2654,432,j,2642,432,2642,437,2637,437,f,2638,438,2638,439,2638,441,2628,448,2618,455,2619,461,j,2619,492,f,2620,515,2627,521,2639,531,2661,554,j,2661,592,f,2663,601,2663,611,2663,616,2653,620,2643,623,2644,631,j,2640,631,2640,635,2634,635,2634,630,2630,630,f,2631,623,2626,623,2619,623,2617,618,j,2613,618,2613,624,2609,624,f,2609,630,2608,633,2608,634,2603,638,2603,645,2601,647,2595,651,2596,653,2583,650,2577,655,2571,661,2565,660,2552,658,2547,660,2544,661,2536,669,2507,693,2504,706,j,2496,706,f,2496,708,2495,710,2495,710,2495,711,2486,710,2484,711,2480,711,2480,718,2456,717,2455,720,2453,723,2443,723,2435,722,2436,728,j,2429,728,2429,735,2422,735,2422,749,2417,749,f,2419,757,2410,758,2406,767,2404,768,2406,772,2400,775,j,2400,782,2417,783,f,2421,783,2422,788,2422,792,2426,791,j,2426,801,f,2432,801,2433,805,j,2452,805,2452,799,2460,799,f,2466,807,2468,811,j,2479,811,2479,803,f,2487,806,2489,800,2489,791,2491,787,2492,767,2493,760,j,2523,760,f,2529,767,2533,769,2535,772,2544,779,2549,784,2561,799,j,2561,805,2554,805,2554,811,2531,811,2531,801,2526,801,2526,813,f,2527,813,2529,814,2530,815,2533,817,j,2533,839,f,2527,838,2524,839,2519,839,2521,844,j,2516,844,f,2518,849,2511,851,2504,852,2506,857,j,2500,857,2500,860,f,2493,859,2492,863,j,2492,886,f,2493,894,2490,896,2488,898,2480,898,j,2480,903,2474,903,f,2473,902,2472,902,j,2472,908,2463,908,2463,916,2456,916,2456,934,2460,934,f,2461,936,2461,941,2462,944,2465,945,2468,946,2469,956,2475,955,2475,961,j,2484,961,2486,955,2493,955,2493,962,f,2497,960,2498,968,2503,967,2504,974,j,2511,974,f,2511,970,2512,968,j,2524,968,2524,962,2536,962,2536,953,2546,953,2546,962,2551,962,2551,968,2585,968,f,2584,972,2590,973,j,2590,983,f,2593,983,2599,986,j,2599,1001,f,2599,1006,2592,1008,j,2592,1022,f,2583,1020,2585,1032,j,2577,1032,2577,1027,2573,1027,2573,1021,2568,1021,2568,1043,2562,1043,2562,1053,2556,1053,2556,1059,2556,1060,f,2556,1064,2553,1067,2550,1070,2550,1073,2550,1077,2551,1094,2551,1106,2545,1107,j,2545,1120,f,2553,1119,2557,1120,j,2557,1138,f,2555,1138,2551,1138,2551,1141,2552,1143,j,2552,1150,2527,1150,2527,1211,2519,1211,2519,1229,2527,1229,2527,1236,f,2531,1237,2533,1237,j,2533,1248,f,2528,1249,2526,1251,2526,1260,2525,1261,2525,1262,2525,1277,j,2529,1277,f,2533,1283,2541,1290,2542,1290,2551,1290,2557,1290,2558,1298,j,2592,1298,2592,1293,2599,1293,2599,1285,2593,1284,2593,1277,2588,1277,f,2587,1278,2585,1278,j,2585,1265,f,2601,1265,2642,1265,j,2642,1258,f,2641,1257,2642,1256,j,2645,1256,2645,1250,2651,1250,f,2653,1255,2652,1268,j,2671,1268,2671,1263,2679,1262,2679,1251,2683,1251,2683,1245,f,2685,1245,2687,1243,j,2690,1243,2690,1250,f,2695,1246,2697,1250,2699,1255,2703,1256,2704,1256,2708,1261,2712,1264,2715,1263,j,2715,1270,2719,1270,f,2718,1266,2719,1263,2719,1242,2737,1241,j,2737,1236,2742,1236,f,2743,1228,2750,1229,j,2750,1223,2788,1223,2788,1216,2793,1216,2793,1231,2797,1231,f,2798,1234,2798,1239,2801,1238,2804,1240,2808,1242,2806,1246,j,2812,1246,2812,1252,f,2818,1251,2820,1259,j,2852,1259,2852,1251,2857,1251,2857,1246,2862,1246,2862,1223,2866,1223,2866,1228,2871,1228,2871,1233,2875,1233,2875,1241,f,2880,1242,2879,1251,j,2886,1251,2886,1246,f,2894,1246,2897,1243,2903,1240,2904,1236,2904,1233,2912,1230,2920,1227,2921,1222,j,2921,1207,2928,1207,2928,1199,2940,1199,2940,1193,2958,1193,2958,1188,2973,1188,2973,1181,f,2976,1181,2977,1181,j,2981,1181,2981,1177,2998,1177,2998,1171,f,3014,1175,3013,1165,j,3026,1165,3026,1159,f,3029,1158,3037,1159,3044,1160,3044,1153,3044,1136,3045,1129,j,3052,1129,f,3058,1126,3064,1125,3066,1124,3068,1124,3076,1123,3080,1124,j,3081,1120,3093,1120,3093,1117,f,3090,1116,3089,1115,j,3089,1110,3080,1110,f,3079,1113,3079,1116,3076,1116,3073,1116,j,3073,1112,3066,1112,f,3064,1110,3054,1107,3052,1106,3051,1102,3051,1098,3050,1097,3044,1096,3044,1094,j,3044,1086,f,3037,1084,3038,1074,3035,1074,3033,1073,j,3033,1060,3039,1060,f,3039,1049,3039,1031,j,3043,1031,3043,1024,f,3049,1024,3052,1021,3055,1017,3061,1019,j,3061,1014,3069,1014,3069,1010,3074,1010,f,3074,1007,3074,1005,3075,1001,3079,999,3081,998,3081,987,3090,988,3086,967,j,3102,967,f,3103,968,3104,971,3105,973,3107,973,j,3113,972,3113,952,f,3113,949,3117,946,3120,944,3118,939,j,3118,938,f,3120,935,3125,935,3125,928,3126,926,j,3131,926,3131,918,f,3137,918,3138,909,j,3143,909,3143,900,3149,900,3149,897,f,3144,896,3142,895,j,3142,889,f,3132,888,3131,888,3128,888,3127,890,3126,893,3121,893,j,3121,899,3116,899,3116,905,3110,905,3110,897,f,3106,895,3107,892,3118,877,3119,877,3123,876,3126,871,3127,869,3130,864,3147,838,3156,834,j,3156,821,f,3154,821,3147,818,j,3147,801,f,3159,798,3161,791,j,3166,791,f,3166,788,3165,786,3160,787,3158,784,3155,781,3152,781,3148,782,3145,779,3141,775,3140,775,j,3140,769,3147,769,3147,761,3154,761,3154,736,3185,736,f,3185,729,3185,711,j,3191,711,3191,701,f,3187,701,3185,701,3186,694,3176,694,j,3176,687,3181,687,3181,682,3196,682,f,3195,684,3198,689,j,3208,689,3208,675,f,3213,673,3213,669,3213,665,3213,664,j,3203,664,f,3204,659,3198,659,3191,660,3189,660,3189,659,3188,656,j,3188,649,3195,649,3195,645,f,3193,641,3193,640,3199,643,3199,638,3199,631,3204,630,j,3225,630,3225,622,f,3231,623,3231,615,3230,607,3230,603,j,3229,600,f,3215,594,3214,579,j,3209,578,3209,572,3203,572,3203,578,3193,578,3193,583,3181,583,f,3181,584,3181,588,j,3171,588,3171,595,3159,595,3159,591,3155,591,f,3154,577,3154,556,j,3148,556,3148,549,3138,549,3138,543,3113,543,3113,550,3047,550,f,3048,540,3037,543,c]],label:"Limburg",shortLabel:"LM",labelPosition:[280.9,83.6],labelAlignment:[t,v]},"06":{outlines:[[i,2418,1401,f,2419,1382,2405,1376,j,2405,1376,f,2398,1363,2391,1363,2382,1383,2354,1388,2328,1390,2327,1391,2316,1401,2304,1402,2292,1408,2282,1412,2263,1419,2261,1423,2257,1428,2246,1428,2235,1428,2233,1430,2225,1437,2208,1437,2187,1437,2184,1432,2182,1424,2180,1421,2177,1412,2171,1414,2173,1430,2149,1430,2120,1429,2116,1434,2112,1436,2110,1436,2106,1437,2106,1445,j,2106,1466,f,2106,1467,2097,1494,j,2084,1494,f,2073,1478,2057,1478,2041,1478,2038,1481,2034,1484,2031,1503,2030,1511,2030,1525,2028,1536,2017,1542,j,2018,1542,2019,1585,f,2038,1603,2044,1606,2047,1622,2041,1633,2033,1645,2033,1652,2032,1664,2035,1665,2042,1668,2048,1675,2051,1678,2069,1699,2069,1700,2058,1708,2045,1717,2042,1726,j,2041,1784,f,2040,1794,2042,1815,2043,1833,2035,1837,2014,1844,2014,1846,2010,1854,1987,1854,1964,1853,1962,1853,1959,1851,1958,1840,j,1918,1840,1909,1848,f,1900,1855,1896,1855,1879,1862,1870,1865,1856,1868,1845,1877,1825,1888,1826,1893,j,1822,1893,1822,1893,1809,1893,f,1807,1893,1803,1901,1797,1906,1792,1907,1783,1907,1779,1912,1773,1919,1758,1922,1746,1924,1746,1937,1746,1957,1773,1955,1782,1966,1795,1983,j,1799,1983,f,1802,1971,1821,1971,1839,1971,1843,1976,1848,1981,1849,2000,1848,2022,1841,2027,1836,2030,1836,2043,1837,2050,1837,2062,j,1823,2062,1823,2114,f,1838,2125,1837,2141,j,1837,2214,f,1848,2230,1848,2233,1845,2254,1852,2259,1860,2264,1860,2281,1860,2311,1860,2314,1861,2320,1873,2331,j,1873,2366,f,1873,2374,1885,2384,1888,2389,1887,2410,j,1894,2410,1894,2427,1947,2426,1948,2415,1985,2415,1985,2404,1997,2404,1997,2390,2022,2390,2022,2376,f,2031,2376,2036,2375,j,2034,2366,f,2073,2366,2099,2364,j,2099,2351,f,2128,2351,2139,2350,j,2139,2297,2152,2297,2152,2262,f,2149,2252,2149,2247,j,2140,2247,2139,2222,f,2149,2227,2150,2214,2149,2200,2150,2197,j,2164,2197,2164,2182,2201,2181,2201,2152,2218,2152,2218,2133,2240,2133,2240,2117,2255,2117,2255,2105,2319,2105,2319,2131,2309,2131,2309,2171,2282,2171,2282,2207,2272,2207,2272,2217,2257,2217,2257,2244,f,2262,2247,2271,2247,j,2271,2277,2270,2284,2255,2284,2255,2315,f,2256,2320,2257,2332,2256,2343,2243,2339,j,2243,2353,f,2235,2353,2230,2353,j,2230,2382,2231,2388,2242,2389,2242,2402,f,2258,2400,2255,2415,j,2280,2415,f,2280,2419,2282,2427,j,2292,2427,2294,2441,2319,2441,f,2319,2447,2320,2448,j,2320,2481,2311,2481,f,2311,2491,2306,2521,2298,2521,2296,2521,2292,2523,2294,2532,j,2282,2532,2282,2545,f,2287,2546,2298,2547,j,2298,2569,2308,2569,2308,2611,2297,2611,2297,2648,2306,2648,2306,2657,2385,2657,2385,2649,2410,2648,2410,2609,2425,2609,f,2428,2606,2430,2577,2430,2547,2434,2545,j,2454,2526,f,2459,2519,2473,2505,j,2520,2466,f,2548,2451,2548,2420,2548,2410,2540,2401,2533,2391,2534,2380,2535,2368,2527,2361,2519,2353,2506,2358,2501,2352,2499,2346,j,2478,2346,f,2478,2348,2476,2353,j,2447,2353,f,2445,2332,2443,2329,2431,2318,2431,2311,2432,2294,2432,2286,2430,2276,2439,2269,2448,2259,2476,2238,2483,2220,2483,2219,2481,2212,2495,2204,2497,2202,2497,2179,2497,2170,2500,2168,2504,2164,2506,2162,j,2512,2162,f,2512,2177,2567,2177,2569,2177,2610,2177,2614,2176,2622,2169,2629,2163,2640,2163,j,2658,2163,f,2664,2163,2670,2158,2686,2139,2686,2138,2679,2133,2679,2124,2679,2118,2697,2105,2715,2091,2715,2088,2715,2079,2706,2076,2694,2066,2688,2060,2676,2050,2677,2039,2677,2034,2664,2021,2651,2009,2651,1999,2651,1988,2664,1981,j,2683,1965,f,2687,1956,2688,1956,j,2738,1956,f,2738,1947,2741,1942,j,2759,1942,f,2760,1935,2787,1914,j,2817,1883,2817,1863,f,2797,1855,2796,1855,j,2782,1840,f,2782,1834,2795,1824,2808,1814,2807,1809,2806,1803,2817,1792,2818,1779,2819,1772,2818,1771,2819,1771,2817,1763,2810,1753,2809,1753,2809,1753,2805,1750,2784,1750,2771,1749,2766,1750,j,2756,1758,2701,1758,2701,1737,f,2693,1729,2689,1726,2682,1720,2667,1723,2667,1715,2660,1708,2652,1701,2652,1700,2652,1692,2660,1688,2665,1683,2664,1673,2663,1658,2658,1653,2643,1642,2639,1636,2637,1631,2626,1620,2614,1608,2609,1608,2600,1608,2601,1619,j,2596,1620,f,2590,1620,2582,1606,2572,1592,2573,1589,2570,1563,2545,1570,2540,1569,2535,1560,j,2507,1529,f,2485,1530,2481,1517,2479,1510,2480,1496,2472,1486,2472,1484,2475,1471,2468,1465,2458,1456,2458,1451,2459,1441,2439,1423,2432,1413,2428,1410,f,2417,1404,2418,1401,c]],label:"Namur",shortLabel:"NA",labelPosition:[235,180.6],labelAlignment:[t,v]},"09":{outlines:[[i,2173,1136,j,2168,1136,2168,1141,2162,1141,2162,1148,2157,1148,f,2156,1150,2156,1154,j,2149,1154,2149,1160,2092,1160,f,2088,1154,2083,1154,2083,1151,2082,1147,j,2076,1147,2076,1141,2073,1141,2073,1164,f,2070,1164,2069,1164,j,2069,1188,2074,1188,f,2073,1191,2076,1198,2079,1198,2081,1199,2081,1206,2082,1210,j,2087,1210,2087,1214,2080,1214,2080,1220,f,2075,1220,2073,1221,j,2073,1232,2059,1232,2059,1237,2034,1237,f,2034,1227,2034,1225,2027,1223,2027,1219,j,2027,1200,f,2025,1199,2024,1199,j,2021,1199,2021,1208,2017,1208,2017,1213,f,2013,1211,2010,1222,2010,1222,2006,1225,2002,1228,2004,1232,j,1983,1232,1983,1237,1969,1237,1969,1241,1964,1241,1964,1253,1960,1253,1960,1258,1955,1258,1955,1252,1951,1252,f,1949,1244,1941,1246,1943,1241,1939,1241,1935,1241,1934,1240,j,1934,1234,1929,1234,1929,1212,1907,1212,1907,1216,1893,1216,f,1892,1222,1879,1232,1868,1241,1862,1244,1861,1244,1834,1246,1831,1246,1824,1250,1818,1253,1812,1251,j,1812,1274,1793,1274,f,1789,1270,1790,1266,1785,1267,1784,1264,1784,1259,1784,1257,1781,1254,1780,1246,j,1775,1246,1775,1251,1769,1251,1769,1265,1765,1265,f,1762,1266,1758,1266,1760,1271,1753,1271,j,1753,1278,1748,1278,1748,1285,f,1748,1286,1743,1288,1741,1296,1737,1297,1727,1299,1705,1299,j,1705,1303,1697,1303,1697,1312,f,1694,1312,1692,1312,j,1692,1316,1687,1316,f,1686,1316,1685,1316,1686,1314,1686,1313,1685,1312,1685,1311,1683,1308,1682,1309,1682,1305,1679,1304,1675,1303,1674,1303,1670,1298,1663,1298,1660,1287,1649,1287,1637,1287,1631,1281,1613,1260,1606,1259,1608,1251,1600,1250,1590,1251,1586,1251,j,1586,1270,1580,1270,1580,1277,1563,1277,1566,1351,f,1566,1361,1571,1370,1574,1377,1588,1377,1604,1377,1606,1376,1608,1375,1620,1361,1628,1351,1630,1349,j,1637,1343,1639,1336,1646,1336,f,1646,1342,1668,1360,1669,1364,1670,1376,1671,1377,1679,1389,1715,1383,1708,1416,1727,1433,1735,1439,1746,1447,1754,1465,j,1775,1465,f,1781,1476,1783,1494,1784,1500,1801,1500,1816,1500,1818,1498,1823,1489,1830,1490,1840,1491,1843,1482,1846,1474,1858,1477,1859,1477,1859,1477,j,1872,1477,f,1876,1477,1878,1481,1883,1491,1891,1491,j,1912,1491,f,1914,1491,1925,1500,1927,1501,1927,1520,1930,1528,1939,1528,1950,1525,1956,1533,1960,1539,1961,1539,j,1987,1538,1987,1527,1997,1527,f,1992,1541,2017,1541,2028,1536,2030,1524,2030,1510,2031,1503,2034,1483,2038,1480,2041,1478,2057,1478,2073,1478,2084,1493,j,2097,1493,f,2106,1466,2106,1465,j,2106,1444,f,2106,1437,2110,1436,2112,1435,2116,1434,2120,1428,2149,1429,2173,1430,2171,1414,2177,1412,2180,1420,2182,1424,2184,1432,2187,1436,2208,1436,2225,1436,2233,1429,2235,1427,2246,1427,2257,1427,2261,1423,2263,1418,2282,1412,2292,1408,2304,1401,2316,1400,2327,1391,2328,1390,2354,1387,2382,1383,2391,1363,2398,1363,2405,1375,2416,1356,2425,1352,2436,1347,2432,1319,j,2431,1290,f,2431,1282,2441,1275,j,2441,1272,f,2433,1259,2434,1247,2434,1235,2435,1213,j,2416,1194,2393,1194,f,2392,1195,2393,1200,j,2385,1200,f,2383,1209,2368,1214,2366,1214,2360,1221,2351,1228,2352,1231,j,2342,1231,f,2341,1223,2330,1223,j,2330,1199,f,2330,1192,2328,1188,2324,1183,2324,1182,j,2316,1182,2316,1190,2311,1190,2311,1198,f,2306,1198,2304,1198,j,2304,1200,2252,1200,2252,1183,2236,1183,2236,1177,f,2230,1177,2229,1176,j,2229,1165,f,2226,1159,2226,1152,j,2219,1152,f,2219,1148,2218,1146,2208,1146,2207,1144,2207,1141,2199,1141,2195,1141,2194,1140,2191,1136,2190,1136,j,2180,1136,f,2180,1132,2180,1130,j,2173,1130,c]],label:"Brabant Wallon",shortLabel:"BW",labelPosition:[200.2,133.6],labelAlignment:[t,v]},"011":{outlines:[[i,2205,781,j,2205,789,2198,789,2198,794,2192,794,2192,801,2187,801,2187,806,2181,806,f,2175,806,2173,805,2170,799,2169,799,j,2155,799,f,2155,802,2155,804,j,2155,807,f,2152,807,2150,806,j,2147,806,2147,813,f,2145,813,2142,813,j,2142,822,2135,822,2135,830,2131,830,2131,841,2125,841,2125,832,2128,832,2128,819,2122,819,2122,811,2116,811,f,2116,805,2108,805,j,2079,805,2079,811,2066,811,2067,817,2058,817,2058,822,2037,822,2037,831,2032,831,2032,851,f,2028,851,2010,852,j,2003,852,f,2004,844,1996,845,1998,838,1989,838,1989,834,1988,833,j,1980,833,1980,839,1972,839,f,1972,840,1973,841,j,1973,845,f,1964,845,1960,846,j,1960,851,1955,851,f,1955,850,1947,840,1942,834,1934,834,1935,831,1933,829,1931,826,1927,828,j,1927,822,1921,822,f,1921,823,1921,823,j,1921,830,1916,830,1916,837,1909,837,1909,844,1897,844,1897,836,1890,836,f,1888,833,1886,833,j,1880,833,1880,840,1866,840,1866,846,1844,846,f,1845,840,1827,840,1827,826,1827,825,1824,818,1816,822,j,1816,799,1820,799,1820,788,1815,788,1815,794,1810,794,1810,803,1803,803,1804,808,1775,808,f,1772,803,1765,804,1765,798,1760,795,1757,789,1753,786,1747,780,1745,781,1735,780,1734,776,j,1710,776,1710,786,1683,786,f,1681,787,1685,790,j,1685,811,1678,811,f,1679,812,1679,815,j,1668,815,1668,825,f,1674,830,1674,834,j,1681,835,1681,841,1674,841,1674,846,1665,846,1665,847,f,1665,847,1666,848,j,1666,851,1656,851,f,1657,853,1657,857,j,1649,857,1649,858,1651,862,1643,862,1643,870,1628,870,f,1629,862,1623,863,1615,864,1613,863,j,1613,855,1612,855,1607,855,1607,860,1604,860,f,1603,863,1604,869,1603,875,1598,874,j,1598,883,1591,884,1591,898,f,1592,898,1597,898,j,1597,908,1602,908,f,1600,917,1609,918,j,1609,926,1605,926,f,1605,928,1600,932,1596,934,1599,943,1594,945,1594,949,j,1594,959,1590,959,1590,968,1586,968,1586,962,f,1573,963,1575,955,1569,955,1566,955,1561,954,1562,950,j,1552,950,1551,945,1546,945,1546,954,f,1547,954,1547,955,j,1541,955,1542,976,1534,976,1534,984,1517,984,1517,987,1520,987,1520,992,1524,992,f,1524,992,1527,992,j,1528,1002,1534,1002,1534,1010,1541,1010,1541,1025,f,1535,1025,1536,1030,j,1536,1036,f,1522,1036,1518,1036,j,1518,1039,1512,1039,1511,1055,1505,1055,1505,1065,f,1505,1069,1501,1071,1501,1075,1501,1081,1500,1083,1492,1083,j,1492,1094,1519,1094,f,1520,1093,1522,1093,1524,1109,1525,1114,1524,1125,1524,1126,1517,1132,1518,1135,j,1518,1144,f,1508,1144,1511,1153,1510,1155,1507,1158,1504,1160,1505,1164,j,1499,1164,1500,1169,1475,1169,1476,1175,1471,1175,f,1472,1177,1472,1182,j,1466,1182,1466,1189,1463,1189,1461,1180,f,1454,1180,1455,1171,j,1453,1171,1453,1182,f,1447,1180,1446,1183,1446,1185,1446,1193,j,1418,1193,1418,1178,1425,1178,1425,1171,1413,1171,1413,1175,1405,1175,1405,1182,f,1399,1180,1399,1187,1399,1191,1397,1191,1394,1192,1394,1193,1394,1194,1396,1199,j,1396,1202,1390,1202,1390,1224,f,1393,1227,1400,1239,j,1409,1239,1409,1242,1405,1242,1405,1247,1396,1247,1396,1251,1382,1252,f,1376,1252,1370,1249,1364,1246,1356,1246,1355,1242,1355,1240,j,1347,1240,f,1347,1243,1347,1249,1347,1259,1347,1261,1345,1266,1343,1267,1342,1267,1342,1270,1342,1275,1369,1299,1371,1299,1372,1301,1373,1304,1375,1304,1387,1304,1388,1305,1396,1309,1399,1310,1403,1309,1406,1313,1407,1314,1409,1317,j,1442,1317,1443,1316,1443,1312,1465,1312,1465,1305,f,1470,1304,1480,1305,1487,1304,1487,1298,j,1499,1298,1499,1294,f,1506,1296,1509,1286,j,1517,1286,1517,1281,1536,1281,f,1535,1285,1538,1288,j,1543,1288,1543,1283,1563,1283,1563,1277,1580,1277,1580,1270,1586,1270,1586,1251,f,1590,1251,1600,1250,1608,1251,1606,1259,1613,1260,1631,1281,1637,1287,1649,1287,1660,1287,1663,1298,1670,1298,1674,1303,1675,1303,1679,1304,1682,1305,1682,1309,1683,1308,1685,1311,1685,1312,1686,1313,1686,1314,1685,1316,1686,1316,1687,1316,j,1692,1316,1692,1312,f,1694,1312,1697,1312,j,1697,1303,1705,1303,1705,1299,f,1727,1299,1737,1297,1741,1296,1743,1288,1748,1286,1748,1285,j,1748,1278,1753,1278,1753,1271,f,1760,1271,1758,1266,1762,1266,1765,1265,j,1769,1265,1769,1251,1775,1251,1775,1246,1780,1246,f,1781,1254,1784,1257,1784,1259,1784,1264,1785,1267,1790,1266,1789,1270,1793,1274,j,1812,1274,1812,1251,f,1818,1253,1824,1250,1831,1246,1834,1246,1861,1244,1862,1244,1868,1241,1879,1232,1892,1222,1893,1216,j,1907,1216,1907,1212,1929,1212,1929,1234,1934,1234,1934,1240,f,1935,1241,1939,1241,1943,1241,1941,1246,1949,1244,1951,1252,j,1955,1252,1955,1258,1960,1258,1960,1253,1964,1253,1964,1241,1969,1241,1969,1237,1983,1237,1983,1232,2004,1232,f,2002,1228,2006,1225,2010,1222,2010,1222,2013,1211,2017,1213,j,2017,1208,2021,1208,2021,1199,2024,1199,f,2025,1199,2027,1200,j,2027,1219,f,2027,1223,2034,1225,2034,1227,2034,1237,j,2059,1237,2059,1232,2073,1232,2073,1221,f,2075,1220,2080,1220,j,2080,1214,2087,1214,2087,1210,2082,1210,f,2081,1206,2081,1199,2079,1198,2076,1198,2073,1191,2074,1188,j,2069,1188,2069,1164,f,2070,1164,2073,1164,j,2073,1141,2076,1141,2076,1147,2082,1147,f,2083,1151,2083,1154,2088,1154,2092,1160,j,2149,1160,2149,1154,2156,1154,f,2156,1150,2157,1148,j,2162,1148,2162,1141,2168,1141,2168,1136,2173,1136,2173,1130,2180,1130,f,2180,1132,2180,1136,j,2190,1136,f,2191,1136,2194,1140,2195,1141,2199,1141,2207,1141,2207,1144,2208,1146,2218,1146,2219,1148,2219,1152,j,2226,1152,f,2226,1159,2229,1165,j,2229,1176,f,2230,1177,2236,1177,j,2236,1183,2252,1183,2252,1200,2304,1200,2304,1198,f,2306,1198,2311,1198,j,2311,1190,2316,1190,2316,1182,2324,1182,f,2324,1183,2328,1188,2330,1192,2330,1199,j,2330,1223,f,2341,1223,2342,1231,j,2352,1231,f,2351,1228,2360,1221,2366,1214,2368,1214,2383,1209,2385,1200,j,2393,1200,f,2392,1195,2393,1194,j,2416,1194,2447,1224,f,2451,1229,2455,1230,2461,1232,2461,1236,j,2461,1263,f,2463,1263,2468,1265,j,2468,1270,f,2474,1269,2475,1273,2477,1278,2481,1280,2482,1281,2489,1281,2495,1281,2498,1287,j,2517,1287,2517,1277,2524,1277,f,2524,1262,2525,1261,2525,1260,2525,1251,2527,1249,2532,1248,j,2532,1237,f,2530,1237,2526,1236,j,2526,1229,2519,1229,2519,1211,2526,1211,2526,1150,2552,1150,2552,1143,f,2550,1141,2550,1138,2554,1138,2557,1138,j,2557,1120,f,2552,1119,2545,1120,j,2545,1107,f,2551,1106,2551,1094,2549,1077,2549,1073,2549,1070,2553,1067,2556,1064,2556,1060,j,2556,1059,2555,1053,2562,1053,2562,1043,2567,1043,2567,1021,2572,1021,2572,1027,2577,1027,2577,1032,2584,1032,f,2583,1020,2591,1022,j,2591,1008,f,2599,1006,2599,1001,j,2599,986,f,2592,983,2590,983,j,2590,973,f,2583,972,2585,968,j,2550,968,2550,962,2545,962,2545,953,2535,953,2535,962,2523,962,2523,968,2511,968,f,2511,970,2511,974,j,2503,974,f,2502,967,2497,968,2496,960,2492,962,j,2492,955,2486,955,2484,961,2474,961,f,2474,955,2469,956,2467,946,2464,945,2461,944,2461,941,2461,936,2460,934,j,2456,934,2456,916,2463,916,2463,908,2471,908,2471,902,f,2473,902,2474,903,j,2480,903,2480,898,f,2487,898,2490,896,2492,894,2492,886,j,2492,863,f,2492,859,2499,860,j,2499,857,2506,857,f,2503,852,2510,851,2518,849,2516,844,j,2521,844,f,2518,839,2524,839,2527,838,2533,839,j,2533,817,f,2530,815,2528,814,2526,813,2526,813,j,2526,801,2530,801,2530,811,2553,811,2553,805,2560,805,2560,799,f,2548,784,2544,779,2534,772,2533,769,2529,767,2523,760,j,2492,760,f,2491,767,2490,787,2489,791,2488,800,2487,806,2479,803,j,2479,811,2467,811,f,2466,807,2460,799,j,2451,799,2451,805,2432,805,f,2432,801,2425,801,j,2425,791,f,2422,792,2421,788,2420,783,2417,783,j,2399,782,2399,781,f,2393,779,2388,778,j,2388,772,2383,772,2383,764,2378,764,2378,770,2372,770,2372,775,2364,776,2364,781,2330,781,2330,791,2322,791,f,2322,793,2323,795,j,2323,799,f,2318,799,2316,799,2311,799,2314,804,j,2291,804,2291,809,2282,809,2282,816,2268,817,2268,823,f,2261,823,2258,824,j,2229,824,2229,795,2225,795,f,2224,793,2220,789,2215,784,2216,781,c,i,1771,993,f,1775,985,1779,983,j,1788,983,1788,989,1801,989,1803,997,f,1805,997,1815,996,j,1820,996,1820,990,1827,990,1827,982,1832,982,1832,977,1835,977,1835,972,1839,972,1841,980,1845,979,1849,979,1852,988,1857,988,f,1858,990,1864,993,1871,996,1872,999,1872,1006,1873,1021,j,1873,1028,1864,1028,1864,1037,1858,1037,1858,1046,f,1867,1046,1868,1051,j,1879,1051,f,1879,1054,1880,1056,j,1886,1056,1887,1061,f,1891,1059,1894,1062,1898,1066,1900,1066,1898,1071,1902,1072,1906,1074,1907,1078,1907,1083,1908,1094,j,1908,1101,1912,1102,1912,1112,1895,1112,1895,1117,1890,1117,1890,1136,1898,1136,1898,1141,1908,1141,f,1907,1149,1915,1150,1924,1150,1920,1154,j,1917,1154,1917,1159,1906,1159,1906,1163,f,1900,1162,1897,1162,1891,1162,1891,1169,1885,1168,1882,1169,1879,1169,1880,1176,j,1870,1176,1869,1180,1857,1180,f,1857,1184,1857,1186,j,1847,1186,f,1847,1191,1846,1192,j,1835,1192,f,1834,1198,1834,1199,1824,1199,1823,1201,1820,1198,1821,1194,j,1815,1194,1815,1187,1815,1187,f,1798,1187,1790,1188,1774,1188,1773,1180,1766,1181,1766,1172,1766,1164,1761,1165,j,1761,1154,1752,1153,1752,1141,1748,1141,1748,1131,1727,1131,f,1726,1135,1723,1135,1720,1135,1719,1132,1718,1130,1714,1130,j,1703,1130,f,1706,1123,1700,1123,1691,1123,1691,1123,j,1691,1111,1696,1111,f,1696,1102,1699,1100,1702,1098,1703,1089,j,1727,1089,1727,1083,1740,1083,1740,1068,f,1737,1068,1731,1068,j,1731,1064,f,1731,1059,1732,1057,1732,1044,1731,1037,1726,1037,1725,1037,j,1725,1024,f,1728,1022,1731,1023,1731,1022,1731,1018,1733,1017,1736,1017,1737,1016,1736,1012,j,1743,1012,1743,1008,1750,1008,1750,1003,1761,1003,1761,996,f,1768,998,1771,993,c]],label:"Vlaams-Brabant",shortLabel:"VB",labelPosition:[207.5,100.3],labelAlignment:[t,v]},"010":{outlines:[[i,1864,993,f,1858,990,1857,988,j,1852,988,1849,979,1845,979,1841,980,1839,972,1835,972,1835,977,1832,977,1832,982,1827,982,1827,990,1820,990,1820,996,1815,996,f,1805,997,1803,997,j,1801,989,1788,989,1788,983,1779,983,f,1775,985,1771,993,1768,998,1761,996,j,1761,1003,1750,1003,1750,1008,1743,1008,1743,1012,1736,1012,f,1737,1016,1736,1017,1733,1017,1731,1018,1731,1022,1731,1023,1728,1022,1725,1024,j,1725,1037,f,1726,1037,1731,1037,1732,1044,1732,1057,1731,1059,1731,1064,j,1731,1068,f,1737,1068,1740,1068,j,1740,1083,1727,1083,1727,1089,1703,1089,f,1702,1098,1699,1100,1696,1102,1696,1111,j,1691,1111,1691,1123,f,1691,1123,1700,1123,1706,1123,1703,1130,j,1714,1130,f,1718,1130,1719,1132,1720,1135,1723,1135,1726,1135,1727,1131,j,1748,1131,1748,1141,1752,1141,1752,1153,1761,1154,1761,1165,f,1766,1164,1766,1172,1766,1181,1773,1180,1774,1188,1790,1188,1798,1187,1815,1187,j,1815,1187,1815,1194,1821,1194,f,1820,1198,1823,1201,1824,1199,1834,1199,1834,1198,1835,1192,j,1846,1192,f,1847,1191,1847,1186,j,1857,1186,f,1857,1184,1857,1180,j,1869,1180,1870,1176,1880,1176,f,1879,1169,1882,1169,1885,1168,1891,1169,1891,1162,1897,1162,1900,1162,1906,1163,j,1906,1159,1917,1159,1917,1154,1920,1154,f,1924,1150,1915,1150,1907,1149,1908,1141,j,1898,1141,1898,1136,1890,1136,1890,1117,1895,1117,1895,1112,1912,1112,1912,1102,1908,1101,1908,1094,f,1907,1083,1907,1078,1906,1074,1902,1072,1898,1071,1900,1066,1898,1066,1894,1062,1891,1059,1887,1061,j,1886,1056,1880,1056,f,1879,1054,1879,1051,j,1868,1051,f,1867,1046,1858,1046,j,1858,1037,1864,1037,1864,1028,1873,1028,1873,1021,f,1872,1006,1872,999,f,1871,996,1864,993,c]],label:"Brussels",shortLabel:"BR",labelPosition:[180.6,108.6],labelAlignment:[t,v]},"02":{outlines:[[i,473,1124,j,457,1124,f,457,1128,457,1129,j,447,1129,447,1136,434,1136,434,1147,440,1147,441,1153,445,1153,f,443,1159,449,1161,455,1163,452,1170,j,455,1170,458,1174,452,1174,f,446,1174,444,1172,j,440,1172,440,1178,422,1178,422,1182,413,1182,f,411,1184,410,1192,409,1198,401,1194,j,401,1201,f,394,1201,391,1201,j,391,1206,383,1206,f,383,1200,377,1200,j,376,1194,368,1194,368,1188,360,1188,f,361,1193,357,1193,j,349,1193,349,1198,338,1198,338,1207,f,340,1207,344,1210,j,344,1223,338,1223,338,1234,345,1234,f,346,1239,346,1243,349,1242,351,1245,353,1249,355,1251,356,1251,357,1255,358,1258,361,1259,j,362,1263,362,1264,f,372,1263,389,1258,393,1257,391,1239,j,424,1239,f,425,1238,426,1238,433,1231,443,1225,468,1185,495,1204,501,1200,507,1195,523,1182,519,1172,j,517,1172,517,1172,511,1171,511,1158,500,1158,f,500,1132,499,1119,494,1119,492,1118,j,473,1118,c],[i,1639,1336,j,1637,1343,1630,1349,f,1628,1351,1620,1361,1608,1375,1606,1376,1604,1377,1588,1377,1574,1377,1571,1370,1566,1361,1566,1351,j,1563,1283,1543,1283,1543,1288,1538,1288,f,1535,1285,1536,1281,j,1517,1281,1517,1286,1509,1286,f,1506,1296,1499,1294,j,1499,1298,1487,1298,f,1487,1304,1480,1305,1470,1304,1465,1305,j,1465,1312,1443,1312,1443,1316,1442,1317,1409,1317,f,1407,1314,1406,1313,1403,1309,1399,1310,1396,1309,1388,1305,1387,1304,1375,1304,1373,1304,1372,1301,1371,1299,1369,1299,1342,1275,1342,1270,1342,1267,1343,1267,1345,1266,1347,1261,1347,1259,1347,1249,1347,1243,1347,1240,1347,1238,1347,1238,1340,1234,1342,1230,1339,1229,1337,1229,j,1337,1223,1314,1223,1314,1228,1282,1228,f,1282,1225,1279,1225,1274,1224,1273,1223,1269,1216,1263,1216,j,1232,1216,1232,1208,f,1225,1210,1224,1205,1223,1197,1223,1197,1221,1195,1221,1190,1221,1184,1220,1182,j,1202,1182,f,1202,1185,1199,1188,j,1174,1188,1174,1169,1169,1169,1169,1177,1153,1177,1153,1182,1143,1182,f,1143,1187,1142,1189,j,1137,1189,f,1139,1192,1132,1202,1125,1212,1124,1214,1122,1217,1118,1221,1113,1225,1111,1230,1108,1235,1106,1236,1104,1236,1103,1239,j,1103,1275,1100,1275,1100,1270,1096,1270,f,1095,1264,1092,1262,1087,1259,1086,1256,1084,1253,1078,1252,1073,1251,1075,1246,1072,1246,1066,1242,1060,1238,1049,1240,j,1012,1240,1012,1208,1006,1208,f,1007,1204,1003,1199,j,989,1199,989,1205,f,978,1205,969,1206,j,953,1206,953,1199,943,1199,942,1195,921,1195,f,918,1204,906,1213,901,1218,877,1216,j,877,1240,870,1240,870,1247,843,1247,843,1261,837,1261,837,1277,824,1277,824,1270,815,1270,f,816,1261,811,1261,805,1262,802,1261,802,1260,801,1256,j,796,1256,796,1237,f,795,1234,792,1230,790,1228,792,1224,788,1225,787,1221,786,1216,785,1215,781,1212,769,1212,j,732,1212,f,732,1207,726,1203,718,1200,716,1198,708,1190,707,1188,705,1187,698,1187,693,1188,690,1189,j,690,1224,704,1224,705,1239,718,1239,718,1248,f,732,1250,758,1254,j,758,1291,746,1291,746,1367,758,1369,758,1390,758,1394,767,1394,769,1398,769,1510,783,1511,783,1526,793,1526,793,1537,809,1538,809,1552,f,818,1552,821,1553,j,821,1564,847,1564,f,841,1576,869,1576,j,869,1588,899,1587,899,1578,923,1578,923,1565,f,947,1565,950,1564,956,1561,955,1553,953,1538,953,1537,j,990,1537,990,1564,977,1564,977,1575,991,1575,991,1587,f,1103,1589,1107,1590,j,1107,1602,f,1122,1603,1119,1613,j,1133,1613,1133,1638,f,1137,1638,1145,1642,j,1145,1725,f,1145,1749,1133,1744,j,1133,1781,1144,1781,1144,1821,1156,1821,f,1156,1826,1159,1845,j,1172,1846,1172,1858,1182,1858,1182,1872,1195,1872,1194,1858,1208,1858,1208,1850,1220,1851,1223,1808,1314,1808,1314,1796,1326,1796,1326,1806,1325,1808,1337,1808,f,1332,1819,1344,1820,1357,1820,1352,1832,j,1376,1832,1377,1844,f,1379,1844,1379,1845,j,1391,1845,1391,1834,f,1423,1837,1414,1819,j,1478,1819,1478,1808,1505,1808,1505,1818,f,1518,1817,1518,1827,1518,1834,1523,1834,1525,1834,1530,1834,1529,1839,1533,1844,1538,1850,1544,1848,j,1544,1858,1559,1858,1559,1873,1570,1873,1570,1886,1584,1886,1584,1926,1597,1926,1597,1936,1602,1936,1610,1935,1611,1948,1635,1948,1635,1926,1661,1926,f,1661,1926,1663,1926,j,1663,1938,1675,1938,1675,1950,1650,1950,1649,1962,1637,1962,1637,1986,1622,1986,1622,2002,f,1611,2001,1608,2002,j,1610,2078,1598,2078,1598,2104,1585,2104,1585,2129,f,1589,2129,1595,2131,j,1595,2144,1650,2144,1650,2167,1661,2168,1661,2184,1676,2184,1676,2233,f,1658,2233,1651,2234,j,1651,2248,1609,2248,1609,2262,1597,2262,1597,2287,1583,2287,1583,2311,1597,2311,1597,2364,1609,2364,1609,2377,f,1640,2373,1637,2390,j,1659,2390,1659,2403,1749,2403,1748,2389,1774,2388,f,1774,2391,1777,2401,j,1803,2401,1803,2415,1882,2415,1882,2409,1887,2409,f,1888,2388,1885,2383,1873,2374,1873,2366,j,1873,2331,f,1861,2319,1860,2313,1860,2310,1860,2281,1860,2264,1852,2259,1845,2253,1848,2233,1848,2229,1837,2214,j,1837,2140,f,1838,2125,1823,2114,j,1823,2062,1837,2062,f,1837,2049,1836,2042,1836,2030,1841,2027,1848,2021,1849,2000,1848,1980,1843,1975,1839,1970,1821,1971,1802,1970,1799,1982,j,1795,1982,f,1782,1965,1773,1954,1746,1956,1746,1936,1746,1923,1758,1921,1773,1919,1779,1911,1783,1906,1792,1906,1797,1906,1803,1900,1807,1893,1809,1893,j,1822,1893,1822,1892,1826,1892,f,1825,1887,1845,1876,1856,1867,1870,1865,1879,1862,1896,1855,1900,1855,1909,1847,j,1918,1839,1958,1839,f,1959,1851,1962,1852,1964,1853,1987,1853,2010,1853,2014,1845,2014,1844,2035,1836,2043,1833,2042,1815,2040,1793,2041,1783,j,2042,1726,f,2045,1717,2058,1708,2069,1700,2069,1699,2051,1678,2048,1675,2042,1667,2035,1664,2032,1664,2033,1651,2033,1645,2041,1632,2047,1621,2044,1605,2038,1603,2019,1585,j,2018,1541,2017,1541,f,1992,1541,1997,1527,j,1987,1527,1987,1538,1961,1539,f,1960,1539,1956,1533,1950,1525,1939,1528,1930,1528,1927,1520,1927,1501,1925,1500,1914,1491,1912,1491,j,1891,1491,f,1883,1491,1878,1481,1876,1477,1872,1477,j,1859,1477,f,1859,1477,1858,1477,1846,1474,1843,1482,1840,1491,1830,1490,1823,1489,1818,1498,1816,1500,1801,1500,1784,1500,1783,1494,1781,1476,1775,1465,j,1754,1465,f,1746,1447,1735,1439,1727,1433,1708,1416,1715,1383,1679,1389,1671,1377,1670,1376,1669,1364,1668,1360,1646,1342,1646,1336,c]],label:"Hainaut",shortLabel:"HA",labelPosition:[137.9,158.8],labelAlignment:[t,v]},"01":{outlines:[[i,2361,149,j,2350,149,2350,152,2339,152,2339,159,2334,159,2335,163,2327,163,2327,177,f,2330,176,2332,179,2333,182,2333,184,2334,184,2342,184,2348,184,2345,191,j,2354,191,2354,182,f,2359,181,2361,181,j,2361,158,2367,158,2367,142,2361,142,c],[i,2421,115,f,2422,123,2415,121,j,2415,126,2409,126,2409,131,f,2416,132,2416,144,2416,154,2412,155,2409,161,2403,162,2406,167,2397,172,2392,180,2389,182,2384,182,2379,190,2373,197,2373,201,2372,202,2363,209,2358,212,2357,217,2356,221,2348,225,2341,228,2342,236,j,2337,236,2337,242,2333,242,2333,237,2329,237,2329,232,f,2317,225,2307,206,j,2293,206,f,2295,211,2288,211,2280,211,2278,211,j,2278,217,2273,217,f,2272,213,2264,213,j,2264,207,2250,207,f,2228,211,2209,211,2202,211,2201,209,2198,206,2191,206,j,2191,184,2209,184,f,2211,188,2225,188,j,2225,195,2236,195,2236,199,f,2241,199,2243,200,j,2248,200,f,2248,167,2249,152,2257,150,2256,134,2254,118,2261,116,j,2261,106,2242,106,f,2243,102,2239,99,2235,95,2236,91,2228,91,2216,80,2203,68,2199,68,2186,75,2178,74,j,2178,79,2168,79,2168,86,2159,86,f,2157,89,2131,124,j,2126,126,f,2123,128,2123,133,2123,135,2122,139,2120,142,2121,146,2122,153,2115,154,2106,153,2102,154,j,2102,161,2086,161,2086,168,2091,168,2091,191,f,2090,191,2091,194,j,2053,194,f,2052,189,2045,188,2036,186,2034,184,2031,183,2022,182,2014,182,2011,177,j,1995,177,1995,184,1984,184,f,1986,190,1980,191,1972,191,1970,191,j,1970,195,1963,195,f,1964,174,1963,165,j,1962,165,1963,145,f,1963,145,1975,139,1982,135,1981,127,j,1988,127,1988,124,f,1977,112,1972,110,1943,109,1941,109,1905,109,1882,122,1851,141,1823,154,j,1823,159,1816,159,1816,162,f,1818,162,1825,166,1831,169,1835,168,j,1835,174,f,1831,175,1832,184,j,1824,184,1824,195,1818,195,1818,205,f,1830,212,1841,233,1842,236,1855,250,1866,261,1866,267,1870,267,1872,268,j,1872,271,f,1859,269,1843,294,j,1832,294,1832,300,1795,300,f,1796,291,1786,284,1776,276,1779,269,j,1771,269,f,1760,266,1759,266,1739,269,1712,270,j,1662,270,1662,277,f,1664,278,1666,278,1669,287,1675,290,1681,300,1686,302,1690,305,1697,310,1703,307,1706,313,1709,320,1714,317,j,1714,368,f,1721,370,1721,386,j,1724,386,f,1723,391,1727,391,1729,392,1736,391,1740,391,1742,396,1744,399,1747,400,j,1754,398,f,1762,398,1762,409,j,1762,418,f,1763,422,1761,423,1758,424,1757,424,1759,428,1756,431,1753,433,1749,432,j,1750,439,1741,439,f,1741,441,1743,448,j,1743,449,f,1739,450,1737,450,j,1737,459,f,1739,458,1743,461,j,1743,516,f,1747,516,1747,527,1747,537,1755,539,1755,551,1756,552,1758,554,1762,555,1764,556,1764,561,1772,561,1772,570,1772,575,1770,582,j,1770,601,f,1770,608,1767,615,1766,616,1766,616,j,1766,642,1761,642,f,1760,643,1762,648,j,1754,648,f,1752,650,1754,653,j,1715,653,1715,659,1708,659,f,1710,662,1707,664,1704,666,1700,665,j,1700,670,1695,670,f,1694,669,1694,666,j,1684,666,1683,660,1673,660,f,1670,654,1671,653,j,1656,653,1656,658,1648,658,1648,665,1642,665,1642,671,1635,671,1635,675,1631,675,1631,680,1626,680,1626,687,f,1624,688,1620,688,j,1620,711,1621,712,1633,713,f,1634,715,1632,737,1632,755,1644,748,j,1644,762,1638,762,f,1639,764,1639,771,j,1632,771,1632,776,1639,776,1638,783,1643,783,1643,787,1646,787,1647,792,1654,792,1654,787,1662,787,1662,782,1671,782,1671,776,1679,776,1680,784,1683,786,1710,786,1710,776,1734,776,f,1735,780,1745,781,1747,780,1753,786,1757,789,1760,795,1765,798,1765,804,1772,803,1775,808,j,1804,808,1803,803,1810,803,1810,794,1815,794,1815,788,1820,788,1820,799,1816,799,1816,822,f,1824,818,1827,825,1827,826,1827,840,1845,840,1844,846,j,1866,846,1866,840,1880,840,1880,833,1886,833,f,1888,833,1890,836,j,1897,836,1897,844,1909,844,1909,837,1916,837,1916,830,1921,830,1921,823,f,1921,823,1921,822,j,1927,822,1927,828,f,1931,826,1933,829,1935,831,1934,834,1942,834,1947,840,1955,850,1955,851,j,1960,851,1960,846,f,1964,845,1973,845,j,1973,841,f,1972,840,1972,839,j,1980,839,1980,833,1988,833,f,1989,834,1989,838,1998,838,1996,845,2004,844,2003,852,j,2010,852,f,2028,851,2032,851,j,2032,831,2037,831,2037,822,2058,822,2058,817,2067,817,2066,811,2079,811,2079,805,2108,805,f,2116,805,2116,811,j,2122,811,2122,819,2128,819,2128,832,2125,832,2125,841,2131,841,2131,830,2135,830,2135,822,2142,822,2142,813,f,2145,813,2147,813,j,2147,806,2150,806,f,2152,807,2155,807,j,2155,804,f,2155,802,2155,799,j,2169,799,f,2170,799,2173,805,2175,806,2181,806,j,2187,806,2187,801,2192,801,2192,794,2198,794,2198,789,2205,789,2205,781,2216,781,f,2215,784,2220,789,2224,793,2225,795,j,2229,795,2229,824,2258,824,f,2261,823,2268,823,j,2268,817,2282,816,2282,809,2291,809,2291,804,2314,804,f,2311,799,2316,799,2318,799,2323,799,j,2323,795,f,2322,793,2322,791,j,2330,791,2330,781,2364,781,2364,776,2372,775,2372,770,2378,770,2378,764,2383,764,2383,772,2388,772,2388,778,f,2393,779,2399,781,j,2399,775,f,2405,772,2404,768,2406,767,2410,758,2418,757,2416,749,j,2422,749,2422,735,2428,735,2428,728,2436,728,f,2434,722,2443,723,2452,723,2454,720,2456,717,2480,718,2480,711,2483,711,2485,710,2494,711,2495,710,2495,710,2496,708,2496,706,j,2504,706,f,2506,693,2535,669,2543,661,2547,660,2552,658,2564,660,2571,661,2577,655,2582,650,2595,653,2595,651,2601,647,2602,645,2602,638,2607,634,2608,633,2608,630,2608,624,j,2612,624,2612,618,2616,618,f,2619,623,2625,623,2630,623,2630,630,j,2633,630,2633,635,2640,635,2640,631,2643,631,f,2643,623,2653,620,2662,616,2663,611,2662,601,2661,592,j,2661,554,f,2639,531,2626,521,2619,515,2619,492,j,2618,461,f,2618,455,2628,448,2637,441,2638,439,2637,438,2636,437,j,2635,437,f,2634,430,2629,427,j,2629,403,2637,403,2637,396,f,2635,387,2635,379,2635,374,2631,371,2633,366,2623,365,2622,359,2613,359,2611,354,2611,351,j,2603,351,f,2603,350,2601,347,j,2590,347,f,2590,349,2589,354,j,2582,354,2582,359,2573,359,2573,364,2559,364,f,2554,357,2548,358,2546,358,2543,355,2541,351,2538,351,j,2538,324,f,2538,322,2533,317,2533,316,2533,308,2522,294,2521,293,2513,281,2513,279,2500,265,2496,259,2489,251,2488,248,2482,245,2483,237,2482,236,2487,232,2488,231,2489,224,2491,221,2491,215,2491,214,2496,210,2496,205,2497,201,2502,202,2505,196,2506,191,2506,189,2511,188,2511,182,2510,178,2507,176,2504,175,2504,168,2503,161,2501,158,2497,153,2496,152,2492,140,2491,136,j,2490,128,f,2486,124,2486,122,2475,120,2467,121,2458,121,2452,117,2451,116,2450,112,2450,108,2447,106,2446,96,2445,93,j,2441,93,2441,99,2435,99,2435,105,f,2423,105,2426,114,f,2425,115,2421,115,c]],label:"Antwerpen",shortLabel:"AN",labelPosition:[214.1,46],labelAlignment:[t,v]},"07":{outlines:[[i,1686,302,f,1681,300,1675,290,j,1676,297,f,1678,301,1679,307,1679,312,1657,342,1635,370,1633,372,1625,388,1619,394,1607,404,1570,430,1536,454,1521,469,1472,469,1456,478,1453,481,1451,483,1449,485,1445,484,1439,483,1438,487,1437,492,1435,493,1429,498,1423,501,1417,501,1415,502,1411,502,1413,508,1408,507,1405,510,1401,514,1399,515,j,1399,508,1393,508,1391,502,f,1391,501,1386,501,1381,501,1377,513,1373,525,1372,527,j,1356,527,1356,533,1344,533,1344,530,1349,530,1349,512,1355,512,1355,495,1345,495,1345,502,1335,502,1335,510,1330,510,f,1330,512,1328,515,j,1256,515,f,1255,508,1255,502,1255,498,1259,496,1263,494,1263,487,j,1263,470,f,1263,451,1262,444,j,1247,444,f,1247,443,1246,438,1229,437,1228,437,1224,432,1221,433,j,1212,433,f,1209,432,1206,430,1203,427,1198,427,1191,427,1189,424,1188,424,1182,421,1144,400,1135,393,j,1123,393,f,1121,397,1122,398,j,1110,398,f,1110,395,1107,394,1103,394,1101,393,j,1093,388,f,1089,381,1088,381,j,1081,381,f,1080,381,1074,375,j,1064,375,1064,392,1061,392,1060,400,1056,400,1056,394,1049,394,1049,388,1043,389,f,1043,395,1019,395,1010,394,1001,395,998,395,995,395,j,995,401,1001,401,1001,444,1005,444,1005,459,993,459,f,993,463,991,463,j,943,463,943,466,913,466,913,462,f,906,461,906,451,905,445,895,436,887,426,884,423,878,418,870,420,j,870,416,866,416,866,428,f,867,429,871,432,872,439,873,440,877,442,877,448,877,457,877,458,j,884,458,884,473,875,473,875,475,f,875,476,875,478,j,864,478,864,485,853,485,853,500,f,857,501,859,501,j,859,517,866,517,866,527,860,527,860,532,852,532,851,538,843,538,843,542,856,542,f,859,539,860,543,861,545,862,549,869,546,870,555,872,565,874,567,877,568,876,579,876,588,885,585,j,885,606,f,885,606,881,608,879,609,879,613,880,619,872,620,874,628,869,631,865,634,866,642,j,860,642,860,648,854,648,854,654,845,654,845,659,839,659,839,665,830,665,830,669,826,669,f,826,673,824,674,821,676,821,680,821,688,829,695,834,699,843,704,852,711,871,728,873,730,876,734,879,736,885,735,888,742,890,743,893,744,896,747,902,749,902,750,905,754,910,753,912,757,917,757,920,757,921,761,922,763,922,765,j,917,765,f,917,770,918,772,j,909,772,909,776,900,776,f,901,777,901,781,905,781,907,781,906,782,906,787,906,792,911,792,j,911,800,f,917,798,917,803,j,917,813,f,919,814,924,814,j,924,823,930,823,931,828,931,831,f,924,830,926,838,j,920,838,920,845,914,845,f,916,850,911,853,906,856,908,861,j,900,861,900,867,907,867,907,874,912,874,912,877,f,914,878,919,878,j,919,881,915,881,916,885,905,885,905,890,896,890,896,895,f,896,895,896,896,j,888,896,888,902,f,889,904,892,904,891,909,903,909,909,909,924,909,j,924,915,930,915,930,925,918,925,918,928,929,928,f,929,930,930,930,j,930,945,918,945,f,913,937,911,937,910,935,909,930,j,905,930,905,949,f,905,951,905,956,905,961,901,960,j,901,965,f,896,963,895,968,894,972,890,970,j,890,976,f,894,980,898,983,899,984,903,986,906,986,906,992,j,917,992,917,985,923,985,923,978,934,978,f,943,989,945,992,948,997,953,998,955,998,956,1005,955,1010,955,1010,954,1010,948,1012,j,948,1020,943,1020,943,1027,925,1027,922,1026,922,1031,f,922,1030,925,1036,j,931,1036,f,931,1036,931,1042,931,1046,937,1046,934,1055,950,1055,960,1054,960,1059,961,1064,965,1063,963,1069,971,1072,972,1074,972,1079,972,1080,978,1081,977,1085,984,1088,j,984,1095,976,1095,976,1098,970,1098,970,1104,f,971,1104,977,1105,974,1113,983,1113,j,983,1119,f,985,1120,990,1121,j,990,1126,f,990,1132,995,1131,j,995,1140,f,985,1141,986,1146,j,967,1146,f,967,1155,961,1153,960,1168,954,1166,955,1173,947,1173,946,1174,943,1175,942,1176,941,1180,939,1182,932,1186,926,1191,927,1195,j,942,1195,943,1199,953,1199,953,1206,969,1206,f,978,1205,989,1205,j,989,1199,1003,1199,f,1007,1204,1006,1208,j,1012,1208,1012,1240,1049,1240,f,1060,1238,1066,1242,1072,1246,1075,1246,1073,1251,1078,1252,1084,1253,1086,1256,1087,1259,1092,1262,1095,1264,1096,1270,j,1100,1270,1100,1275,1103,1275,1103,1239,f,1104,1236,1106,1236,1108,1235,1111,1230,1113,1225,1118,1221,1122,1217,1124,1214,1125,1212,1132,1202,1139,1192,1137,1189,j,1142,1189,f,1143,1187,1143,1182,j,1153,1182,1153,1177,1169,1177,1169,1169,1174,1169,1174,1188,1199,1188,f,1202,1185,1202,1182,j,1220,1182,f,1221,1184,1221,1190,1221,1195,1223,1197,1223,1197,1224,1205,1225,1210,1232,1208,j,1232,1216,1263,1216,f,1269,1216,1273,1223,1274,1224,1279,1225,1282,1225,1282,1228,j,1314,1228,1314,1223,1337,1223,1337,1229,f,1339,1229,1342,1230,1340,1234,1347,1238,1347,1238,1347,1240,j,1355,1240,f,1355,1242,1356,1246,1364,1246,1370,1249,1376,1252,1382,1252,j,1396,1251,1396,1247,1405,1247,1405,1242,1409,1242,1409,1239,1400,1239,f,1393,1227,1390,1224,j,1390,1202,1396,1202,1396,1199,f,1394,1194,1394,1193,1394,1192,1397,1191,1399,1191,1399,1187,1399,1180,1405,1182,j,1405,1175,1413,1175,1413,1171,1425,1171,1425,1178,1418,1178,1418,1193,1446,1193,f,1446,1185,1446,1183,1447,1180,1453,1182,j,1453,1171,1455,1171,f,1454,1180,1461,1180,j,1463,1189,1466,1189,1466,1182,1472,1182,f,1472,1177,1471,1175,j,1476,1175,1475,1169,1500,1169,1499,1164,1505,1164,f,1504,1160,1507,1158,1510,1155,1511,1153,1508,1144,1518,1144,j,1518,1135,f,1517,1132,1524,1126,1524,1125,1525,1114,1524,1109,1522,1093,1520,1093,1519,1094,j,1492,1094,1492,1083,f,1500,1083,1501,1081,1501,1075,1501,1071,1505,1069,1505,1065,j,1505,1055,1511,1055,1512,1039,1518,1039,1518,1036,f,1522,1036,1536,1036,j,1536,1030,f,1535,1025,1541,1025,j,1541,1010,1534,1010,1534,1002,1528,1002,1527,992,f,1524,992,1524,992,j,1520,992,1520,987,1517,987,1517,984,1534,984,1534,976,1542,976,1541,955,1547,955,f,1547,954,1546,954,j,1546,945,1551,945,1552,950,1562,950,f,1561,954,1566,955,1569,955,1575,955,1573,963,1586,962,j,1586,968,1590,968,1590,959,1594,959,1594,949,f,1594,945,1599,943,1596,934,1600,932,1605,928,1605,926,j,1609,926,1609,918,f,1600,917,1602,908,j,1597,908,1597,898,f,1592,898,1591,898,j,1591,884,1598,883,1598,874,f,1603,875,1604,869,1603,863,1604,860,j,1607,860,1607,855,1612,855,1613,855,1613,863,f,1615,864,1623,863,1629,862,1628,870,j,1643,870,1643,862,1651,862,1649,858,1649,857,1657,857,f,1657,853,1656,851,j,1666,851,1666,848,f,1665,847,1665,847,j,1665,846,1674,846,1674,841,1681,841,1681,835,1674,834,f,1674,830,1668,825,j,1668,815,1679,815,f,1679,812,1678,811,j,1685,811,1685,790,f,1681,787,1683,786,j,1680,784,1679,776,1671,776,1671,782,1662,782,1662,787,1654,787,1654,792,1647,792,1646,787,1643,787,1643,783,1638,783,1639,776,1632,776,1632,771,1639,771,f,1639,764,1638,762,j,1644,762,1644,748,f,1632,755,1632,737,1634,715,1633,713,j,1621,712,1620,711,1620,688,f,1624,688,1626,687,j,1626,680,1631,680,1631,675,1635,675,1635,671,1642,671,1642,665,1648,665,1648,658,1656,658,1656,653,1671,653,f,1670,654,1673,660,j,1683,660,1684,666,1694,666,f,1694,669,1695,670,j,1700,670,1700,665,f,1704,666,1707,664,1710,662,1708,659,j,1715,659,1715,653,1754,653,f,1752,650,1754,648,j,1762,648,f,1760,643,1761,642,j,1766,642,1766,616,f,1766,616,1767,615,1770,608,1770,601,j,1770,582,f,1772,575,1772,570,1772,561,1764,561,1764,556,1762,555,1758,554,1756,552,1755,551,1755,539,1747,537,1747,527,1747,516,1743,516,j,1743,461,f,1739,458,1737,459,j,1737,450,f,1739,450,1743,449,j,1743,448,f,1741,441,1741,439,j,1750,439,1749,432,f,1753,433,1756,431,1759,428,1757,424,1758,424,1761,423,1763,422,1762,418,j,1762,409,f,1762,398,1754,398,j,1747,400,f,1744,399,1742,396,1740,391,1736,391,1729,392,1727,391,1723,391,1724,386,j,1721,386,f,1721,370,1714,368,j,1714,317,f,1709,320,1706,313,1703,307,1697,310,f,1690,305,1686,302,c]],label:"Oost-Vlaanderen",shortLabel:"OV",labelPosition:[126.2,83.3],labelAlignment:[t,v]},"08":{outlines:[[i,839,270,j,839,276,821,277,821,282,806,282,806,289,f,798,288,794,289,796,293,791,294,790,294,789,294,787,294,782,293,777,293,776,296,772,300,764,300,762,306,751,305,741,305,743,312,j,732,312,f,729,318,728,319,728,319,721,319,710,319,710,312,701,313,700,311,698,306,691,306,690,304,690,299,j,686,299,686,305,681,305,681,317,675,317,f,675,320,675,328,674,329,669,330,666,331,667,334,654,336,653,337,649,343,640,341,628,346,611,351,601,355,597,357,590,364,585,364,578,363,573,369,567,376,565,379,558,395,546,396,538,402,535,404,525,409,520,411,518,412,499,427,496,428,491,429,489,432,489,435,479,437,475,439,j,474,439,f,470,442,469,441,470,446,465,447,459,446,458,446,459,451,456,452,452,452,450,452,j,450,456,430,456,f,424,456,416,468,404,483,393,491,381,499,359,511,336,522,323,531,314,537,291,551,280,559,258,570,228,592,227,593,226,594,212,603,j,195,613,f,187,617,179,617,179,622,174,622,173,622,168,627,167,628,158,629,152,630,153,637,142,636,139,642,132,642,129,642,123,642,125,647,118,647,114,650,110,652,103,652,103,655,102,658,93,658,90,659,83,659,85,665,79,664,77,665,74,665,73,670,j,64,670,64,675,54,675,54,683,f,60,688,62,695,66,701,68,709,68,710,69,716,69,722,72,723,77,727,76,742,j,76,764,f,76,769,83,779,j,83,800,f,83,809,89,813,j,89,823,f,99,823,112,827,112,828,112,839,112,849,115,851,118,853,118,862,118,868,123,868,j,123,879,f,123,882,129,886,130,889,130,897,132,903,138,902,j,138,908,f,128,907,126,913,125,914,116,924,113,926,106,932,101,939,93,938,j,93,943,88,943,88,947,96,947,96,950,f,101,950,114,952,j,114,1005,f,113,1006,114,1009,j,114,1009,f,114,1013,115,1023,115,1031,107,1032,109,1039,101,1041,100,1045,97,1046,94,1045,93,1046,j,93,1048,117,1048,117,1055,f,117,1060,121,1063,124,1064,123,1078,124,1079,127,1081,129,1083,129,1088,129,1090,128,1097,128,1103,135,1101,j,135,1105,f,138,1106,143,1108,j,162,1108,162,1087,167,1087,167,1094,171,1094,171,1102,178,1102,178,1106,204,1106,204,1100,213,1100,213,1106,217,1106,217,1120,f,217,1125,223,1129,225,1132,226,1139,228,1141,234,1147,j,234,1147,f,235,1149,241,1155,245,1159,245,1164,j,251,1164,251,1188,258,1188,f,261,1195,274,1204,274,1204,274,1209,274,1214,277,1214,283,1215,280,1228,284,1229,288,1230,j,288,1244,f,292,1245,293,1245,j,293,1251,f,293,1254,296,1256,j,308,1256,308,1251,339,1251,f,336,1258,341,1262,348,1265,348,1270,j,355,1270,355,1265,362,1265,362,1263,361,1259,f,358,1258,357,1255,356,1251,355,1251,353,1249,351,1245,349,1242,346,1243,346,1239,345,1234,j,338,1234,338,1223,344,1223,344,1210,f,340,1207,338,1207,j,338,1198,349,1198,349,1193,357,1193,f,361,1193,360,1188,j,368,1188,368,1194,376,1194,377,1200,f,383,1200,383,1206,j,391,1206,391,1201,f,394,1201,401,1201,j,401,1194,f,409,1198,410,1192,411,1184,413,1182,j,422,1182,422,1178,440,1178,440,1172,444,1172,f,446,1174,452,1174,j,458,1174,455,1170,452,1170,f,455,1163,449,1161,443,1159,445,1153,j,441,1153,440,1147,434,1147,434,1136,447,1136,447,1129,457,1129,f,457,1128,457,1124,j,473,1124,473,1118,492,1118,f,494,1119,499,1119,500,1132,500,1158,j,511,1158,511,1171,519,1172,529,1171,f,527,1165,533,1164,535,1164,541,1166,j,542,1160,550,1160,f,551,1162,551,1166,562,1163,559,1171,j,562,1171,563,1177,577,1177,577,1168,581,1168,581,1156,f,587,1159,588,1147,j,590,1147,590,1140,596,1140,596,1147,602,1148,602,1153,634,1153,634,1174,f,636,1178,641,1178,640,1182,645,1185,648,1187,647,1194,650,1197,654,1200,656,1203,656,1205,656,1206,661,1206,668,1205,670,1201,674,1199,677,1193,680,1192,690,1189,693,1188,698,1187,705,1187,707,1188,708,1190,716,1198,718,1200,726,1203,732,1207,732,1212,j,769,1212,f,781,1212,785,1215,786,1216,787,1221,788,1225,792,1224,790,1228,792,1230,795,1234,796,1237,j,796,1256,801,1256,f,802,1260,802,1261,805,1262,811,1261,816,1261,815,1270,j,824,1270,824,1277,837,1277,837,1261,843,1261,843,1247,870,1247,870,1240,877,1240,877,1216,f,901,1218,906,1213,918,1204,921,1195,j,927,1195,f,926,1191,932,1186,939,1182,941,1180,942,1176,943,1175,946,1174,947,1173,955,1173,954,1166,960,1168,961,1153,967,1155,967,1146,j,986,1146,f,985,1141,995,1140,j,995,1131,f,990,1132,990,1126,j,990,1121,f,985,1120,983,1119,j,983,1113,f,974,1113,977,1105,971,1104,970,1104,j,970,1098,976,1098,976,1095,984,1095,984,1088,f,977,1085,978,1081,972,1080,972,1079,972,1074,971,1072,963,1069,965,1063,961,1064,960,1059,960,1054,950,1055,934,1055,937,1046,931,1046,931,1042,931,1036,931,1036,j,925,1036,f,922,1030,922,1031,j,922,1026,925,1027,943,1027,943,1020,948,1020,948,1012,f,954,1010,955,1010,955,1010,956,1005,955,998,953,998,948,997,945,992,943,989,934,978,j,923,978,923,985,917,985,917,992,906,992,f,906,986,903,986,899,984,898,983,894,980,890,976,j,890,970,f,894,972,895,968,896,963,901,965,j,901,960,f,905,961,905,956,905,951,905,949,j,905,930,909,930,f,910,935,911,937,913,937,918,945,j,930,945,930,930,f,929,930,929,928,j,918,928,918,925,930,925,930,915,924,915,924,909,f,909,909,903,909,891,909,892,904,889,904,888,902,j,888,896,896,896,f,896,895,896,895,j,896,890,905,890,905,885,916,885,915,881,919,881,919,878,f,914,878,912,877,j,912,874,907,874,907,867,900,867,900,861,908,861,f,906,856,911,853,916,850,914,845,j,920,845,920,838,926,838,f,924,830,931,831,j,931,828,930,823,924,823,924,814,f,919,814,917,813,j,917,803,f,917,798,911,800,j,911,792,f,906,792,906,787,906,782,907,781,905,781,901,781,901,777,900,776,j,909,776,909,772,918,772,f,917,770,917,765,j,922,765,f,922,763,921,761,920,757,917,757,912,757,910,753,905,754,902,750,902,749,896,747,893,744,890,743,888,742,885,735,879,736,876,734,873,730,871,728,852,711,843,704,834,699,829,695,821,688,821,680,821,676,824,674,826,673,826,669,j,830,669,830,665,839,665,839,659,845,659,845,654,854,654,854,648,860,648,860,642,866,642,f,865,634,869,631,874,628,872,620,880,619,879,613,879,609,881,608,885,606,885,606,j,885,585,f,876,588,876,579,877,568,874,567,872,565,870,555,869,546,862,549,861,545,860,543,859,539,856,542,j,843,542,843,538,851,538,852,532,860,532,860,527,866,527,866,517,859,517,859,501,f,857,501,853,500,j,853,485,864,485,864,478,875,478,f,875,476,875,475,j,875,473,884,473,884,458,877,458,f,877,457,877,448,877,442,873,440,872,439,871,432,867,429,866,428,j,866,392,f,863,391,861,388,858,385,855,384,j,855,378,f,862,379,862,375,862,371,856,365,849,359,849,357,849,351,852,353,j,852,347,860,347,860,341,866,341,866,335,f,871,335,878,333,j,878,324,f,873,325,873,322,872,318,872,317,867,313,866,311,861,307,860,304,861,300,861,292,860,282,858,280,852,276,850,270,c]],label:"West-Vlaanderen",shortLabel:"WV",labelPosition:[52.4,77.3],labelAlignment:[t,v]}}}]; g=d.length;if(r){while(g--){e=d[g];n(e.name.toLowerCase(),e,n.geo);}}else{while(g--){e=d[g];u=e.name.toLowerCase();a(s,u,1);h[s].unshift({cmd:"_call",obj:window,args:[function(w,x){if(!n.geo){p.raiseError(p.core,"12052314141","run","JavaScriptRenderer~Maps._call()",new Error("FusionCharts.HC.Maps.js is required in order to define vizualization")); return;}n(w,x,n.geo);},[u,e],window]});}}}]);
import path from 'path'; import webpack from 'webpack'; import autoprefixer from 'autoprefixer'; const SRC_DIR = path.join(__dirname, '../'); export default { devtool: 'source-map', entry: [ 'babel-polyfill', 'webpack-dev-server/client?http://0.0.0.0:3000', 'webpack/hot/dev-server', './index', ], output: { path: path.join(__dirname, '../dist'), filename: 'bundle.js', publicPath: '/static/', }, plugins: [new webpack.HotModuleReplacementPlugin()], module: { loaders: [ { test: /\.js?$/, loaders: ['babel'], include: SRC_DIR, exclude: /node_modules/, }, { test: /\.css$/, loader: 'style-loader!css-loader', }, { test: /\.(jpe?g|png|gif|svg|woff|woff2)$/i, loader: 'file-loader?name=icons/[name].[ext]', }, ], }, postcss: [autoprefixer({ browsers: ['last 2 versions'] })], };
describe('Auth', function () { beforeEach(module('components.auth')); beforeEach(module(function ($stateProvider) { $stateProvider.state('app', { url: '/' }); })); describe('Routes', function () { var $state, AuthService, $location, $rootScope, $q; function goTo(url) { $location.url(url); $rootScope.$digest(); } beforeEach(inject(function ($injector) { $state = $injector.get('$state'); AuthService = $injector.get('AuthService'); $location = $injector.get('$location'); $rootScope = $injector.get('$rootScope'); $q = $injector.get('$q'); })); it('should redirect to auth.login state', function() { spyOn(AuthService, 'requireAuthentication').and.callFake( function () { return $q.reject('Not authenticated!'); } ); goTo('/app'); expect($state.current.name).toEqual('auth.login') }); it('should redirect to app state', function() { spyOn(AuthService, 'isAuthenticated').and.returnValue(true); goTo('/auth'); expect($state.current.name).toEqual('app') }); }); describe('AuthService', function () { var AuthService, $firebaseAuth, $rootScope; beforeEach(inject(function ($injector) { AuthService = $injector.get('AuthService'); $firebaseAuth = $injector.get('$firebaseAuth')(); $rootScope = $injector.get('$rootScope'); })); it('should return undefined for initial user', function () { expect(AuthService.getUser()).toBeUndefined(); }); it('should login and store the authenticated user', function () { var user = { email: 'test@test.com', password: 'insecure' }, response = { $id: 1 }, promise = AuthService.login(user); promise.then(function (result) { expect(result).toEqual(response); expect(AuthService.isAuthenticated()).toBe(true); expect(AuthService.getUser()).toEqual(response); }); $rootScope.$digest(); }); it('should properly store auth data when registering a user', function () { var user = { email: 'test@test.com', password: 'insecure' }, response = { $id: 1 }, promise = AuthService.register(user); promise.then(function (result) { expect(result).toEqual(response); expect(AuthService.isAuthenticated()).toBe(true); expect(AuthService.getUser()).toEqual(response); }); $rootScope.$digest(); }); it('should clear auth data when logout is called', function () { var promise = AuthService.logout(); promise.then(function (result) { expect(AuthService.isAuthenticated()).toBe(false); expect(AuthService.getUser()).toBeUndefined(); }); $rootScope.$digest(); }); it('should should return correct auth data on getUser', function () { var user = { email: 'test@test.com', password: 'insecure' }, response = { $id: 1 }, promise = AuthService.login(user); promise.then(function (result) { expect(AuthService.getUser()).toEqual(response); }); $rootScope.$digest(); promise = AuthService.logout(); promise.then(function (result) { expect(AuthService.getUser()).toBeUndefined(); }); $rootScope.$digest(); }); it('should should return correct response on requireAuthentication', function () { var response = { $id: 1 }, promise = AuthService.requireAuthentication(); promise.then(function (result) { expect(result).toEqual(response); }); $rootScope.$digest(); }); }); });
/*! * FullCalendar v2.3.0 * Docs & License: http://arshaw.com/fullcalendar/ * (c) 2013 Adam Shaw */ (function(factory) { if (typeof define === 'function' && define.amd) { define([ 'jquery', 'moment' ], factory); } else { factory(jQuery, moment); } })(function($, moment) { ;; var fc = $.fullCalendar = { version: "2.3.0" }; var fcViews = fc.views = {}; $.fn.fullCalendar = function(options) { var args = Array.prototype.slice.call(arguments, 1); // for a possible method call var res = this; // what this function will return (this jQuery object by default) this.each(function(i, _element) { // loop each DOM element involved var element = $(_element); var calendar = element.data('fullCalendar'); // get the existing calendar object (if any) var singleRes; // the returned value of this single method call // a method call if (typeof options === 'string') { if (calendar && $.isFunction(calendar[options])) { singleRes = calendar[options].apply(calendar, args); if (!i) { res = singleRes; // record the first method call result } if (options === 'destroy') { // for the destroy method, must remove Calendar object data element.removeData('fullCalendar'); } } } // a new calendar initialization else if (!calendar) { // don't initialize twice calendar = new fc.CalendarBase(element, options); element.data('fullCalendar', calendar); calendar.render(); } }); return res; }; var complexOptions = [ // names of options that are objects whose properties should be combined 'header', 'buttonText', 'buttonIcons', 'themeButtonIcons' ]; // Recursively combines all passed-in option-hash arguments into a new single option-hash. // Given option-hashes are ordered from lowest to highest priority. function mergeOptions() { var chain = Array.prototype.slice.call(arguments); // convert to a real array var complexVals = {}; // hash for each complex option's combined values var i, name; var combinedVal; var j; var val; // for each complex option, loop through each option-hash and accumulate the combined values for (i = 0; i < complexOptions.length; i++) { name = complexOptions[i]; combinedVal = null; // an object holding the merge of all the values for (j = 0; j < chain.length; j++) { val = chain[j][name]; if ($.isPlainObject(val)) { combinedVal = $.extend(combinedVal || {}, val); // merge new properties } else if (val != null) { // a non-null non-undefined atomic option combinedVal = null; // signal to use the atomic value } } // if not null, the final value was a combination of other objects. record it if (combinedVal !== null) { complexVals[name] = combinedVal; } } chain.unshift({}); // $.extend will mutate this with the result chain.push(complexVals); // computed complex values are applied last return $.extend.apply($, chain); // combine } // Given options specified for the calendar's constructor, massages any legacy options into a non-legacy form. // Converts View-Option-Hashes into the View-Specific-Options format. function massageOverrides(input) { var overrides = { views: input.views || {} }; // the output. ensure a `views` hash var subObj; // iterate through all option override properties (except `views`) $.each(input, function(name, val) { if (name != 'views') { // could the value be a legacy View-Option-Hash? if ( $.isPlainObject(val) && !/(time|duration|interval)$/i.test(name) && // exclude duration options. might be given as objects $.inArray(name, complexOptions) == -1 // complex options aren't allowed to be View-Option-Hashes ) { subObj = null; // iterate through the properties of this possible View-Option-Hash value $.each(val, function(subName, subVal) { // is the property targeting a view? if (/^(month|week|day|default|basic(Week|Day)?|agenda(Week|Day)?)$/.test(subName)) { if (!overrides.views[subName]) { // ensure the view-target entry exists overrides.views[subName] = {}; } overrides.views[subName][name] = subVal; // record the value in the `views` object } else { // a non-View-Option-Hash property if (!subObj) { subObj = {}; } subObj[subName] = subVal; // accumulate these unrelated values for later } }); if (subObj) { // non-View-Option-Hash properties? transfer them as-is overrides[name] = subObj; } } else { overrides[name] = val; // transfer normal options as-is } } }); return overrides; } ;; // exports fc.intersectionToSeg = intersectionToSeg; fc.applyAll = applyAll; fc.debounce = debounce; fc.isInt = isInt; fc.htmlEscape = htmlEscape; fc.cssToStr = cssToStr; fc.proxy = proxy; /* FullCalendar-specific DOM Utilities ----------------------------------------------------------------------------------------------------------------------*/ // Given the scrollbar widths of some other container, create borders/margins on rowEls in order to match the left // and right space that was offset by the scrollbars. A 1-pixel border first, then margin beyond that. function compensateScroll(rowEls, scrollbarWidths) { if (scrollbarWidths.left) { rowEls.css({ 'border-left-width': 1, 'margin-left': scrollbarWidths.left - 1 }); } if (scrollbarWidths.right) { rowEls.css({ 'border-right-width': 1, 'margin-right': scrollbarWidths.right - 1 }); } } // Undoes compensateScroll and restores all borders/margins function uncompensateScroll(rowEls) { rowEls.css({ 'margin-left': '', 'margin-right': '', 'border-left-width': '', 'border-right-width': '' }); } // Make the mouse cursor express that an event is not allowed in the current area function disableCursor() { $('body').addClass('fc-not-allowed'); } // Returns the mouse cursor to its original look function enableCursor() { $('body').removeClass('fc-not-allowed'); } // Given a total available height to fill, have `els` (essentially child rows) expand to accomodate. // By default, all elements that are shorter than the recommended height are expanded uniformly, not considering // any other els that are already too tall. if `shouldRedistribute` is on, it considers these tall rows and // reduces the available height. function distributeHeight(els, availableHeight, shouldRedistribute) { // *FLOORING NOTE*: we floor in certain places because zoom can give inaccurate floating-point dimensions, // and it is better to be shorter than taller, to avoid creating unnecessary scrollbars. var minOffset1 = Math.floor(availableHeight / els.length); // for non-last element var minOffset2 = Math.floor(availableHeight - minOffset1 * (els.length - 1)); // for last element *FLOORING NOTE* var flexEls = []; // elements that are allowed to expand. array of DOM nodes var flexOffsets = []; // amount of vertical space it takes up var flexHeights = []; // actual css height var usedHeight = 0; undistributeHeight(els); // give all elements their natural height // find elements that are below the recommended height (expandable). // important to query for heights in a single first pass (to avoid reflow oscillation). els.each(function(i, el) { var minOffset = i === els.length - 1 ? minOffset2 : minOffset1; var naturalOffset = $(el).outerHeight(true); if (naturalOffset < minOffset) { flexEls.push(el); flexOffsets.push(naturalOffset); flexHeights.push($(el).height()); } else { // this element stretches past recommended height (non-expandable). mark the space as occupied. usedHeight += naturalOffset; } }); // readjust the recommended height to only consider the height available to non-maxed-out rows. if (shouldRedistribute) { availableHeight -= usedHeight; minOffset1 = Math.floor(availableHeight / flexEls.length); minOffset2 = Math.floor(availableHeight - minOffset1 * (flexEls.length - 1)); // *FLOORING NOTE* } // assign heights to all expandable elements $(flexEls).each(function(i, el) { var minOffset = i === flexEls.length - 1 ? minOffset2 : minOffset1; var naturalOffset = flexOffsets[i]; var naturalHeight = flexHeights[i]; var newHeight = minOffset - (naturalOffset - naturalHeight); // subtract the margin/padding if (naturalOffset < minOffset) { // we check this again because redistribution might have changed things $(el).height(newHeight); } }); } // Undoes distrubuteHeight, restoring all els to their natural height function undistributeHeight(els) { els.height(''); } // Given `els`, a jQuery set of <td> cells, find the cell with the largest natural width and set the widths of all the // cells to be that width. // PREREQUISITE: if you want a cell to take up width, it needs to have a single inner element w/ display:inline function matchCellWidths(els) { var maxInnerWidth = 0; els.find('> *').each(function(i, innerEl) { var innerWidth = $(innerEl).outerWidth(); if (innerWidth > maxInnerWidth) { maxInnerWidth = innerWidth; } }); maxInnerWidth++; // sometimes not accurate of width the text needs to stay on one line. insurance els.width(maxInnerWidth); return maxInnerWidth; } // Turns a container element into a scroller if its contents is taller than the allotted height. // Returns true if the element is now a scroller, false otherwise. // NOTE: this method is best because it takes weird zooming dimensions into account function setPotentialScroller(containerEl, height) { containerEl.height(height).addClass('fc-scroller'); // are scrollbars needed? if (containerEl[0].scrollHeight - 1 > containerEl[0].clientHeight) { // !!! -1 because IE is often off-by-one :( return true; } unsetScroller(containerEl); // undo return false; } // Takes an element that might have been a scroller, and turns it back into a normal element. function unsetScroller(containerEl) { containerEl.height('').removeClass('fc-scroller'); } /* General DOM Utilities ----------------------------------------------------------------------------------------------------------------------*/ fc.getClientRect = getClientRect; fc.getContentRect = getContentRect; fc.getScrollbarWidths = getScrollbarWidths; // borrowed from https://github.com/jquery/jquery-ui/blob/1.11.0/ui/core.js#L51 function getScrollParent(el) { var position = el.css('position'), scrollParent = el.parents().filter(function() { var parent = $(this); return (/(auto|scroll)/).test( parent.css('overflow') + parent.css('overflow-y') + parent.css('overflow-x') ); }).eq(0); return position === 'fixed' || !scrollParent.length ? $(el[0].ownerDocument || document) : scrollParent; } // Queries the outer bounding area of a jQuery element. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive). function getOuterRect(el) { var offset = el.offset(); return { left: offset.left, right: offset.left + el.outerWidth(), top: offset.top, bottom: offset.top + el.outerHeight() }; } // Queries the area within the margin/border/scrollbars of a jQuery element. Does not go within the padding. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive). // NOTE: should use clientLeft/clientTop, but very unreliable cross-browser. function getClientRect(el) { var offset = el.offset(); var scrollbarWidths = getScrollbarWidths(el); var left = offset.left + getCssFloat(el, 'border-left-width') + scrollbarWidths.left; var top = offset.top + getCssFloat(el, 'border-top-width') + scrollbarWidths.top; return { left: left, right: left + el[0].clientWidth, // clientWidth includes padding but NOT scrollbars top: top, bottom: top + el[0].clientHeight // clientHeight includes padding but NOT scrollbars }; } // Queries the area within the margin/border/padding of a jQuery element. Assumed not to have scrollbars. // Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive). function getContentRect(el) { var offset = el.offset(); // just outside of border, margin not included var left = offset.left + getCssFloat(el, 'border-left-width') + getCssFloat(el, 'padding-left'); var top = offset.top + getCssFloat(el, 'border-top-width') + getCssFloat(el, 'padding-top'); return { left: left, right: left + el.width(), top: top, bottom: top + el.height() }; } // Returns the computed left/right/top/bottom scrollbar widths for the given jQuery element. // NOTE: should use clientLeft/clientTop, but very unreliable cross-browser. function getScrollbarWidths(el) { var leftRightWidth = el.innerWidth() - el[0].clientWidth; // the paddings cancel out, leaving the scrollbars var widths = { left: 0, right: 0, top: 0, bottom: el.innerHeight() - el[0].clientHeight // the paddings cancel out, leaving the bottom scrollbar }; if (getIsLeftRtlScrollbars() && el.css('direction') == 'rtl') { // is the scrollbar on the left side? widths.left = leftRightWidth; } else { widths.right = leftRightWidth; } return widths; } // Logic for determining if, when the element is right-to-left, the scrollbar appears on the left side var _isLeftRtlScrollbars = null; function getIsLeftRtlScrollbars() { // responsible for caching the computation if (_isLeftRtlScrollbars === null) { _isLeftRtlScrollbars = computeIsLeftRtlScrollbars(); } return _isLeftRtlScrollbars; } function computeIsLeftRtlScrollbars() { // creates an offscreen test element, then removes it var el = $('<div><div/></div>') .css({ position: 'absolute', top: -1000, left: 0, border: 0, padding: 0, overflow: 'scroll', direction: 'rtl' }) .appendTo('body'); var innerEl = el.children(); var res = innerEl.offset().left > el.offset().left; // is the inner div shifted to accommodate a left scrollbar? el.remove(); return res; } // Retrieves a jQuery element's computed CSS value as a floating-point number. // If the queried value is non-numeric (ex: IE can return "medium" for border width), will just return zero. function getCssFloat(el, prop) { return parseFloat(el.css(prop)) || 0; } // Returns a boolean whether this was a left mouse click and no ctrl key (which means right click on Mac) function isPrimaryMouseButton(ev) { return ev.which == 1 && !ev.ctrlKey; } /* Geometry ----------------------------------------------------------------------------------------------------------------------*/ // Returns a new rectangle that is the intersection of the two rectangles. If they don't intersect, returns false function intersectRects(rect1, rect2) { var res = { left: Math.max(rect1.left, rect2.left), right: Math.min(rect1.right, rect2.right), top: Math.max(rect1.top, rect2.top), bottom: Math.min(rect1.bottom, rect2.bottom) }; if (res.left < res.right && res.top < res.bottom) { return res; } return false; } // Returns a new point that will have been moved to reside within the given rectangle function constrainPoint(point, rect) { return { left: Math.min(Math.max(point.left, rect.left), rect.right), top: Math.min(Math.max(point.top, rect.top), rect.bottom) }; } // Returns a point that is the center of the given rectangle function getRectCenter(rect) { return { left: (rect.left + rect.right) / 2, top: (rect.top + rect.bottom) / 2 }; } // Subtracts point2's coordinates from point1's coordinates, returning a delta function diffPoints(point1, point2) { return { left: point1.left - point2.left, top: point1.top - point2.top }; } /* FullCalendar-specific Misc Utilities ----------------------------------------------------------------------------------------------------------------------*/ // Creates a basic segment with the intersection of the two ranges. Returns undefined if no intersection. // Expects all dates to be normalized to the same timezone beforehand. // TODO: move to date section? function intersectionToSeg(subjectRange, constraintRange) { var subjectStart = subjectRange.start; var subjectEnd = subjectRange.end; var constraintStart = constraintRange.start; var constraintEnd = constraintRange.end; var segStart, segEnd; var isStart, isEnd; if (subjectEnd > constraintStart && subjectStart < constraintEnd) { // in bounds at all? if (subjectStart >= constraintStart) { segStart = subjectStart.clone(); isStart = true; } else { segStart = constraintStart.clone(); isStart = false; } if (subjectEnd <= constraintEnd) { segEnd = subjectEnd.clone(); isEnd = true; } else { segEnd = constraintEnd.clone(); isEnd = false; } return { start: segStart, end: segEnd, isStart: isStart, isEnd: isEnd }; } } /* Date Utilities ----------------------------------------------------------------------------------------------------------------------*/ fc.computeIntervalUnit = computeIntervalUnit; fc.durationHasTime = durationHasTime; var dayIDs = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ]; var intervalUnits = [ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond' ]; // Diffs the two moments into a Duration where full-days are recorded first, then the remaining time. // Moments will have their timezones normalized. function diffDayTime(a, b) { return moment.duration({ days: a.clone().stripTime().diff(b.clone().stripTime(), 'days'), ms: a.time() - b.time() // time-of-day from day start. disregards timezone }); } // Diffs the two moments via their start-of-day (regardless of timezone). Produces whole-day durations. function diffDay(a, b) { return moment.duration({ days: a.clone().stripTime().diff(b.clone().stripTime(), 'days') }); } // Diffs two moments, producing a duration, made of a whole-unit-increment of the given unit. Uses rounding. function diffByUnit(a, b, unit) { return moment.duration( Math.round(a.diff(b, unit, true)), // returnFloat=true unit ); } // Computes the unit name of the largest whole-unit period of time. // For example, 48 hours will be "days" whereas 49 hours will be "hours". // Accepts start/end, a range object, or an original duration object. function computeIntervalUnit(start, end) { var i, unit; var val; for (i = 0; i < intervalUnits.length; i++) { unit = intervalUnits[i]; val = computeRangeAs(unit, start, end); if (val >= 1 && isInt(val)) { break; } } return unit; // will be "milliseconds" if nothing else matches } // Computes the number of units (like "hours") in the given range. // Range can be a {start,end} object, separate start/end args, or a Duration. // Results are based on Moment's .as() and .diff() methods, so results can depend on internal handling // of month-diffing logic (which tends to vary from version to version). function computeRangeAs(unit, start, end) { if (end != null) { // given start, end return end.diff(start, unit, true); } else if (moment.isDuration(start)) { // given duration return start.as(unit); } else { // given { start, end } range object return start.end.diff(start.start, unit, true); } } // Returns a boolean about whether the given duration has any time parts (hours/minutes/seconds/ms) function durationHasTime(dur) { return Boolean(dur.hours() || dur.minutes() || dur.seconds() || dur.milliseconds()); } function isNativeDate(input) { return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; } // Returns a boolean about whether the given input is a time string, like "06:40:00" or "06:00" function isTimeString(str) { return /^\d+\:\d+(?:\:\d+\.?(?:\d{3})?)?$/.test(str); } /* General Utilities ----------------------------------------------------------------------------------------------------------------------*/ var hasOwnPropMethod = {}.hasOwnProperty; // Create an object that has the given prototype. Just like Object.create function createObject(proto) { var f = function() {}; f.prototype = proto; return new f(); } function copyOwnProps(src, dest) { for (var name in src) { if (hasOwnProp(src, name)) { dest[name] = src[name]; } } } // Copies over certain methods with the same names as Object.prototype methods. Overcomes an IE<=8 bug: // https://developer.mozilla.org/en-US/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug function copyNativeMethods(src, dest) { var names = [ 'constructor', 'toString', 'valueOf' ]; var i, name; for (i = 0; i < names.length; i++) { name = names[i]; if (src[name] !== Object.prototype[name]) { dest[name] = src[name]; } } } function hasOwnProp(obj, name) { return hasOwnPropMethod.call(obj, name); } // Is the given value a non-object non-function value? function isAtomic(val) { return /undefined|null|boolean|number|string/.test($.type(val)); } function applyAll(functions, thisObj, args) { if ($.isFunction(functions)) { functions = [ functions ]; } if (functions) { var i; var ret; for (i=0; i<functions.length; i++) { ret = functions[i].apply(thisObj, args) || ret; } return ret; } } function firstDefined() { for (var i=0; i<arguments.length; i++) { if (arguments[i] !== undefined) { return arguments[i]; } } } function htmlEscape(s) { return (s + '').replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/'/g, '&#039;') .replace(/"/g, '&quot;') .replace(/\n/g, '<br />'); } function stripHtmlEntities(text) { return text.replace(/&.*?;/g, ''); } // Given a hash of CSS properties, returns a string of CSS. // Uses property names as-is (no camel-case conversion). Will not make statements for null/undefined values. function cssToStr(cssProps) { var statements = []; $.each(cssProps, function(name, val) { if (val != null) { statements.push(name + ':' + val); } }); return statements.join(';'); } function capitaliseFirstLetter(str) { return str.charAt(0).toUpperCase() + str.slice(1); } function compareNumbers(a, b) { // for .sort() return a - b; } function isInt(n) { return n % 1 === 0; } // Returns a method bound to the given object context. // Just like one of the jQuery.proxy signatures, but without the undesired behavior of treating the same method with // different contexts as identical when binding/unbinding events. function proxy(obj, methodName) { var method = obj[methodName]; return function() { return method.apply(obj, arguments); }; } // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. // https://github.com/jashkenas/underscore/blob/1.6.0/underscore.js#L714 function debounce(func, wait) { var timeoutId; var args; var context; var timestamp; // of most recent call var later = function() { var last = +new Date() - timestamp; if (last < wait && last > 0) { timeoutId = setTimeout(later, wait - last); } else { timeoutId = null; func.apply(context, args); if (!timeoutId) { context = args = null; } } }; return function() { context = this; args = arguments; timestamp = +new Date(); if (!timeoutId) { timeoutId = setTimeout(later, wait); } }; } ;; var ambigDateOfMonthRegex = /^\s*\d{4}-\d\d$/; var ambigTimeOrZoneRegex = /^\s*\d{4}-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?)?$/; var newMomentProto = moment.fn; // where we will attach our new methods var oldMomentProto = $.extend({}, newMomentProto); // copy of original moment methods var allowValueOptimization; var setUTCValues; // function defined below var setLocalValues; // function defined below // Creating // ------------------------------------------------------------------------------------------------- // Creates a new moment, similar to the vanilla moment(...) constructor, but with // extra features (ambiguous time, enhanced formatting). When given an existing moment, // it will function as a clone (and retain the zone of the moment). Anything else will // result in a moment in the local zone. fc.moment = function() { return makeMoment(arguments); }; // Sames as fc.moment, but forces the resulting moment to be in the UTC timezone. fc.moment.utc = function() { var mom = makeMoment(arguments, true); // Force it into UTC because makeMoment doesn't guarantee it // (if given a pre-existing moment for example) if (mom.hasTime()) { // don't give ambiguously-timed moments a UTC zone mom.utc(); } return mom; }; // Same as fc.moment, but when given an ISO8601 string, the timezone offset is preserved. // ISO8601 strings with no timezone offset will become ambiguously zoned. fc.moment.parseZone = function() { return makeMoment(arguments, true, true); }; // Builds an enhanced moment from args. When given an existing moment, it clones. When given a // native Date, or called with no arguments (the current time), the resulting moment will be local. // Anything else needs to be "parsed" (a string or an array), and will be affected by: // parseAsUTC - if there is no zone information, should we parse the input in UTC? // parseZone - if there is zone information, should we force the zone of the moment? function makeMoment(args, parseAsUTC, parseZone) { var input = args[0]; var isSingleString = args.length == 1 && typeof input === 'string'; var isAmbigTime; var isAmbigZone; var ambigMatch; var mom; if (moment.isMoment(input)) { mom = moment.apply(null, args); // clone it transferAmbigs(input, mom); // the ambig flags weren't transfered with the clone } else if (isNativeDate(input) || input === undefined) { mom = moment.apply(null, args); // will be local } else { // "parsing" is required isAmbigTime = false; isAmbigZone = false; if (isSingleString) { if (ambigDateOfMonthRegex.test(input)) { // accept strings like '2014-05', but convert to the first of the month input += '-01'; args = [ input ]; // for when we pass it on to moment's constructor isAmbigTime = true; isAmbigZone = true; } else if ((ambigMatch = ambigTimeOrZoneRegex.exec(input))) { isAmbigTime = !ambigMatch[5]; // no time part? isAmbigZone = true; } } else if ($.isArray(input)) { // arrays have no timezone information, so assume ambiguous zone isAmbigZone = true; } // otherwise, probably a string with a format if (parseAsUTC || isAmbigTime) { mom = moment.utc.apply(moment, args); } else { mom = moment.apply(null, args); } if (isAmbigTime) { mom._ambigTime = true; mom._ambigZone = true; // ambiguous time always means ambiguous zone } else if (parseZone) { // let's record the inputted zone somehow if (isAmbigZone) { mom._ambigZone = true; } else if (isSingleString) { if (mom.utcOffset) { mom.utcOffset(input); // if not a valid zone, will assign UTC } else { mom.zone(input); // for moment-pre-2.9 } } } } mom._fullCalendar = true; // flag for extended functionality return mom; } // A clone method that works with the flags related to our enhanced functionality. // In the future, use moment.momentProperties newMomentProto.clone = function() { var mom = oldMomentProto.clone.apply(this, arguments); // these flags weren't transfered with the clone transferAmbigs(this, mom); if (this._fullCalendar) { mom._fullCalendar = true; } return mom; }; // Week Number // ------------------------------------------------------------------------------------------------- // Returns the week number, considering the locale's custom week number calcuation // `weeks` is an alias for `week` newMomentProto.week = newMomentProto.weeks = function(input) { var weekCalc = (this._locale || this._lang) // works pre-moment-2.8 ._fullCalendar_weekCalc; if (input == null && typeof weekCalc === 'function') { // custom function only works for getter return weekCalc(this); } else if (weekCalc === 'ISO') { return oldMomentProto.isoWeek.apply(this, arguments); // ISO getter/setter } return oldMomentProto.week.apply(this, arguments); // local getter/setter }; // Time-of-day // ------------------------------------------------------------------------------------------------- // GETTER // Returns a Duration with the hours/minutes/seconds/ms values of the moment. // If the moment has an ambiguous time, a duration of 00:00 will be returned. // // SETTER // You can supply a Duration, a Moment, or a Duration-like argument. // When setting the time, and the moment has an ambiguous time, it then becomes unambiguous. newMomentProto.time = function(time) { // Fallback to the original method (if there is one) if this moment wasn't created via FullCalendar. // `time` is a generic enough method name where this precaution is necessary to avoid collisions w/ other plugins. if (!this._fullCalendar) { return oldMomentProto.time.apply(this, arguments); } if (time == null) { // getter return moment.duration({ hours: this.hours(), minutes: this.minutes(), seconds: this.seconds(), milliseconds: this.milliseconds() }); } else { // setter this._ambigTime = false; // mark that the moment now has a time if (!moment.isDuration(time) && !moment.isMoment(time)) { time = moment.duration(time); } // The day value should cause overflow (so 24 hours becomes 00:00:00 of next day). // Only for Duration times, not Moment times. var dayHours = 0; if (moment.isDuration(time)) { dayHours = Math.floor(time.asDays()) * 24; } // We need to set the individual fields. // Can't use startOf('day') then add duration. In case of DST at start of day. return this.hours(dayHours + time.hours()) .minutes(time.minutes()) .seconds(time.seconds()) .milliseconds(time.milliseconds()); } }; // Converts the moment to UTC, stripping out its time-of-day and timezone offset, // but preserving its YMD. A moment with a stripped time will display no time // nor timezone offset when .format() is called. newMomentProto.stripTime = function() { var a; if (!this._ambigTime) { // get the values before any conversion happens a = this.toArray(); // array of y/m/d/h/m/s/ms // TODO: use keepLocalTime in the future this.utc(); // set the internal UTC flag (will clear the ambig flags) setUTCValues(this, a.slice(0, 3)); // set the year/month/date. time will be zero // Mark the time as ambiguous. This needs to happen after the .utc() call, which might call .utcOffset(), // which clears all ambig flags. Same with setUTCValues with moment-timezone. this._ambigTime = true; this._ambigZone = true; // if ambiguous time, also ambiguous timezone offset } return this; // for chaining }; // Returns if the moment has a non-ambiguous time (boolean) newMomentProto.hasTime = function() { return !this._ambigTime; }; // Timezone // ------------------------------------------------------------------------------------------------- // Converts the moment to UTC, stripping out its timezone offset, but preserving its // YMD and time-of-day. A moment with a stripped timezone offset will display no // timezone offset when .format() is called. // TODO: look into Moment's keepLocalTime functionality newMomentProto.stripZone = function() { var a, wasAmbigTime; if (!this._ambigZone) { // get the values before any conversion happens a = this.toArray(); // array of y/m/d/h/m/s/ms wasAmbigTime = this._ambigTime; this.utc(); // set the internal UTC flag (might clear the ambig flags, depending on Moment internals) setUTCValues(this, a); // will set the year/month/date/hours/minutes/seconds/ms // the above call to .utc()/.utcOffset() unfortunately might clear the ambig flags, so restore this._ambigTime = wasAmbigTime || false; // Mark the zone as ambiguous. This needs to happen after the .utc() call, which might call .utcOffset(), // which clears the ambig flags. Same with setUTCValues with moment-timezone. this._ambigZone = true; } return this; // for chaining }; // Returns of the moment has a non-ambiguous timezone offset (boolean) newMomentProto.hasZone = function() { return !this._ambigZone; }; // this method implicitly marks a zone newMomentProto.local = function() { var a = this.toArray(); // year,month,date,hours,minutes,seconds,ms as an array var wasAmbigZone = this._ambigZone; oldMomentProto.local.apply(this, arguments); // ensure non-ambiguous // this probably already happened via local() -> utcOffset(), but don't rely on Moment's internals this._ambigTime = false; this._ambigZone = false; if (wasAmbigZone) { // If the moment was ambiguously zoned, the date fields were stored as UTC. // We want to preserve these, but in local time. // TODO: look into Moment's keepLocalTime functionality setLocalValues(this, a); } return this; // for chaining }; // implicitly marks a zone newMomentProto.utc = function() { oldMomentProto.utc.apply(this, arguments); // ensure non-ambiguous // this probably already happened via utc() -> utcOffset(), but don't rely on Moment's internals this._ambigTime = false; this._ambigZone = false; return this; }; // methods for arbitrarily manipulating timezone offset. // should clear time/zone ambiguity when called. $.each([ 'zone', // only in moment-pre-2.9. deprecated afterwards 'utcOffset' ], function(i, name) { if (oldMomentProto[name]) { // original method exists? // this method implicitly marks a zone (will probably get called upon .utc() and .local()) newMomentProto[name] = function(tzo) { if (tzo != null) { // setter // these assignments needs to happen before the original zone method is called. // I forget why, something to do with a browser crash. this._ambigTime = false; this._ambigZone = false; } return oldMomentProto[name].apply(this, arguments); }; } }); // Formatting // ------------------------------------------------------------------------------------------------- newMomentProto.format = function() { if (this._fullCalendar && arguments[0]) { // an enhanced moment? and a format string provided? return formatDate(this, arguments[0]); // our extended formatting } if (this._ambigTime) { return oldMomentFormat(this, 'YYYY-MM-DD'); } if (this._ambigZone) { return oldMomentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss'); } return oldMomentProto.format.apply(this, arguments); }; newMomentProto.toISOString = function() { if (this._ambigTime) { return oldMomentFormat(this, 'YYYY-MM-DD'); } if (this._ambigZone) { return oldMomentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss'); } return oldMomentProto.toISOString.apply(this, arguments); }; // Querying // ------------------------------------------------------------------------------------------------- // Is the moment within the specified range? `end` is exclusive. // FYI, this method is not a standard Moment method, so always do our enhanced logic. newMomentProto.isWithin = function(start, end) { var a = commonlyAmbiguate([ this, start, end ]); return a[0] >= a[1] && a[0] < a[2]; }; // When isSame is called with units, timezone ambiguity is normalized before the comparison happens. // If no units specified, the two moments must be identically the same, with matching ambig flags. newMomentProto.isSame = function(input, units) { var a; // only do custom logic if this is an enhanced moment if (!this._fullCalendar) { return oldMomentProto.isSame.apply(this, arguments); } if (units) { a = commonlyAmbiguate([ this, input ], true); // normalize timezones but don't erase times return oldMomentProto.isSame.call(a[0], a[1], units); } else { input = fc.moment.parseZone(input); // normalize input return oldMomentProto.isSame.call(this, input) && Boolean(this._ambigTime) === Boolean(input._ambigTime) && Boolean(this._ambigZone) === Boolean(input._ambigZone); } }; // Make these query methods work with ambiguous moments $.each([ 'isBefore', 'isAfter' ], function(i, methodName) { newMomentProto[methodName] = function(input, units) { var a; // only do custom logic if this is an enhanced moment if (!this._fullCalendar) { return oldMomentProto[methodName].apply(this, arguments); } a = commonlyAmbiguate([ this, input ]); return oldMomentProto[methodName].call(a[0], a[1], units); }; }); // Misc Internals // ------------------------------------------------------------------------------------------------- // given an array of moment-like inputs, return a parallel array w/ moments similarly ambiguated. // for example, of one moment has ambig time, but not others, all moments will have their time stripped. // set `preserveTime` to `true` to keep times, but only normalize zone ambiguity. // returns the original moments if no modifications are necessary. function commonlyAmbiguate(inputs, preserveTime) { var anyAmbigTime = false; var anyAmbigZone = false; var len = inputs.length; var moms = []; var i, mom; // parse inputs into real moments and query their ambig flags for (i = 0; i < len; i++) { mom = inputs[i]; if (!moment.isMoment(mom)) { mom = fc.moment.parseZone(mom); } anyAmbigTime = anyAmbigTime || mom._ambigTime; anyAmbigZone = anyAmbigZone || mom._ambigZone; moms.push(mom); } // strip each moment down to lowest common ambiguity // use clones to avoid modifying the original moments for (i = 0; i < len; i++) { mom = moms[i]; if (!preserveTime && anyAmbigTime && !mom._ambigTime) { moms[i] = mom.clone().stripTime(); } else if (anyAmbigZone && !mom._ambigZone) { moms[i] = mom.clone().stripZone(); } } return moms; } // Transfers all the flags related to ambiguous time/zone from the `src` moment to the `dest` moment // TODO: look into moment.momentProperties for this. function transferAmbigs(src, dest) { if (src._ambigTime) { dest._ambigTime = true; } else if (dest._ambigTime) { dest._ambigTime = false; } if (src._ambigZone) { dest._ambigZone = true; } else if (dest._ambigZone) { dest._ambigZone = false; } } // Sets the year/month/date/etc values of the moment from the given array. // Inefficient because it calls each individual setter. function setMomentValues(mom, a) { mom.year(a[0] || 0) .month(a[1] || 0) .date(a[2] || 0) .hours(a[3] || 0) .minutes(a[4] || 0) .seconds(a[5] || 0) .milliseconds(a[6] || 0); } // Can we set the moment's internal date directly? allowValueOptimization = '_d' in moment() && 'updateOffset' in moment; // Utility function. Accepts a moment and an array of the UTC year/month/date/etc values to set. // Assumes the given moment is already in UTC mode. setUTCValues = allowValueOptimization ? function(mom, a) { // simlate what moment's accessors do mom._d.setTime(Date.UTC.apply(Date, a)); moment.updateOffset(mom, false); // keepTime=false } : setMomentValues; // Utility function. Accepts a moment and an array of the local year/month/date/etc values to set. // Assumes the given moment is already in local mode. setLocalValues = allowValueOptimization ? function(mom, a) { // simlate what moment's accessors do mom._d.setTime(+new Date( // FYI, there is now way to apply an array of args to a constructor a[0] || 0, a[1] || 0, a[2] || 0, a[3] || 0, a[4] || 0, a[5] || 0, a[6] || 0 )); moment.updateOffset(mom, false); // keepTime=false } : setMomentValues; ;; // Single Date Formatting // ------------------------------------------------------------------------------------------------- // call this if you want Moment's original format method to be used function oldMomentFormat(mom, formatStr) { return oldMomentProto.format.call(mom, formatStr); // oldMomentProto defined in moment-ext.js } // Formats `date` with a Moment formatting string, but allow our non-zero areas and // additional token. function formatDate(date, formatStr) { return formatDateWithChunks(date, getFormatStringChunks(formatStr)); } function formatDateWithChunks(date, chunks) { var s = ''; var i; for (i=0; i<chunks.length; i++) { s += formatDateWithChunk(date, chunks[i]); } return s; } // addition formatting tokens we want recognized var tokenOverrides = { t: function(date) { // "a" or "p" return oldMomentFormat(date, 'a').charAt(0); }, T: function(date) { // "A" or "P" return oldMomentFormat(date, 'A').charAt(0); } }; function formatDateWithChunk(date, chunk) { var token; var maybeStr; if (typeof chunk === 'string') { // a literal string return chunk; } else if ((token = chunk.token)) { // a token, like "YYYY" if (tokenOverrides[token]) { return tokenOverrides[token](date); // use our custom token } return oldMomentFormat(date, token); } else if (chunk.maybe) { // a grouping of other chunks that must be non-zero maybeStr = formatDateWithChunks(date, chunk.maybe); if (maybeStr.match(/[1-9]/)) { return maybeStr; } } return ''; } // Date Range Formatting // ------------------------------------------------------------------------------------------------- // TODO: make it work with timezone offset // Using a formatting string meant for a single date, generate a range string, like // "Sep 2 - 9 2013", that intelligently inserts a separator where the dates differ. // If the dates are the same as far as the format string is concerned, just return a single // rendering of one date, without any separator. function formatRange(date1, date2, formatStr, separator, isRTL) { var localeData; date1 = fc.moment.parseZone(date1); date2 = fc.moment.parseZone(date2); localeData = (date1.localeData || date1.lang).call(date1); // works with moment-pre-2.8 // Expand localized format strings, like "LL" -> "MMMM D YYYY" formatStr = localeData.longDateFormat(formatStr) || formatStr; // BTW, this is not important for `formatDate` because it is impossible to put custom tokens // or non-zero areas in Moment's localized format strings. separator = separator || ' - '; return formatRangeWithChunks( date1, date2, getFormatStringChunks(formatStr), separator, isRTL ); } fc.formatRange = formatRange; // expose function formatRangeWithChunks(date1, date2, chunks, separator, isRTL) { var chunkStr; // the rendering of the chunk var leftI; var leftStr = ''; var rightI; var rightStr = ''; var middleI; var middleStr1 = ''; var middleStr2 = ''; var middleStr = ''; // Start at the leftmost side of the formatting string and continue until you hit a token // that is not the same between dates. for (leftI=0; leftI<chunks.length; leftI++) { chunkStr = formatSimilarChunk(date1, date2, chunks[leftI]); if (chunkStr === false) { break; } leftStr += chunkStr; } // Similarly, start at the rightmost side of the formatting string and move left for (rightI=chunks.length-1; rightI>leftI; rightI--) { chunkStr = formatSimilarChunk(date1, date2, chunks[rightI]); if (chunkStr === false) { break; } rightStr = chunkStr + rightStr; } // The area in the middle is different for both of the dates. // Collect them distinctly so we can jam them together later. for (middleI=leftI; middleI<=rightI; middleI++) { middleStr1 += formatDateWithChunk(date1, chunks[middleI]); middleStr2 += formatDateWithChunk(date2, chunks[middleI]); } if (middleStr1 || middleStr2) { if (isRTL) { middleStr = middleStr2 + separator + middleStr1; } else { middleStr = middleStr1 + separator + middleStr2; } } return leftStr + middleStr + rightStr; } var similarUnitMap = { Y: 'year', M: 'month', D: 'day', // day of month d: 'day', // day of week // prevents a separator between anything time-related... A: 'second', // AM/PM a: 'second', // am/pm T: 'second', // A/P t: 'second', // a/p H: 'second', // hour (24) h: 'second', // hour (12) m: 'second', // minute s: 'second' // second }; // TODO: week maybe? // Given a formatting chunk, and given that both dates are similar in the regard the // formatting chunk is concerned, format date1 against `chunk`. Otherwise, return `false`. function formatSimilarChunk(date1, date2, chunk) { var token; var unit; if (typeof chunk === 'string') { // a literal string return chunk; } else if ((token = chunk.token)) { unit = similarUnitMap[token.charAt(0)]; // are the dates the same for this unit of measurement? if (unit && date1.isSame(date2, unit)) { return oldMomentFormat(date1, token); // would be the same if we used `date2` // BTW, don't support custom tokens } } return false; // the chunk is NOT the same for the two dates // BTW, don't support splitting on non-zero areas } // Chunking Utils // ------------------------------------------------------------------------------------------------- var formatStringChunkCache = {}; function getFormatStringChunks(formatStr) { if (formatStr in formatStringChunkCache) { return formatStringChunkCache[formatStr]; } return (formatStringChunkCache[formatStr] = chunkFormatString(formatStr)); } // Break the formatting string into an array of chunks function chunkFormatString(formatStr) { var chunks = []; var chunker = /\[([^\]]*)\]|\(([^\)]*)\)|(LTS|LT|(\w)\4*o?)|([^\w\[\(]+)/g; // TODO: more descrimination var match; while ((match = chunker.exec(formatStr))) { if (match[1]) { // a literal string inside [ ... ] chunks.push(match[1]); } else if (match[2]) { // non-zero formatting inside ( ... ) chunks.push({ maybe: chunkFormatString(match[2]) }); } else if (match[3]) { // a formatting token chunks.push({ token: match[3] }); } else if (match[5]) { // an unenclosed literal string chunks.push(match[5]); } } return chunks; } ;; fc.Class = Class; // export // class that all other classes will inherit from function Class() { } // called upon a class to create a subclass Class.extend = function(members) { var superClass = this; var subClass; members = members || {}; // ensure a constructor for the subclass, forwarding all arguments to the super-constructor if it doesn't exist if (hasOwnProp(members, 'constructor')) { subClass = members.constructor; } if (typeof subClass !== 'function') { subClass = members.constructor = function() { superClass.apply(this, arguments); }; } // build the base prototype for the subclass, which is an new object chained to the superclass's prototype subClass.prototype = createObject(superClass.prototype); // copy each member variable/method onto the the subclass's prototype copyOwnProps(members, subClass.prototype); copyNativeMethods(members, subClass.prototype); // hack for IE8 // copy over all class variables/methods to the subclass, such as `extend` and `mixin` copyOwnProps(superClass, subClass); return subClass; }; // adds new member variables/methods to the class's prototype. // can be called with another class, or a plain object hash containing new members. Class.mixin = function(members) { copyOwnProps(members.prototype || members, this.prototype); }; ;; /* A rectangular panel that is absolutely positioned over other content ------------------------------------------------------------------------------------------------------------------------ Options: - className (string) - content (HTML string or jQuery element set) - parentEl - top - left - right (the x coord of where the right edge should be. not a "CSS" right) - autoHide (boolean) - show (callback) - hide (callback) */ var Popover = Class.extend({ isHidden: true, options: null, el: null, // the container element for the popover. generated by this object documentMousedownProxy: null, // document mousedown handler bound to `this` margin: 10, // the space required between the popover and the edges of the scroll container constructor: function(options) { this.options = options || {}; }, // Shows the popover on the specified position. Renders it if not already show: function() { if (this.isHidden) { if (!this.el) { this.render(); } this.el.show(); this.position(); this.isHidden = false; this.trigger('show'); } }, // Hides the popover, through CSS, but does not remove it from the DOM hide: function() { if (!this.isHidden) { this.el.hide(); this.isHidden = true; this.trigger('hide'); } }, // Creates `this.el` and renders content inside of it render: function() { var _this = this; var options = this.options; this.el = $('<div class="fc-popover"/>') .addClass(options.className || '') .css({ // position initially to the top left to avoid creating scrollbars top: 0, left: 0 }) .append(options.content) .appendTo(options.parentEl); // when a click happens on anything inside with a 'fc-close' className, hide the popover this.el.on('click', '.fc-close', function() { _this.hide(); }); if (options.autoHide) { $(document).on('mousedown', this.documentMousedownProxy = proxy(this, 'documentMousedown')); } }, // Triggered when the user clicks *anywhere* in the document, for the autoHide feature documentMousedown: function(ev) { // only hide the popover if the click happened outside the popover if (this.el && !$(ev.target).closest(this.el).length) { this.hide(); } }, // Hides and unregisters any handlers destroy: function() { this.hide(); if (this.el) { this.el.remove(); this.el = null; } $(document).off('mousedown', this.documentMousedownProxy); }, // Positions the popover optimally, using the top/left/right options position: function() { var options = this.options; var origin = this.el.offsetParent().offset(); var width = this.el.outerWidth(); var height = this.el.outerHeight(); var windowEl = $(window); var viewportEl = getScrollParent(this.el); var viewportTop; var viewportLeft; var viewportOffset; var top; // the "position" (not "offset") values for the popover var left; // // compute top and left top = options.top || 0; if (options.left !== undefined) { left = options.left; } else if (options.right !== undefined) { left = options.right - width; // derive the left value from the right value } else { left = 0; } if (viewportEl.is(window) || viewportEl.is(document)) { // normalize getScrollParent's result viewportEl = windowEl; viewportTop = 0; // the window is always at the top left viewportLeft = 0; // (and .offset() won't work if called here) } else { viewportOffset = viewportEl.offset(); viewportTop = viewportOffset.top; viewportLeft = viewportOffset.left; } // if the window is scrolled, it causes the visible area to be further down viewportTop += windowEl.scrollTop(); viewportLeft += windowEl.scrollLeft(); // constrain to the view port. if constrained by two edges, give precedence to top/left if (options.viewportConstrain !== false) { top = Math.min(top, viewportTop + viewportEl.outerHeight() - height - this.margin); top = Math.max(top, viewportTop + this.margin); left = Math.min(left, viewportLeft + viewportEl.outerWidth() - width - this.margin); left = Math.max(left, viewportLeft + this.margin); } this.el.css({ top: top - origin.top, left: left - origin.left }); }, // Triggers a callback. Calls a function in the option hash of the same name. // Arguments beyond the first `name` are forwarded on. // TODO: better code reuse for this. Repeat code trigger: function(name) { if (this.options[name]) { this.options[name].apply(this, Array.prototype.slice.call(arguments, 1)); } } }); ;; /* A "coordinate map" converts pixel coordinates into an associated cell, which has an associated date ------------------------------------------------------------------------------------------------------------------------ Common interface: CoordMap.prototype = { build: function() {}, getCell: function(x, y) {} }; */ /* Coordinate map for a grid component ----------------------------------------------------------------------------------------------------------------------*/ var GridCoordMap = Class.extend({ grid: null, // reference to the Grid rowCoords: null, // array of {top,bottom} objects colCoords: null, // array of {left,right} objects containerEl: null, // container element that all coordinates are constrained to. optionally assigned bounds: null, constructor: function(grid) { this.grid = grid; }, // Queries the grid for the coordinates of all the cells build: function() { this.rowCoords = this.grid.computeRowCoords(); this.colCoords = this.grid.computeColCoords(); this.computeBounds(); }, // Clears the coordinates data to free up memory clear: function() { this.rowCoords = null; this.colCoords = null; }, // Given a coordinate of the document, gets the associated cell. If no cell is underneath, returns null getCell: function(x, y) { var rowCoords = this.rowCoords; var rowCnt = rowCoords.length; var colCoords = this.colCoords; var colCnt = colCoords.length; var hitRow = null; var hitCol = null; var i, coords; var cell; if (this.inBounds(x, y)) { for (i = 0; i < rowCnt; i++) { coords = rowCoords[i]; if (y >= coords.top && y < coords.bottom) { hitRow = i; break; } } for (i = 0; i < colCnt; i++) { coords = colCoords[i]; if (x >= coords.left && x < coords.right) { hitCol = i; break; } } if (hitRow !== null && hitCol !== null) { cell = this.grid.getCell(hitRow, hitCol); // expected to return a fresh object we can modify cell.grid = this.grid; // for CellDragListener's isCellsEqual. dragging between grids // make the coordinates available on the cell object $.extend(cell, rowCoords[hitRow], colCoords[hitCol]); return cell; } } return null; }, // If there is a containerEl, compute the bounds into min/max values computeBounds: function() { this.bounds = this.containerEl ? getClientRect(this.containerEl) : // area within scrollbars null; }, // Determines if the given coordinates are in bounds. If no `containerEl`, always true inBounds: function(x, y) { var bounds = this.bounds; if (bounds) { return x >= bounds.left && x < bounds.right && y >= bounds.top && y < bounds.bottom; } return true; } }); /* Coordinate map that is a combination of multiple other coordinate maps ----------------------------------------------------------------------------------------------------------------------*/ var ComboCoordMap = Class.extend({ coordMaps: null, // an array of CoordMaps constructor: function(coordMaps) { this.coordMaps = coordMaps; }, // Builds all coordMaps build: function() { var coordMaps = this.coordMaps; var i; for (i = 0; i < coordMaps.length; i++) { coordMaps[i].build(); } }, // Queries all coordMaps for the cell underneath the given coordinates, returning the first result getCell: function(x, y) { var coordMaps = this.coordMaps; var cell = null; var i; for (i = 0; i < coordMaps.length && !cell; i++) { cell = coordMaps[i].getCell(x, y); } return cell; }, // Clears all coordMaps clear: function() { var coordMaps = this.coordMaps; var i; for (i = 0; i < coordMaps.length; i++) { coordMaps[i].clear(); } } }); ;; /* Tracks a drag's mouse movement, firing various handlers ----------------------------------------------------------------------------------------------------------------------*/ var DragListener = fc.DragListener = Class.extend({ options: null, isListening: false, isDragging: false, // coordinates of the initial mousedown originX: null, originY: null, // handler attached to the document, bound to the DragListener's `this` mousemoveProxy: null, mouseupProxy: null, // for IE8 bug-fighting behavior, for now subjectEl: null, // the element being draged. optional subjectHref: null, scrollEl: null, scrollBounds: null, // { top, bottom, left, right } scrollTopVel: null, // pixels per second scrollLeftVel: null, // pixels per second scrollIntervalId: null, // ID of setTimeout for scrolling animation loop scrollHandlerProxy: null, // this-scoped function for handling when scrollEl is scrolled scrollSensitivity: 30, // pixels from edge for scrolling to start scrollSpeed: 200, // pixels per second, at maximum speed scrollIntervalMs: 50, // millisecond wait between scroll increment constructor: function(options) { options = options || {}; this.options = options; this.subjectEl = options.subjectEl; }, // Call this when the user does a mousedown. Will probably lead to startListening mousedown: function(ev) { if (isPrimaryMouseButton(ev)) { ev.preventDefault(); // prevents native selection in most browsers this.startListening(ev); // start the drag immediately if there is no minimum distance for a drag start if (!this.options.distance) { this.startDrag(ev); } } }, // Call this to start tracking mouse movements startListening: function(ev) { var scrollParent; if (!this.isListening) { // grab scroll container and attach handler if (ev && this.options.scroll) { scrollParent = getScrollParent($(ev.target)); if (!scrollParent.is(window) && !scrollParent.is(document)) { this.scrollEl = scrollParent; // scope to `this`, and use `debounce` to make sure rapid calls don't happen this.scrollHandlerProxy = debounce(proxy(this, 'scrollHandler'), 100); this.scrollEl.on('scroll', this.scrollHandlerProxy); } } $(document) .on('mousemove', this.mousemoveProxy = proxy(this, 'mousemove')) .on('mouseup', this.mouseupProxy = proxy(this, 'mouseup')) .on('selectstart', this.preventDefault); // prevents native selection in IE<=8 if (ev) { this.originX = ev.pageX; this.originY = ev.pageY; } else { // if no starting information was given, origin will be the topleft corner of the screen. // if so, dx/dy in the future will be the absolute coordinates. this.originX = 0; this.originY = 0; } this.isListening = true; this.listenStart(ev); } }, // Called when drag listening has started (but a real drag has not necessarily began) listenStart: function(ev) { this.trigger('listenStart', ev); }, // Called when the user moves the mouse mousemove: function(ev) { var dx = ev.pageX - this.originX; var dy = ev.pageY - this.originY; var minDistance; var distanceSq; // current distance from the origin, squared if (!this.isDragging) { // if not already dragging... // then start the drag if the minimum distance criteria is met minDistance = this.options.distance || 1; distanceSq = dx * dx + dy * dy; if (distanceSq >= minDistance * minDistance) { // use pythagorean theorem this.startDrag(ev); } } if (this.isDragging) { this.drag(dx, dy, ev); // report a drag, even if this mousemove initiated the drag } }, // Call this to initiate a legitimate drag. // This function is called internally from this class, but can also be called explicitly from outside startDrag: function(ev) { if (!this.isListening) { // startDrag must have manually initiated this.startListening(); } if (!this.isDragging) { this.isDragging = true; this.dragStart(ev); } }, // Called when the actual drag has started (went beyond minDistance) dragStart: function(ev) { var subjectEl = this.subjectEl; this.trigger('dragStart', ev); // remove a mousedown'd <a>'s href so it is not visited (IE8 bug) if ((this.subjectHref = subjectEl ? subjectEl.attr('href') : null)) { subjectEl.removeAttr('href'); } }, // Called while the mouse is being moved and when we know a legitimate drag is taking place drag: function(dx, dy, ev) { this.trigger('drag', dx, dy, ev); this.updateScroll(ev); // will possibly cause scrolling }, // Called when the user does a mouseup mouseup: function(ev) { this.stopListening(ev); }, // Called when the drag is over. Will not cause listening to stop however. // A concluding 'cellOut' event will NOT be triggered. stopDrag: function(ev) { if (this.isDragging) { this.stopScrolling(); this.dragStop(ev); this.isDragging = false; } }, // Called when dragging has been stopped dragStop: function(ev) { var _this = this; this.trigger('dragStop', ev); // restore a mousedown'd <a>'s href (for IE8 bug) setTimeout(function() { // must be outside of the click's execution if (_this.subjectHref) { _this.subjectEl.attr('href', _this.subjectHref); } }, 0); }, // Call this to stop listening to the user's mouse events stopListening: function(ev) { this.stopDrag(ev); // if there's a current drag, kill it if (this.isListening) { // remove the scroll handler if there is a scrollEl if (this.scrollEl) { this.scrollEl.off('scroll', this.scrollHandlerProxy); this.scrollHandlerProxy = null; } $(document) .off('mousemove', this.mousemoveProxy) .off('mouseup', this.mouseupProxy) .off('selectstart', this.preventDefault); this.mousemoveProxy = null; this.mouseupProxy = null; this.isListening = false; this.listenStop(ev); } }, // Called when drag listening has stopped listenStop: function(ev) { this.trigger('listenStop', ev); }, // Triggers a callback. Calls a function in the option hash of the same name. // Arguments beyond the first `name` are forwarded on. trigger: function(name) { if (this.options[name]) { this.options[name].apply(this, Array.prototype.slice.call(arguments, 1)); } }, // Stops a given mouse event from doing it's native browser action. In our case, text selection. preventDefault: function(ev) { ev.preventDefault(); }, /* Scrolling ------------------------------------------------------------------------------------------------------------------*/ // Computes and stores the bounding rectangle of scrollEl computeScrollBounds: function() { var el = this.scrollEl; this.scrollBounds = el ? getOuterRect(el) : null; // TODO: use getClientRect in future. but prevents auto scrolling when on top of scrollbars }, // Called when the dragging is in progress and scrolling should be updated updateScroll: function(ev) { var sensitivity = this.scrollSensitivity; var bounds = this.scrollBounds; var topCloseness, bottomCloseness; var leftCloseness, rightCloseness; var topVel = 0; var leftVel = 0; if (bounds) { // only scroll if scrollEl exists // compute closeness to edges. valid range is from 0.0 - 1.0 topCloseness = (sensitivity - (ev.pageY - bounds.top)) / sensitivity; bottomCloseness = (sensitivity - (bounds.bottom - ev.pageY)) / sensitivity; leftCloseness = (sensitivity - (ev.pageX - bounds.left)) / sensitivity; rightCloseness = (sensitivity - (bounds.right - ev.pageX)) / sensitivity; // translate vertical closeness into velocity. // mouse must be completely in bounds for velocity to happen. if (topCloseness >= 0 && topCloseness <= 1) { topVel = topCloseness * this.scrollSpeed * -1; // negative. for scrolling up } else if (bottomCloseness >= 0 && bottomCloseness <= 1) { topVel = bottomCloseness * this.scrollSpeed; } // translate horizontal closeness into velocity if (leftCloseness >= 0 && leftCloseness <= 1) { leftVel = leftCloseness * this.scrollSpeed * -1; // negative. for scrolling left } else if (rightCloseness >= 0 && rightCloseness <= 1) { leftVel = rightCloseness * this.scrollSpeed; } } this.setScrollVel(topVel, leftVel); }, // Sets the speed-of-scrolling for the scrollEl setScrollVel: function(topVel, leftVel) { this.scrollTopVel = topVel; this.scrollLeftVel = leftVel; this.constrainScrollVel(); // massages into realistic values // if there is non-zero velocity, and an animation loop hasn't already started, then START if ((this.scrollTopVel || this.scrollLeftVel) && !this.scrollIntervalId) { this.scrollIntervalId = setInterval( proxy(this, 'scrollIntervalFunc'), // scope to `this` this.scrollIntervalMs ); } }, // Forces scrollTopVel and scrollLeftVel to be zero if scrolling has already gone all the way constrainScrollVel: function() { var el = this.scrollEl; if (this.scrollTopVel < 0) { // scrolling up? if (el.scrollTop() <= 0) { // already scrolled all the way up? this.scrollTopVel = 0; } } else if (this.scrollTopVel > 0) { // scrolling down? if (el.scrollTop() + el[0].clientHeight >= el[0].scrollHeight) { // already scrolled all the way down? this.scrollTopVel = 0; } } if (this.scrollLeftVel < 0) { // scrolling left? if (el.scrollLeft() <= 0) { // already scrolled all the left? this.scrollLeftVel = 0; } } else if (this.scrollLeftVel > 0) { // scrolling right? if (el.scrollLeft() + el[0].clientWidth >= el[0].scrollWidth) { // already scrolled all the way right? this.scrollLeftVel = 0; } } }, // This function gets called during every iteration of the scrolling animation loop scrollIntervalFunc: function() { var el = this.scrollEl; var frac = this.scrollIntervalMs / 1000; // considering animation frequency, what the vel should be mult'd by // change the value of scrollEl's scroll if (this.scrollTopVel) { el.scrollTop(el.scrollTop() + this.scrollTopVel * frac); } if (this.scrollLeftVel) { el.scrollLeft(el.scrollLeft() + this.scrollLeftVel * frac); } this.constrainScrollVel(); // since the scroll values changed, recompute the velocities // if scrolled all the way, which causes the vels to be zero, stop the animation loop if (!this.scrollTopVel && !this.scrollLeftVel) { this.stopScrolling(); } }, // Kills any existing scrolling animation loop stopScrolling: function() { if (this.scrollIntervalId) { clearInterval(this.scrollIntervalId); this.scrollIntervalId = null; // when all done with scrolling, recompute positions since they probably changed this.scrollStop(); } }, // Get called when the scrollEl is scrolled (NOTE: this is delayed via debounce) scrollHandler: function() { // recompute all coordinates, but *only* if this is *not* part of our scrolling animation if (!this.scrollIntervalId) { this.scrollStop(); } }, // Called when scrolling has stopped, whether through auto scroll, or the user scrolling scrollStop: function() { } }); ;; /* Tracks mouse movements over a CoordMap and raises events about which cell the mouse is over. ------------------------------------------------------------------------------------------------------------------------ options: - subjectEl - subjectCenter */ var CellDragListener = DragListener.extend({ coordMap: null, // converts coordinates to date cells origCell: null, // the cell the mouse was over when listening started cell: null, // the cell the mouse is over coordAdjust: null, // delta that will be added to the mouse coordinates when computing collisions constructor: function(coordMap, options) { DragListener.prototype.constructor.call(this, options); // call the super-constructor this.coordMap = coordMap; }, // Called when drag listening starts (but a real drag has not necessarily began). // ev might be undefined if dragging was started manually. listenStart: function(ev) { var subjectEl = this.subjectEl; var subjectRect; var origPoint; var point; DragListener.prototype.listenStart.apply(this, arguments); // call the super-method this.computeCoords(); if (ev) { origPoint = { left: ev.pageX, top: ev.pageY }; point = origPoint; // constrain the point to bounds of the element being dragged if (subjectEl) { subjectRect = getOuterRect(subjectEl); // used for centering as well point = constrainPoint(point, subjectRect); } this.origCell = this.getCell(point.left, point.top); // treat the center of the subject as the collision point? if (subjectEl && this.options.subjectCenter) { // only consider the area the subject overlaps the cell. best for large subjects if (this.origCell) { subjectRect = intersectRects(this.origCell, subjectRect) || subjectRect; // in case there is no intersection } point = getRectCenter(subjectRect); } this.coordAdjust = diffPoints(point, origPoint); // point - origPoint } else { this.origCell = null; this.coordAdjust = null; } }, // Recomputes the drag-critical positions of elements computeCoords: function() { this.coordMap.build(); this.computeScrollBounds(); }, // Called when the actual drag has started dragStart: function(ev) { var cell; DragListener.prototype.dragStart.apply(this, arguments); // call the super-method cell = this.getCell(ev.pageX, ev.pageY); // might be different from this.origCell if the min-distance is large // report the initial cell the mouse is over // especially important if no min-distance and drag starts immediately if (cell) { this.cellOver(cell); } }, // Called when the drag moves drag: function(dx, dy, ev) { var cell; DragListener.prototype.drag.apply(this, arguments); // call the super-method cell = this.getCell(ev.pageX, ev.pageY); if (!isCellsEqual(cell, this.cell)) { // a different cell than before? if (this.cell) { this.cellOut(); } if (cell) { this.cellOver(cell); } } }, // Called when dragging has been stopped dragStop: function() { this.cellDone(); DragListener.prototype.dragStop.apply(this, arguments); // call the super-method }, // Called when a the mouse has just moved over a new cell cellOver: function(cell) { this.cell = cell; this.trigger('cellOver', cell, isCellsEqual(cell, this.origCell), this.origCell); }, // Called when the mouse has just moved out of a cell cellOut: function() { if (this.cell) { this.trigger('cellOut', this.cell); this.cellDone(); this.cell = null; } }, // Called after a cellOut. Also called before a dragStop cellDone: function() { if (this.cell) { this.trigger('cellDone', this.cell); } }, // Called when drag listening has stopped listenStop: function() { DragListener.prototype.listenStop.apply(this, arguments); // call the super-method this.origCell = this.cell = null; this.coordMap.clear(); }, // Called when scrolling has stopped, whether through auto scroll, or the user scrolling scrollStop: function() { DragListener.prototype.scrollStop.apply(this, arguments); // call the super-method this.computeCoords(); // cells' absolute positions will be in new places. recompute }, // Gets the cell underneath the coordinates for the given mouse event getCell: function(left, top) { if (this.coordAdjust) { left += this.coordAdjust.left; top += this.coordAdjust.top; } return this.coordMap.getCell(left, top); } }); // Returns `true` if the cells are identically equal. `false` otherwise. // They must have the same row, col, and be from the same grid. // Two null values will be considered equal, as two "out of the grid" states are the same. function isCellsEqual(cell1, cell2) { if (!cell1 && !cell2) { return true; } if (cell1 && cell2) { return cell1.grid === cell2.grid && cell1.row === cell2.row && cell1.col === cell2.col; } return false; } ;; /* Creates a clone of an element and lets it track the mouse as it moves ----------------------------------------------------------------------------------------------------------------------*/ var MouseFollower = Class.extend({ options: null, sourceEl: null, // the element that will be cloned and made to look like it is dragging el: null, // the clone of `sourceEl` that will track the mouse parentEl: null, // the element that `el` (the clone) will be attached to // the initial position of el, relative to the offset parent. made to match the initial offset of sourceEl top0: null, left0: null, // the initial position of the mouse mouseY0: null, mouseX0: null, // the number of pixels the mouse has moved from its initial position topDelta: null, leftDelta: null, mousemoveProxy: null, // document mousemove handler, bound to the MouseFollower's `this` isFollowing: false, isHidden: false, isAnimating: false, // doing the revert animation? constructor: function(sourceEl, options) { this.options = options = options || {}; this.sourceEl = sourceEl; this.parentEl = options.parentEl ? $(options.parentEl) : sourceEl.parent(); // default to sourceEl's parent }, // Causes the element to start following the mouse start: function(ev) { if (!this.isFollowing) { this.isFollowing = true; this.mouseY0 = ev.pageY; this.mouseX0 = ev.pageX; this.topDelta = 0; this.leftDelta = 0; if (!this.isHidden) { this.updatePosition(); } $(document).on('mousemove', this.mousemoveProxy = proxy(this, 'mousemove')); } }, // Causes the element to stop following the mouse. If shouldRevert is true, will animate back to original position. // `callback` gets invoked when the animation is complete. If no animation, it is invoked immediately. stop: function(shouldRevert, callback) { var _this = this; var revertDuration = this.options.revertDuration; function complete() { this.isAnimating = false; _this.destroyEl(); this.top0 = this.left0 = null; // reset state for future updatePosition calls if (callback) { callback(); } } if (this.isFollowing && !this.isAnimating) { // disallow more than one stop animation at a time this.isFollowing = false; $(document).off('mousemove', this.mousemoveProxy); if (shouldRevert && revertDuration && !this.isHidden) { // do a revert animation? this.isAnimating = true; this.el.animate({ top: this.top0, left: this.left0 }, { duration: revertDuration, complete: complete }); } else { complete(); } } }, // Gets the tracking element. Create it if necessary getEl: function() { var el = this.el; if (!el) { this.sourceEl.width(); // hack to force IE8 to compute correct bounding box el = this.el = this.sourceEl.clone() .css({ position: 'absolute', visibility: '', // in case original element was hidden (commonly through hideEvents()) display: this.isHidden ? 'none' : '', // for when initially hidden margin: 0, right: 'auto', // erase and set width instead bottom: 'auto', // erase and set height instead width: this.sourceEl.width(), // explicit height in case there was a 'right' value height: this.sourceEl.height(), // explicit width in case there was a 'bottom' value opacity: this.options.opacity || '', zIndex: this.options.zIndex }) .appendTo(this.parentEl); } return el; }, // Removes the tracking element if it has already been created destroyEl: function() { if (this.el) { this.el.remove(); this.el = null; } }, // Update the CSS position of the tracking element updatePosition: function() { var sourceOffset; var origin; this.getEl(); // ensure this.el // make sure origin info was computed if (this.top0 === null) { this.sourceEl.width(); // hack to force IE8 to compute correct bounding box sourceOffset = this.sourceEl.offset(); origin = this.el.offsetParent().offset(); this.top0 = sourceOffset.top - origin.top; this.left0 = sourceOffset.left - origin.left; } this.el.css({ top: this.top0 + this.topDelta, left: this.left0 + this.leftDelta }); }, // Gets called when the user moves the mouse mousemove: function(ev) { this.topDelta = ev.pageY - this.mouseY0; this.leftDelta = ev.pageX - this.mouseX0; if (!this.isHidden) { this.updatePosition(); } }, // Temporarily makes the tracking element invisible. Can be called before following starts hide: function() { if (!this.isHidden) { this.isHidden = true; if (this.el) { this.el.hide(); } } }, // Show the tracking element after it has been temporarily hidden show: function() { if (this.isHidden) { this.isHidden = false; this.updatePosition(); this.getEl().show(); } } }); ;; /* A utility class for rendering <tr> rows. ----------------------------------------------------------------------------------------------------------------------*/ // It leverages methods of the subclass and the View to determine custom rendering behavior for each row "type" // (such as highlight rows, day rows, helper rows, etc). var RowRenderer = Class.extend({ view: null, // a View object isRTL: null, // shortcut to the view's isRTL option cellHtml: '<td/>', // plain default HTML used for a cell when no other is available constructor: function(view) { this.view = view; this.isRTL = view.opt('isRTL'); }, // Renders the HTML for a row, leveraging custom cell-HTML-renderers based on the `rowType`. // Also applies the "intro" and "outro" cells, which are specified by the subclass and views. // `row` is an optional row number. rowHtml: function(rowType, row) { var renderCell = this.getHtmlRenderer('cell', rowType); var rowCellHtml = ''; var col; var cell; row = row || 0; for (col = 0; col < this.colCnt; col++) { cell = this.getCell(row, col); rowCellHtml += renderCell(cell); } rowCellHtml = this.bookendCells(rowCellHtml, rowType, row); // apply intro and outro return '<tr>' + rowCellHtml + '</tr>'; }, // Applies the "intro" and "outro" HTML to the given cells. // Intro means the leftmost cell when the calendar is LTR and the rightmost cell when RTL. Vice-versa for outro. // `cells` can be an HTML string of <td>'s or a jQuery <tr> element // `row` is an optional row number. bookendCells: function(cells, rowType, row) { var intro = this.getHtmlRenderer('intro', rowType)(row || 0); var outro = this.getHtmlRenderer('outro', rowType)(row || 0); var prependHtml = this.isRTL ? outro : intro; var appendHtml = this.isRTL ? intro : outro; if (typeof cells === 'string') { return prependHtml + cells + appendHtml; } else { // a jQuery <tr> element return cells.prepend(prependHtml).append(appendHtml); } }, // Returns an HTML-rendering function given a specific `rendererName` (like cell, intro, or outro) and a specific // `rowType` (like day, eventSkeleton, helperSkeleton), which is optional. // If a renderer for the specific rowType doesn't exist, it will fall back to a generic renderer. // We will query the View object first for any custom rendering functions, then the methods of the subclass. getHtmlRenderer: function(rendererName, rowType) { var view = this.view; var generalName; // like "cellHtml" var specificName; // like "dayCellHtml". based on rowType var provider; // either the View or the RowRenderer subclass, whichever provided the method var renderer; generalName = rendererName + 'Html'; if (rowType) { specificName = rowType + capitaliseFirstLetter(rendererName) + 'Html'; } if (specificName && (renderer = view[specificName])) { provider = view; } else if (specificName && (renderer = this[specificName])) { provider = this; } else if ((renderer = view[generalName])) { provider = view; } else if ((renderer = this[generalName])) { provider = this; } if (typeof renderer === 'function') { return function() { return renderer.apply(provider, arguments) || ''; // use correct `this` and always return a string }; } // the rendered can be a plain string as well. if not specified, always an empty string. return function() { return renderer || ''; }; } }); ;; /* An abstract class comprised of a "grid" of cells that each represent a specific datetime ----------------------------------------------------------------------------------------------------------------------*/ var Grid = fc.Grid = RowRenderer.extend({ start: null, // the date of the first cell end: null, // the date after the last cell rowCnt: 0, // number of rows colCnt: 0, // number of cols rowData: null, // array of objects, holding misc data for each row colData: null, // array of objects, holding misc data for each column el: null, // the containing element coordMap: null, // a GridCoordMap that converts pixel values to datetimes elsByFill: null, // a hash of jQuery element sets used for rendering each fill. Keyed by fill name. externalDragStartProxy: null, // binds the Grid's scope to externalDragStart (in DayGrid.events) // derived from options colHeadFormat: null, // TODO: move to another class. not applicable to all Grids eventTimeFormat: null, displayEventTime: null, displayEventEnd: null, // if all cells are the same length of time, the duration they all share. optional. // when defined, allows the computeCellRange shortcut, as well as improved resizing behavior. cellDuration: null, // if defined, holds the unit identified (ex: "year" or "month") that determines the level of granularity // of the date cells. if not defined, assumes to be day and time granularity. largeUnit: null, constructor: function() { RowRenderer.apply(this, arguments); // call the super-constructor this.coordMap = new GridCoordMap(this); this.elsByFill = {}; this.externalDragStartProxy = proxy(this, 'externalDragStart'); }, /* Options ------------------------------------------------------------------------------------------------------------------*/ // Generates the format string used for the text in column headers, if not explicitly defined by 'columnFormat' // TODO: move to another class. not applicable to all Grids computeColHeadFormat: function() { // subclasses must implement if they want to use headHtml() }, // Generates the format string used for event time text, if not explicitly defined by 'timeFormat' computeEventTimeFormat: function() { return this.view.opt('smallTimeFormat'); }, // Determines whether events should have their end times displayed, if not explicitly defined by 'displayEventTime'. // Only applies to non-all-day events. computeDisplayEventTime: function() { return true; }, // Determines whether events should have their end times displayed, if not explicitly defined by 'displayEventEnd' computeDisplayEventEnd: function() { return true; }, /* Dates ------------------------------------------------------------------------------------------------------------------*/ // Tells the grid about what period of time to display. Grid will subsequently compute dates for cell system. setRange: function(range) { var view = this.view; var displayEventTime; var displayEventEnd; this.start = range.start.clone(); this.end = range.end.clone(); this.rowData = []; this.colData = []; this.updateCells(); // Populate option-derived settings. Look for override first, then compute if necessary. this.colHeadFormat = view.opt('columnFormat') || this.computeColHeadFormat(); this.eventTimeFormat = view.opt('eventTimeFormat') || view.opt('timeFormat') || // deprecated this.computeEventTimeFormat(); displayEventTime = view.opt('displayEventTime'); if (displayEventTime == null) { displayEventTime = this.computeDisplayEventTime(); // might be based off of range } displayEventEnd = view.opt('displayEventEnd'); if (displayEventEnd == null) { displayEventEnd = this.computeDisplayEventEnd(); // might be based off of range } this.displayEventTime = displayEventTime; this.displayEventEnd = displayEventEnd; }, // Responsible for setting rowCnt/colCnt and any other row/col data updateCells: function() { // subclasses must implement }, // Converts a range with an inclusive `start` and an exclusive `end` into an array of segment objects rangeToSegs: function(range) { // subclasses must implement }, // Diffs the two dates, returning a duration, based on granularity of the grid diffDates: function(a, b) { if (this.largeUnit) { return diffByUnit(a, b, this.largeUnit); } else { return diffDayTime(a, b); } }, /* Cells ------------------------------------------------------------------------------------------------------------------*/ // NOTE: columns are ordered left-to-right // Gets an object containing row/col number, misc data, and range information about the cell. // Accepts row/col values, an object with row/col properties, or a single-number offset from the first cell. getCell: function(row, col) { var cell; if (col == null) { if (typeof row === 'number') { // a single-number offset col = row % this.colCnt; row = Math.floor(row / this.colCnt); } else { // an object with row/col properties col = row.col; row = row.row; } } cell = { row: row, col: col }; $.extend(cell, this.getRowData(row), this.getColData(col)); $.extend(cell, this.computeCellRange(cell)); return cell; }, // Given a cell object with index and misc data, generates a range object // If the grid is leveraging cellDuration, this doesn't need to be defined. Only computeCellDate does. // If being overridden, should return a range with reference-free date copies. computeCellRange: function(cell) { var date = this.computeCellDate(cell); return { start: date, end: date.clone().add(this.cellDuration) }; }, // Given a cell, returns its start date. Should return a reference-free date copy. computeCellDate: function(cell) { // subclasses can implement }, // Retrieves misc data about the given row getRowData: function(row) { return this.rowData[row] || {}; }, // Retrieves misc data baout the given column getColData: function(col) { return this.colData[col] || {}; }, // Retrieves the element representing the given row getRowEl: function(row) { // subclasses should implement if leveraging the default getCellDayEl() or computeRowCoords() }, // Retrieves the element representing the given column getColEl: function(col) { // subclasses should implement if leveraging the default getCellDayEl() or computeColCoords() }, // Given a cell object, returns the element that represents the cell's whole-day getCellDayEl: function(cell) { return this.getColEl(cell.col) || this.getRowEl(cell.row); }, /* Cell Coordinates ------------------------------------------------------------------------------------------------------------------*/ // Computes the top/bottom coordinates of all rows. // By default, queries the dimensions of the element provided by getRowEl(). computeRowCoords: function() { var items = []; var i, el; var top; for (i = 0; i < this.rowCnt; i++) { el = this.getRowEl(i); top = el.offset().top; items.push({ top: top, bottom: top + el.outerHeight() }); } return items; }, // Computes the left/right coordinates of all rows. // By default, queries the dimensions of the element provided by getColEl(). Columns can be LTR or RTL. computeColCoords: function() { var items = []; var i, el; var left; for (i = 0; i < this.colCnt; i++) { el = this.getColEl(i); left = el.offset().left; items.push({ left: left, right: left + el.outerWidth() }); } return items; }, /* Rendering ------------------------------------------------------------------------------------------------------------------*/ // Sets the container element that the grid should render inside of. // Does other DOM-related initializations. setElement: function(el) { var _this = this; this.el = el; // attach a handler to the grid's root element. // jQuery will take care of unregistering them when removeElement gets called. el.on('mousedown', function(ev) { if ( !$(ev.target).is('.fc-event-container *, .fc-more') && // not an an event element, or "more.." link !$(ev.target).closest('.fc-popover').length // not on a popover (like the "more.." events one) ) { _this.dayMousedown(ev); } }); // attach event-element-related handlers. in Grid.events // same garbage collection note as above. this.bindSegHandlers(); this.bindGlobalHandlers(); }, // Removes the grid's container element from the DOM. Undoes any other DOM-related attachments. // DOES NOT remove any content before hand (doens't clear events or call destroyDates), unlike View removeElement: function() { this.unbindGlobalHandlers(); this.el.remove(); // NOTE: we don't null-out this.el for the same reasons we don't do it within View::removeElement }, // Renders the basic structure of grid view before any content is rendered renderSkeleton: function() { // subclasses should implement }, // Renders the grid's date-related content (like cells that represent days/times). // Assumes setRange has already been called and the skeleton has already been rendered. renderDates: function() { // subclasses should implement }, // Unrenders the grid's date-related content destroyDates: function() { // subclasses should implement }, /* Handlers ------------------------------------------------------------------------------------------------------------------*/ // Binds DOM handlers to elements that reside outside the grid, such as the document bindGlobalHandlers: function() { $(document).on('dragstart sortstart', this.externalDragStartProxy); // jqui }, // Unbinds DOM handlers from elements that reside outside the grid unbindGlobalHandlers: function() { $(document).off('dragstart sortstart', this.externalDragStartProxy); // jqui }, // Process a mousedown on an element that represents a day. For day clicking and selecting. dayMousedown: function(ev) { var _this = this; var view = this.view; var isSelectable = view.opt('selectable'); var dayClickCell; // null if invalid dayClick var selectionRange; // null if invalid selection // this listener tracks a mousedown on a day element, and a subsequent drag. // if the drag ends on the same day, it is a 'dayClick'. // if 'selectable' is enabled, this listener also detects selections. var dragListener = new CellDragListener(this.coordMap, { //distance: 5, // needs more work if we want dayClick to fire correctly scroll: view.opt('dragScroll'), dragStart: function() { view.unselect(); // since we could be rendering a new selection, we want to clear any old one }, cellOver: function(cell, isOrig, origCell) { if (origCell) { // click needs to have started on a cell dayClickCell = isOrig ? cell : null; // single-cell selection is a day click if (isSelectable) { selectionRange = _this.computeSelection(origCell, cell); if (selectionRange) { _this.renderSelection(selectionRange); } else { disableCursor(); } } } }, cellOut: function(cell) { dayClickCell = null; selectionRange = null; _this.destroySelection(); enableCursor(); }, listenStop: function(ev) { if (dayClickCell) { view.trigger('dayClick', _this.getCellDayEl(dayClickCell), dayClickCell.start, ev); } if (selectionRange) { // the selection will already have been rendered. just report it view.reportSelection(selectionRange, ev); } enableCursor(); } }); dragListener.mousedown(ev); // start listening, which will eventually initiate a dragStart }, /* Event Helper ------------------------------------------------------------------------------------------------------------------*/ // TODO: should probably move this to Grid.events, like we did event dragging / resizing // Renders a mock event over the given range renderRangeHelper: function(range, sourceSeg) { var fakeEvent = this.fabricateHelperEvent(range, sourceSeg); this.renderHelper(fakeEvent, sourceSeg); // do the actual rendering }, // Builds a fake event given a date range it should cover, and a segment is should be inspired from. // The range's end can be null, in which case the mock event that is rendered will have a null end time. // `sourceSeg` is the internal segment object involved in the drag. If null, something external is dragging. fabricateHelperEvent: function(range, sourceSeg) { var fakeEvent = sourceSeg ? createObject(sourceSeg.event) : {}; // mask the original event object if possible fakeEvent.start = range.start.clone(); fakeEvent.end = range.end ? range.end.clone() : null; fakeEvent.allDay = null; // force it to be freshly computed by normalizeEventRange this.view.calendar.normalizeEventRange(fakeEvent); // this extra className will be useful for differentiating real events from mock events in CSS fakeEvent.className = (fakeEvent.className || []).concat('fc-helper'); // if something external is being dragged in, don't render a resizer if (!sourceSeg) { fakeEvent.editable = false; } return fakeEvent; }, // Renders a mock event renderHelper: function(event, sourceSeg) { // subclasses must implement }, // Unrenders a mock event destroyHelper: function() { // subclasses must implement }, /* Selection ------------------------------------------------------------------------------------------------------------------*/ // Renders a visual indication of a selection. Will highlight by default but can be overridden by subclasses. renderSelection: function(range) { this.renderHighlight(range); }, // Unrenders any visual indications of a selection. Will unrender a highlight by default. destroySelection: function() { this.destroyHighlight(); }, // Given the first and last cells of a selection, returns a range object. // Will return something falsy if the selection is invalid (when outside of selectionConstraint for example). // Subclasses can override and provide additional data in the range object. Will be passed to renderSelection(). computeSelection: function(firstCell, lastCell) { var dates = [ firstCell.start, firstCell.end, lastCell.start, lastCell.end ]; var range; dates.sort(compareNumbers); // sorts chronologically. works with Moments range = { start: dates[0].clone(), end: dates[3].clone() }; if (!this.view.calendar.isSelectionRangeAllowed(range)) { return null; } return range; }, /* Highlight ------------------------------------------------------------------------------------------------------------------*/ // Renders an emphasis on the given date range. `start` is inclusive. `end` is exclusive. renderHighlight: function(range) { this.renderFill('highlight', this.rangeToSegs(range)); }, // Unrenders the emphasis on a date range destroyHighlight: function() { this.destroyFill('highlight'); }, // Generates an array of classNames for rendering the highlight. Used by the fill system. highlightSegClasses: function() { return [ 'fc-highlight' ]; }, /* Fill System (highlight, background events, business hours) ------------------------------------------------------------------------------------------------------------------*/ // Renders a set of rectangles over the given segments of time. // Returns a subset of segs, the segs that were actually rendered. // Responsible for populating this.elsByFill. TODO: better API for expressing this requirement renderFill: function(type, segs) { // subclasses must implement }, // Unrenders a specific type of fill that is currently rendered on the grid destroyFill: function(type) { var el = this.elsByFill[type]; if (el) { el.remove(); delete this.elsByFill[type]; } }, // Renders and assigns an `el` property for each fill segment. Generic enough to work with different types. // Only returns segments that successfully rendered. // To be harnessed by renderFill (implemented by subclasses). // Analagous to renderFgSegEls. renderFillSegEls: function(type, segs) { var _this = this; var segElMethod = this[type + 'SegEl']; var html = ''; var renderedSegs = []; var i; if (segs.length) { // build a large concatenation of segment HTML for (i = 0; i < segs.length; i++) { html += this.fillSegHtml(type, segs[i]); } // Grab individual elements from the combined HTML string. Use each as the default rendering. // Then, compute the 'el' for each segment. $(html).each(function(i, node) { var seg = segs[i]; var el = $(node); // allow custom filter methods per-type if (segElMethod) { el = segElMethod.call(_this, seg, el); } if (el) { // custom filters did not cancel the render el = $(el); // allow custom filter to return raw DOM node // correct element type? (would be bad if a non-TD were inserted into a table for example) if (el.is(_this.fillSegTag)) { seg.el = el; renderedSegs.push(seg); } } }); } return renderedSegs; }, fillSegTag: 'div', // subclasses can override // Builds the HTML needed for one fill segment. Generic enought o work with different types. fillSegHtml: function(type, seg) { // custom hooks per-type var classesMethod = this[type + 'SegClasses']; var cssMethod = this[type + 'SegCss']; var classes = classesMethod ? classesMethod.call(this, seg) : []; var css = cssToStr(cssMethod ? cssMethod.call(this, seg) : {}); return '<' + this.fillSegTag + (classes.length ? ' class="' + classes.join(' ') + '"' : '') + (css ? ' style="' + css + '"' : '') + ' />'; }, /* Generic rendering utilities for subclasses ------------------------------------------------------------------------------------------------------------------*/ // Renders a day-of-week header row. // TODO: move to another class. not applicable to all Grids headHtml: function() { return '' + '<div class="fc-row ' + this.view.widgetHeaderClass + '">' + '<table>' + '<thead>' + this.rowHtml('head') + // leverages RowRenderer '</thead>' + '</table>' + '</div>'; }, // Used by the `headHtml` method, via RowRenderer, for rendering the HTML of a day-of-week header cell // TODO: move to another class. not applicable to all Grids headCellHtml: function(cell) { var view = this.view; var date = cell.start; return '' + '<th class="fc-day-header ' + view.widgetHeaderClass + ' fc-' + dayIDs[date.day()] + '">' + htmlEscape(date.format(this.colHeadFormat)) + '</th>'; }, // Renders the HTML for a single-day background cell bgCellHtml: function(cell) { var view = this.view; var date = cell.start; var classes = this.getDayClasses(date); classes.unshift('fc-day', view.widgetContentClass); return '<td class="' + classes.join(' ') + '"' + ' data-date="' + date.format('YYYY-MM-DD') + '"' + // if date has a time, won't format it '></td>'; }, // Computes HTML classNames for a single-day cell getDayClasses: function(date) { var view = this.view; var today = view.calendar.getNow().stripTime(); var classes = [ 'fc-' + dayIDs[date.day()] ]; if ( view.intervalDuration.as('months') == 1 && date.month() != view.intervalStart.month() ) { classes.push('fc-other-month'); } if (date.isSame(today, 'day')) { classes.push( 'fc-today', view.highlightStateClass ); } else if (date < today) { classes.push('fc-past'); } else { classes.push('fc-future'); } return classes; } }); ;; /* Event-rendering and event-interaction methods for the abstract Grid class ----------------------------------------------------------------------------------------------------------------------*/ Grid.mixin({ mousedOverSeg: null, // the segment object the user's mouse is over. null if over nothing isDraggingSeg: false, // is a segment being dragged? boolean isResizingSeg: false, // is a segment being resized? boolean isDraggingExternal: false, // jqui-dragging an external element? boolean segs: null, // the event segments currently rendered in the grid // Renders the given events onto the grid renderEvents: function(events) { var segs = this.eventsToSegs(events); var bgSegs = []; var fgSegs = []; var i, seg; for (i = 0; i < segs.length; i++) { seg = segs[i]; if (isBgEvent(seg.event)) { bgSegs.push(seg); } else { fgSegs.push(seg); } } // Render each different type of segment. // Each function may return a subset of the segs, segs that were actually rendered. bgSegs = this.renderBgSegs(bgSegs) || bgSegs; fgSegs = this.renderFgSegs(fgSegs) || fgSegs; this.segs = bgSegs.concat(fgSegs); }, // Unrenders all events currently rendered on the grid destroyEvents: function() { this.triggerSegMouseout(); // trigger an eventMouseout if user's mouse is over an event this.destroyFgSegs(); this.destroyBgSegs(); this.segs = null; }, // Retrieves all rendered segment objects currently rendered on the grid getEventSegs: function() { return this.segs || []; }, /* Foreground Segment Rendering ------------------------------------------------------------------------------------------------------------------*/ // Renders foreground event segments onto the grid. May return a subset of segs that were rendered. renderFgSegs: function(segs) { // subclasses must implement }, // Unrenders all currently rendered foreground segments destroyFgSegs: function() { // subclasses must implement }, // Renders and assigns an `el` property for each foreground event segment. // Only returns segments that successfully rendered. // A utility that subclasses may use. renderFgSegEls: function(segs, disableResizing) { var view = this.view; var html = ''; var renderedSegs = []; var i; if (segs.length) { // don't build an empty html string // build a large concatenation of event segment HTML for (i = 0; i < segs.length; i++) { html += this.fgSegHtml(segs[i], disableResizing); } // Grab individual elements from the combined HTML string. Use each as the default rendering. // Then, compute the 'el' for each segment. An el might be null if the eventRender callback returned false. $(html).each(function(i, node) { var seg = segs[i]; var el = view.resolveEventEl(seg.event, $(node)); if (el) { el.data('fc-seg', seg); // used by handlers seg.el = el; renderedSegs.push(seg); } }); } return renderedSegs; }, // Generates the HTML for the default rendering of a foreground event segment. Used by renderFgSegEls() fgSegHtml: function(seg, disableResizing) { // subclasses should implement }, /* Background Segment Rendering ------------------------------------------------------------------------------------------------------------------*/ // Renders the given background event segments onto the grid. // Returns a subset of the segs that were actually rendered. renderBgSegs: function(segs) { return this.renderFill('bgEvent', segs); }, // Unrenders all the currently rendered background event segments destroyBgSegs: function() { this.destroyFill('bgEvent'); }, // Renders a background event element, given the default rendering. Called by the fill system. bgEventSegEl: function(seg, el) { return this.view.resolveEventEl(seg.event, el); // will filter through eventRender }, // Generates an array of classNames to be used for the default rendering of a background event. // Called by the fill system. bgEventSegClasses: function(seg) { var event = seg.event; var source = event.source || {}; return [ 'fc-bgevent' ].concat( event.className, source.className || [] ); }, // Generates a semicolon-separated CSS string to be used for the default rendering of a background event. // Called by the fill system. // TODO: consolidate with getEventSkinCss? bgEventSegCss: function(seg) { var view = this.view; var event = seg.event; var source = event.source || {}; return { 'background-color': event.backgroundColor || event.color || source.backgroundColor || source.color || view.opt('eventBackgroundColor') || view.opt('eventColor') }; }, // Generates an array of classNames to be used for the rendering business hours overlay. Called by the fill system. businessHoursSegClasses: function(seg) { return [ 'fc-nonbusiness', 'fc-bgevent' ]; }, /* Handlers ------------------------------------------------------------------------------------------------------------------*/ // Attaches event-element-related handlers to the container element and leverage bubbling bindSegHandlers: function() { var _this = this; var view = this.view; $.each( { mouseenter: function(seg, ev) { _this.triggerSegMouseover(seg, ev); }, mouseleave: function(seg, ev) { _this.triggerSegMouseout(seg, ev); }, click: function(seg, ev) { return view.trigger('eventClick', this, seg.event, ev); // can return `false` to cancel }, mousedown: function(seg, ev) { if ($(ev.target).is('.fc-resizer') && view.isEventResizable(seg.event)) { _this.segResizeMousedown(seg, ev, $(ev.target).is('.fc-start-resizer')); } else if (view.isEventDraggable(seg.event)) { _this.segDragMousedown(seg, ev); } } }, function(name, func) { // attach the handler to the container element and only listen for real event elements via bubbling _this.el.on(name, '.fc-event-container > *', function(ev) { var seg = $(this).data('fc-seg'); // grab segment data. put there by View::renderEvents // only call the handlers if there is not a drag/resize in progress if (seg && !_this.isDraggingSeg && !_this.isResizingSeg) { return func.call(this, seg, ev); // `this` will be the event element } }); } ); }, // Updates internal state and triggers handlers for when an event element is moused over triggerSegMouseover: function(seg, ev) { if (!this.mousedOverSeg) { this.mousedOverSeg = seg; this.view.trigger('eventMouseover', seg.el[0], seg.event, ev); } }, // Updates internal state and triggers handlers for when an event element is moused out. // Can be given no arguments, in which case it will mouseout the segment that was previously moused over. triggerSegMouseout: function(seg, ev) { ev = ev || {}; // if given no args, make a mock mouse event if (this.mousedOverSeg) { seg = seg || this.mousedOverSeg; // if given no args, use the currently moused-over segment this.mousedOverSeg = null; this.view.trigger('eventMouseout', seg.el[0], seg.event, ev); } }, /* Event Dragging ------------------------------------------------------------------------------------------------------------------*/ // Called when the user does a mousedown on an event, which might lead to dragging. // Generic enough to work with any type of Grid. segDragMousedown: function(seg, ev) { var _this = this; var view = this.view; var calendar = view.calendar; var el = seg.el; var event = seg.event; var dropLocation; // A clone of the original element that will move with the mouse var mouseFollower = new MouseFollower(seg.el, { parentEl: view.el, opacity: view.opt('dragOpacity'), revertDuration: view.opt('dragRevertDuration'), zIndex: 2 // one above the .fc-view }); // Tracks mouse movement over the *view's* coordinate map. Allows dragging and dropping between subcomponents // of the view. var dragListener = new CellDragListener(view.coordMap, { distance: 5, scroll: view.opt('dragScroll'), subjectEl: el, subjectCenter: true, listenStart: function(ev) { mouseFollower.hide(); // don't show until we know this is a real drag mouseFollower.start(ev); }, dragStart: function(ev) { _this.triggerSegMouseout(seg, ev); // ensure a mouseout on the manipulated event has been reported _this.segDragStart(seg, ev); view.hideEvent(event); // hide all event segments. our mouseFollower will take over }, cellOver: function(cell, isOrig, origCell) { // starting cell could be forced (DayGrid.limit) if (seg.cell) { origCell = seg.cell; } dropLocation = _this.computeEventDrop(origCell, cell, event); if (dropLocation && !calendar.isEventRangeAllowed(dropLocation, event)) { disableCursor(); dropLocation = null; } // if a valid drop location, have the subclass render a visual indication if (dropLocation && view.renderDrag(dropLocation, seg)) { mouseFollower.hide(); // if the subclass is already using a mock event "helper", hide our own } else { mouseFollower.show(); // otherwise, have the helper follow the mouse (no snapping) } if (isOrig) { dropLocation = null; // needs to have moved cells to be a valid drop } }, cellOut: function() { // called before mouse moves to a different cell OR moved out of all cells view.destroyDrag(); // unrender whatever was done in renderDrag mouseFollower.show(); // show in case we are moving out of all cells dropLocation = null; }, cellDone: function() { // Called after a cellOut OR before a dragStop enableCursor(); }, dragStop: function(ev) { // do revert animation if hasn't changed. calls a callback when finished (whether animation or not) mouseFollower.stop(!dropLocation, function() { view.destroyDrag(); view.showEvent(event); _this.segDragStop(seg, ev); if (dropLocation) { view.reportEventDrop(event, dropLocation, this.largeUnit, el, ev); } }); }, listenStop: function() { mouseFollower.stop(); // put in listenStop in case there was a mousedown but the drag never started } }); dragListener.mousedown(ev); // start listening, which will eventually lead to a dragStart }, // Called before event segment dragging starts segDragStart: function(seg, ev) { this.isDraggingSeg = true; this.view.trigger('eventDragStart', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy }, // Called after event segment dragging stops segDragStop: function(seg, ev) { this.isDraggingSeg = false; this.view.trigger('eventDragStop', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy }, // Given the cell an event drag began, and the cell event was dropped, calculates the new start/end/allDay // values for the event. Subclasses may override and set additional properties to be used by renderDrag. // A falsy returned value indicates an invalid drop. computeEventDrop: function(startCell, endCell, event) { var calendar = this.view.calendar; var dragStart = startCell.start; var dragEnd = endCell.start; var delta; var dropLocation; if (dragStart.hasTime() === dragEnd.hasTime()) { delta = this.diffDates(dragEnd, dragStart); // if an all-day event was in a timed area and it was dragged to a different time, // guarantee an end and adjust start/end to have times if (event.allDay && durationHasTime(delta)) { dropLocation = { start: event.start.clone(), end: calendar.getEventEnd(event), // will be an ambig day allDay: false // for normalizeEventRangeTimes }; calendar.normalizeEventRangeTimes(dropLocation); } // othewise, work off existing values else { dropLocation = { start: event.start.clone(), end: event.end ? event.end.clone() : null, allDay: event.allDay // keep it the same }; } dropLocation.start.add(delta); if (dropLocation.end) { dropLocation.end.add(delta); } } else { // if switching from day <-> timed, start should be reset to the dropped date, and the end cleared dropLocation = { start: dragEnd.clone(), end: null, // end should be cleared allDay: !dragEnd.hasTime() }; } return dropLocation; }, // Utility for apply dragOpacity to a jQuery set applyDragOpacity: function(els) { var opacity = this.view.opt('dragOpacity'); if (opacity != null) { els.each(function(i, node) { // Don't use jQuery (will set an IE filter), do it the old fashioned way. // In IE8, a helper element will disappears if there's a filter. node.style.opacity = opacity; }); } }, /* External Element Dragging ------------------------------------------------------------------------------------------------------------------*/ // Called when a jQuery UI drag is initiated anywhere in the DOM externalDragStart: function(ev, ui) { var view = this.view; var el; var accept; if (view.opt('droppable')) { // only listen if this setting is on el = $((ui ? ui.item : null) || ev.target); // Test that the dragged element passes the dropAccept selector or filter function. // FYI, the default is "*" (matches all) accept = view.opt('dropAccept'); if ($.isFunction(accept) ? accept.call(el[0], el) : el.is(accept)) { if (!this.isDraggingExternal) { // prevent double-listening if fired twice this.listenToExternalDrag(el, ev, ui); } } } }, // Called when a jQuery UI drag starts and it needs to be monitored for cell dropping listenToExternalDrag: function(el, ev, ui) { var _this = this; var meta = getDraggedElMeta(el); // extra data about event drop, including possible event to create var dragListener; var dropLocation; // a null value signals an unsuccessful drag // listener that tracks mouse movement over date-associated pixel regions dragListener = new CellDragListener(this.coordMap, { listenStart: function() { _this.isDraggingExternal = true; }, cellOver: function(cell) { dropLocation = _this.computeExternalDrop(cell, meta); if (dropLocation) { _this.renderDrag(dropLocation); // called without a seg parameter } else { // invalid drop cell disableCursor(); } }, cellOut: function() { dropLocation = null; // signal unsuccessful _this.destroyDrag(); enableCursor(); }, dragStop: function() { _this.destroyDrag(); enableCursor(); if (dropLocation) { // element was dropped on a valid date/time cell _this.view.reportExternalDrop(meta, dropLocation, el, ev, ui); } }, listenStop: function() { _this.isDraggingExternal = false; } }); dragListener.startDrag(ev); // start listening immediately }, // Given a cell to be dropped upon, and misc data associated with the jqui drag (guaranteed to be a plain object), // returns start/end dates for the event that would result from the hypothetical drop. end might be null. // Returning a null value signals an invalid drop cell. computeExternalDrop: function(cell, meta) { var dropLocation = { start: cell.start.clone(), end: null }; // if dropped on an all-day cell, and element's metadata specified a time, set it if (meta.startTime && !dropLocation.start.hasTime()) { dropLocation.start.time(meta.startTime); } if (meta.duration) { dropLocation.end = dropLocation.start.clone().add(meta.duration); } if (!this.view.calendar.isExternalDropRangeAllowed(dropLocation, meta.eventProps)) { return null; } return dropLocation; }, /* Drag Rendering (for both events and an external elements) ------------------------------------------------------------------------------------------------------------------*/ // Renders a visual indication of an event or external element being dragged. // `dropLocation` contains hypothetical start/end/allDay values the event would have if dropped. end can be null. // `seg` is the internal segment object that is being dragged. If dragging an external element, `seg` is null. // A truthy returned value indicates this method has rendered a helper element. renderDrag: function(dropLocation, seg) { // subclasses must implement }, // Unrenders a visual indication of an event or external element being dragged destroyDrag: function() { // subclasses must implement }, /* Resizing ------------------------------------------------------------------------------------------------------------------*/ // Called when the user does a mousedown on an event's resizer, which might lead to resizing. // Generic enough to work with any type of Grid. segResizeMousedown: function(seg, ev, isStart) { var _this = this; var view = this.view; var calendar = view.calendar; var el = seg.el; var event = seg.event; var eventEnd = calendar.getEventEnd(event); var dragListener; var resizeLocation; // falsy if invalid resize // Tracks mouse movement over the *grid's* coordinate map dragListener = new CellDragListener(this.coordMap, { distance: 5, scroll: view.opt('dragScroll'), subjectEl: el, dragStart: function(ev) { _this.triggerSegMouseout(seg, ev); // ensure a mouseout on the manipulated event has been reported _this.segResizeStart(seg, ev); }, cellOver: function(cell, isOrig, origCell) { resizeLocation = isStart ? _this.computeEventStartResize(origCell, cell, event) : _this.computeEventEndResize(origCell, cell, event); if (resizeLocation) { if (!calendar.isEventRangeAllowed(resizeLocation, event)) { disableCursor(); resizeLocation = null; } // no change? (TODO: how does this work with timezones?) else if (resizeLocation.start.isSame(event.start) && resizeLocation.end.isSame(eventEnd)) { resizeLocation = null; } } if (resizeLocation) { view.hideEvent(event); _this.renderEventResize(resizeLocation, seg); } }, cellOut: function() { // called before mouse moves to a different cell OR moved out of all cells resizeLocation = null; }, cellDone: function() { // resets the rendering to show the original event _this.destroyEventResize(); view.showEvent(event); enableCursor(); }, dragStop: function(ev) { _this.segResizeStop(seg, ev); if (resizeLocation) { // valid date to resize to? view.reportEventResize(event, resizeLocation, this.largeUnit, el, ev); } } }); dragListener.mousedown(ev); // start listening, which will eventually lead to a dragStart }, // Called before event segment resizing starts segResizeStart: function(seg, ev) { this.isResizingSeg = true; this.view.trigger('eventResizeStart', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy }, // Called after event segment resizing stops segResizeStop: function(seg, ev) { this.isResizingSeg = false; this.view.trigger('eventResizeStop', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy }, // Returns new date-information for an event segment being resized from its start computeEventStartResize: function(startCell, endCell, event) { return this.computeEventResize('start', startCell, endCell, event); }, // Returns new date-information for an event segment being resized from its end computeEventEndResize: function(startCell, endCell, event) { return this.computeEventResize('end', startCell, endCell, event); }, // Returns new date-information for an event segment being resized from its start OR end // `type` is either 'start' or 'end' computeEventResize: function(type, startCell, endCell, event) { var calendar = this.view.calendar; var delta = this.diffDates(endCell[type], startCell[type]); var range; var defaultDuration; // build original values to work from, guaranteeing a start and end range = { start: event.start.clone(), end: calendar.getEventEnd(event), allDay: event.allDay }; // if an all-day event was in a timed area and was resized to a time, adjust start/end to have times if (range.allDay && durationHasTime(delta)) { range.allDay = false; calendar.normalizeEventRangeTimes(range); } range[type].add(delta); // apply delta to start or end // if the event was compressed too small, find a new reasonable duration for it if (!range.start.isBefore(range.end)) { defaultDuration = event.allDay ? calendar.defaultAllDayEventDuration : calendar.defaultTimedEventDuration; // between the cell's duration and the event's default duration, use the smaller of the two. // example: if year-length slots, and compressed to one slot, we don't want the event to be a year long if (this.cellDuration && this.cellDuration < defaultDuration) { defaultDuration = this.cellDuration; } if (type == 'start') { // resizing the start? range.start = range.end.clone().subtract(defaultDuration); } else { // resizing the end? range.end = range.start.clone().add(defaultDuration); } } return range; }, // Renders a visual indication of an event being resized. // `range` has the updated dates of the event. `seg` is the original segment object involved in the drag. renderEventResize: function(range, seg) { // subclasses must implement }, // Unrenders a visual indication of an event being resized. destroyEventResize: function() { // subclasses must implement }, /* Rendering Utils ------------------------------------------------------------------------------------------------------------------*/ // Compute the text that should be displayed on an event's element. // `range` can be the Event object itself, or something range-like, with at least a `start`. // If event times are disabled, or the event has no time, will return a blank string. // If not specified, formatStr will default to the eventTimeFormat setting, // and displayEnd will default to the displayEventEnd setting. getEventTimeText: function(range, formatStr, displayEnd) { if (formatStr == null) { formatStr = this.eventTimeFormat; } if (displayEnd == null) { displayEnd = this.displayEventEnd; } if (this.displayEventTime && range.start.hasTime()) { if (displayEnd && range.end) { return this.view.formatRange(range, formatStr); } else { return range.start.format(formatStr); } } return ''; }, // Generic utility for generating the HTML classNames for an event segment's element getSegClasses: function(seg, isDraggable, isResizable) { var event = seg.event; var classes = [ 'fc-event', seg.isStart ? 'fc-start' : 'fc-not-start', seg.isEnd ? 'fc-end' : 'fc-not-end' ].concat( event.className, event.source ? event.source.className : [] ); if (isDraggable) { classes.push('fc-draggable'); } if (isResizable) { classes.push('fc-resizable'); } return classes; }, // Utility for generating event skin-related CSS properties getEventSkinCss: function(event) { var view = this.view; var source = event.source || {}; var eventColor = event.color; var sourceColor = source.color; var optionColor = view.opt('eventColor'); return { 'background-color': event.backgroundColor || eventColor || source.backgroundColor || sourceColor || view.opt('eventBackgroundColor') || optionColor, 'border-color': event.borderColor || eventColor || source.borderColor || sourceColor || view.opt('eventBorderColor') || optionColor, color: event.textColor || source.textColor || view.opt('eventTextColor') }; }, /* Converting events -> ranges -> segs ------------------------------------------------------------------------------------------------------------------*/ // Converts an array of event objects into an array of event segment objects. // A custom `rangeToSegsFunc` may be given for arbitrarily slicing up events. // Doesn't guarantee an order for the resulting array. eventsToSegs: function(events, rangeToSegsFunc) { var eventRanges = this.eventsToRanges(events); var segs = []; var i; for (i = 0; i < eventRanges.length; i++) { segs.push.apply( segs, this.eventRangeToSegs(eventRanges[i], rangeToSegsFunc) ); } return segs; }, // Converts an array of events into an array of "range" objects. // A "range" object is a plain object with start/end properties denoting the time it covers. Also an event property. // For "normal" events, this will be identical to the event's start/end, but for "inverse-background" events, // will create an array of ranges that span the time *not* covered by the given event. // Doesn't guarantee an order for the resulting array. eventsToRanges: function(events) { var _this = this; var eventsById = groupEventsById(events); var ranges = []; // group by ID so that related inverse-background events can be rendered together $.each(eventsById, function(id, eventGroup) { if (eventGroup.length) { ranges.push.apply( ranges, isInverseBgEvent(eventGroup[0]) ? _this.eventsToInverseRanges(eventGroup) : _this.eventsToNormalRanges(eventGroup) ); } }); return ranges; }, // Converts an array of "normal" events (not inverted rendering) into a parallel array of ranges eventsToNormalRanges: function(events) { var calendar = this.view.calendar; var ranges = []; var i, event; var eventStart, eventEnd; for (i = 0; i < events.length; i++) { event = events[i]; // make copies and normalize by stripping timezone eventStart = event.start.clone().stripZone(); eventEnd = calendar.getEventEnd(event).stripZone(); ranges.push({ event: event, start: eventStart, end: eventEnd, eventStartMS: +eventStart, eventDurationMS: eventEnd - eventStart }); } return ranges; }, // Converts an array of events, with inverse-background rendering, into an array of range objects. // The range objects will cover all the time NOT covered by the events. eventsToInverseRanges: function(events) { var view = this.view; var viewStart = view.start.clone().stripZone(); // normalize timezone var viewEnd = view.end.clone().stripZone(); // normalize timezone var normalRanges = this.eventsToNormalRanges(events); // will give us normalized dates we can use w/o copies var inverseRanges = []; var event0 = events[0]; // assign this to each range's `.event` var start = viewStart; // the end of the previous range. the start of the new range var i, normalRange; // ranges need to be in order. required for our date-walking algorithm normalRanges.sort(compareNormalRanges); for (i = 0; i < normalRanges.length; i++) { normalRange = normalRanges[i]; // add the span of time before the event (if there is any) if (normalRange.start > start) { // compare millisecond time (skip any ambig logic) inverseRanges.push({ event: event0, start: start, end: normalRange.start }); } start = normalRange.end; } // add the span of time after the last event (if there is any) if (start < viewEnd) { // compare millisecond time (skip any ambig logic) inverseRanges.push({ event: event0, start: start, end: viewEnd }); } return inverseRanges; }, // Slices the given event range into one or more segment objects. // A `rangeToSegsFunc` custom slicing function can be given. eventRangeToSegs: function(eventRange, rangeToSegsFunc) { var segs; var i, seg; if (rangeToSegsFunc) { segs = rangeToSegsFunc(eventRange); } else { segs = this.rangeToSegs(eventRange); // defined by the subclass } for (i = 0; i < segs.length; i++) { seg = segs[i]; seg.event = eventRange.event; seg.eventStartMS = eventRange.eventStartMS; seg.eventDurationMS = eventRange.eventDurationMS; } return segs; } }); /* Utilities ----------------------------------------------------------------------------------------------------------------------*/ function isBgEvent(event) { // returns true if background OR inverse-background var rendering = getEventRendering(event); return rendering === 'background' || rendering === 'inverse-background'; } function isInverseBgEvent(event) { return getEventRendering(event) === 'inverse-background'; } function getEventRendering(event) { return firstDefined((event.source || {}).rendering, event.rendering); } function groupEventsById(events) { var eventsById = {}; var i, event; for (i = 0; i < events.length; i++) { event = events[i]; (eventsById[event._id] || (eventsById[event._id] = [])).push(event); } return eventsById; } // A cmp function for determining which non-inverted "ranges" (see above) happen earlier function compareNormalRanges(range1, range2) { return range1.eventStartMS - range2.eventStartMS; // earlier ranges go first } // A cmp function for determining which segments should take visual priority // DOES NOT WORK ON INVERTED BACKGROUND EVENTS because they have no eventStartMS/eventDurationMS function compareSegs(seg1, seg2) { return seg1.eventStartMS - seg2.eventStartMS || // earlier events go first seg2.eventDurationMS - seg1.eventDurationMS || // tie? longer events go first seg2.event.allDay - seg1.event.allDay || // tie? put all-day events first (booleans cast to 0/1) (seg1.event.title || '').localeCompare(seg2.event.title); // tie? alphabetically by title } fc.compareSegs = compareSegs; // export /* External-Dragging-Element Data ----------------------------------------------------------------------------------------------------------------------*/ // Require all HTML5 data-* attributes used by FullCalendar to have this prefix. // A value of '' will query attributes like data-event. A value of 'fc' will query attributes like data-fc-event. fc.dataAttrPrefix = ''; // Given a jQuery element that might represent a dragged FullCalendar event, returns an intermediate data structure // to be used for Event Object creation. // A defined `.eventProps`, even when empty, indicates that an event should be created. function getDraggedElMeta(el) { var prefix = fc.dataAttrPrefix; var eventProps; // properties for creating the event, not related to date/time var startTime; // a Duration var duration; var stick; if (prefix) { prefix += '-'; } eventProps = el.data(prefix + 'event') || null; if (eventProps) { if (typeof eventProps === 'object') { eventProps = $.extend({}, eventProps); // make a copy } else { // something like 1 or true. still signal event creation eventProps = {}; } // pluck special-cased date/time properties startTime = eventProps.start; if (startTime == null) { startTime = eventProps.time; } // accept 'time' as well duration = eventProps.duration; stick = eventProps.stick; delete eventProps.start; delete eventProps.time; delete eventProps.duration; delete eventProps.stick; } // fallback to standalone attribute values for each of the date/time properties if (startTime == null) { startTime = el.data(prefix + 'start'); } if (startTime == null) { startTime = el.data(prefix + 'time'); } // accept 'time' as well if (duration == null) { duration = el.data(prefix + 'duration'); } if (stick == null) { stick = el.data(prefix + 'stick'); } // massage into correct data types startTime = startTime != null ? moment.duration(startTime) : null; duration = duration != null ? moment.duration(duration) : null; stick = Boolean(stick); return { eventProps: eventProps, startTime: startTime, duration: duration, stick: stick }; } ;; /* A component that renders a grid of whole-days that runs horizontally. There can be multiple rows, one per week. ----------------------------------------------------------------------------------------------------------------------*/ var DayGrid = Grid.extend({ numbersVisible: false, // should render a row for day/week numbers? set by outside view. TODO: make internal bottomCoordPadding: 0, // hack for extending the hit area for the last row of the coordinate grid breakOnWeeks: null, // should create a new row for each week? set by outside view cellDates: null, // flat chronological array of each cell's dates dayToCellOffsets: null, // maps days offsets from grid's start date, to cell offsets rowEls: null, // set of fake row elements dayEls: null, // set of whole-day elements comprising the row's background helperEls: null, // set of cell skeleton elements for rendering the mock event "helper" constructor: function() { Grid.apply(this, arguments); this.cellDuration = moment.duration(1, 'day'); // for Grid system }, // Renders the rows and columns into the component's `this.el`, which should already be assigned. // isRigid determins whether the individual rows should ignore the contents and be a constant height. // Relies on the view's colCnt and rowCnt. In the future, this component should probably be self-sufficient. renderDates: function(isRigid) { var view = this.view; var rowCnt = this.rowCnt; var colCnt = this.colCnt; var cellCnt = rowCnt * colCnt; var html = ''; var row; var i, cell; for (row = 0; row < rowCnt; row++) { html += this.dayRowHtml(row, isRigid); } this.el.html(html); this.rowEls = this.el.find('.fc-row'); this.dayEls = this.el.find('.fc-day'); // trigger dayRender with each cell's element for (i = 0; i < cellCnt; i++) { cell = this.getCell(i); view.trigger('dayRender', null, cell.start, this.dayEls.eq(i)); } }, destroyDates: function() { this.destroySegPopover(); }, renderBusinessHours: function() { var events = this.view.calendar.getBusinessHoursEvents(true); // wholeDay=true var segs = this.eventsToSegs(events); this.renderFill('businessHours', segs, 'bgevent'); }, // Generates the HTML for a single row. `row` is the row number. dayRowHtml: function(row, isRigid) { var view = this.view; var classes = [ 'fc-row', 'fc-week', view.widgetContentClass ]; if (isRigid) { classes.push('fc-rigid'); } return '' + '<div class="' + classes.join(' ') + '">' + '<div class="fc-bg">' + '<table>' + this.rowHtml('day', row) + // leverages RowRenderer. calls dayCellHtml() '</table>' + '</div>' + '<div class="fc-content-skeleton">' + '<table>' + (this.numbersVisible ? '<thead>' + this.rowHtml('number', row) + // leverages RowRenderer. View will define render method '</thead>' : '' ) + '</table>' + '</div>' + '</div>'; }, // Renders the HTML for a whole-day cell. Will eventually end up in the day-row's background. // We go through a 'day' row type instead of just doing a 'bg' row type so that the View can do custom rendering // specifically for whole-day rows, whereas a 'bg' might also be used for other purposes (TimeGrid bg for example). dayCellHtml: function(cell) { return this.bgCellHtml(cell); }, /* Options ------------------------------------------------------------------------------------------------------------------*/ // Computes a default column header formatting string if `colFormat` is not explicitly defined computeColHeadFormat: function() { if (this.rowCnt > 1) { // more than one week row. day numbers will be in each cell return 'ddd'; // "Sat" } else if (this.colCnt > 1) { // multiple days, so full single date string WON'T be in title text return this.view.opt('dayOfMonthFormat'); // "Sat 12/10" } else { // single day, so full single date string will probably be in title text return 'dddd'; // "Saturday" } }, // Computes a default event time formatting string if `timeFormat` is not explicitly defined computeEventTimeFormat: function() { return this.view.opt('extraSmallTimeFormat'); // like "6p" or "6:30p" }, // Computes a default `displayEventEnd` value if one is not expliclty defined computeDisplayEventEnd: function() { return this.colCnt == 1; // we'll likely have space if there's only one day }, /* Cell System ------------------------------------------------------------------------------------------------------------------*/ // Initializes row/col information updateCells: function() { var cellDates; var firstDay; var rowCnt; var colCnt; this.updateCellDates(); // populates cellDates and dayToCellOffsets cellDates = this.cellDates; if (this.breakOnWeeks) { // count columns until the day-of-week repeats firstDay = cellDates[0].day(); for (colCnt = 1; colCnt < cellDates.length; colCnt++) { if (cellDates[colCnt].day() == firstDay) { break; } } rowCnt = Math.ceil(cellDates.length / colCnt); } else { rowCnt = 1; colCnt = cellDates.length; } this.rowCnt = rowCnt; this.colCnt = colCnt; }, // Populates cellDates and dayToCellOffsets updateCellDates: function() { var view = this.view; var date = this.start.clone(); var dates = []; var offset = -1; var offsets = []; while (date.isBefore(this.end)) { // loop each day from start to end if (view.isHiddenDay(date)) { offsets.push(offset + 0.5); // mark that it's between offsets } else { offset++; offsets.push(offset); dates.push(date.clone()); } date.add(1, 'days'); } this.cellDates = dates; this.dayToCellOffsets = offsets; }, // Given a cell object, generates its start date. Returns a reference-free copy. computeCellDate: function(cell) { var colCnt = this.colCnt; var index = cell.row * colCnt + (this.isRTL ? colCnt - cell.col - 1 : cell.col); return this.cellDates[index].clone(); }, // Retrieves the element representing the given row getRowEl: function(row) { return this.rowEls.eq(row); }, // Retrieves the element representing the given column getColEl: function(col) { return this.dayEls.eq(col); }, // Gets the whole-day element associated with the cell getCellDayEl: function(cell) { return this.dayEls.eq(cell.row * this.colCnt + cell.col); }, // Overrides Grid's method for when row coordinates are computed computeRowCoords: function() { var rowCoords = Grid.prototype.computeRowCoords.call(this); // call the super-method // hack for extending last row (used by AgendaView) rowCoords[rowCoords.length - 1].bottom += this.bottomCoordPadding; return rowCoords; }, /* Dates ------------------------------------------------------------------------------------------------------------------*/ // Slices up a date range by row into an array of segments rangeToSegs: function(range) { var isRTL = this.isRTL; var rowCnt = this.rowCnt; var colCnt = this.colCnt; var segs = []; var first, last; // inclusive cell-offset range for given range var row; var rowFirst, rowLast; // inclusive cell-offset range for current row var isStart, isEnd; var segFirst, segLast; // inclusive cell-offset range for segment var seg; range = this.view.computeDayRange(range); // make whole-day range, considering nextDayThreshold first = this.dateToCellOffset(range.start); last = this.dateToCellOffset(range.end.subtract(1, 'days')); // offset of inclusive end date for (row = 0; row < rowCnt; row++) { rowFirst = row * colCnt; rowLast = rowFirst + colCnt - 1; // intersect segment's offset range with the row's segFirst = Math.max(rowFirst, first); segLast = Math.min(rowLast, last); // deal with in-between indices segFirst = Math.ceil(segFirst); // in-between starts round to next cell segLast = Math.floor(segLast); // in-between ends round to prev cell if (segFirst <= segLast) { // was there any intersection with the current row? // must be matching integers to be the segment's start/end isStart = segFirst === first; isEnd = segLast === last; // translate offsets to be relative to start-of-row segFirst -= rowFirst; segLast -= rowFirst; seg = { row: row, isStart: isStart, isEnd: isEnd }; if (isRTL) { seg.leftCol = colCnt - segLast - 1; seg.rightCol = colCnt - segFirst - 1; } else { seg.leftCol = segFirst; seg.rightCol = segLast; } segs.push(seg); } } return segs; }, // Given a date, returns its chronolocial cell-offset from the first cell of the grid. // If the date lies between cells (because of hiddenDays), returns a floating-point value between offsets. // If before the first offset, returns a negative number. // If after the last offset, returns an offset past the last cell offset. // Only works for *start* dates of cells. Will not work for exclusive end dates for cells. dateToCellOffset: function(date) { var offsets = this.dayToCellOffsets; var day = date.diff(this.start, 'days'); if (day < 0) { return offsets[0] - 1; } else if (day >= offsets.length) { return offsets[offsets.length - 1] + 1; } else { return offsets[day]; } }, /* Event Drag Visualization ------------------------------------------------------------------------------------------------------------------*/ // TODO: move to DayGrid.event, similar to what we did with Grid's drag methods // Renders a visual indication of an event or external element being dragged. // The dropLocation's end can be null. seg can be null. See Grid::renderDrag for more info. renderDrag: function(dropLocation, seg) { // always render a highlight underneath this.renderHighlight( this.view.calendar.ensureVisibleEventRange(dropLocation) // needs to be a proper range ); // if a segment from the same calendar but another component is being dragged, render a helper event if (seg && !seg.el.closest(this.el).length) { this.renderRangeHelper(dropLocation, seg); this.applyDragOpacity(this.helperEls); return true; // a helper has been rendered } }, // Unrenders any visual indication of a hovering event destroyDrag: function() { this.destroyHighlight(); this.destroyHelper(); }, /* Event Resize Visualization ------------------------------------------------------------------------------------------------------------------*/ // Renders a visual indication of an event being resized renderEventResize: function(range, seg) { this.renderHighlight(range); this.renderRangeHelper(range, seg); }, // Unrenders a visual indication of an event being resized destroyEventResize: function() { this.destroyHighlight(); this.destroyHelper(); }, /* Event Helper ------------------------------------------------------------------------------------------------------------------*/ // Renders a mock "helper" event. `sourceSeg` is the associated internal segment object. It can be null. renderHelper: function(event, sourceSeg) { var helperNodes = []; var segs = this.eventsToSegs([ event ]); var rowStructs; segs = this.renderFgSegEls(segs); // assigns each seg's el and returns a subset of segs that were rendered rowStructs = this.renderSegRows(segs); // inject each new event skeleton into each associated row this.rowEls.each(function(row, rowNode) { var rowEl = $(rowNode); // the .fc-row var skeletonEl = $('<div class="fc-helper-skeleton"><table/></div>'); // will be absolutely positioned var skeletonTop; // If there is an original segment, match the top position. Otherwise, put it at the row's top level if (sourceSeg && sourceSeg.row === row) { skeletonTop = sourceSeg.el.position().top; } else { skeletonTop = rowEl.find('.fc-content-skeleton tbody').position().top; } skeletonEl.css('top', skeletonTop) .find('table') .append(rowStructs[row].tbodyEl); rowEl.append(skeletonEl); helperNodes.push(skeletonEl[0]); }); this.helperEls = $(helperNodes); // array -> jQuery set }, // Unrenders any visual indication of a mock helper event destroyHelper: function() { if (this.helperEls) { this.helperEls.remove(); this.helperEls = null; } }, /* Fill System (highlight, background events, business hours) ------------------------------------------------------------------------------------------------------------------*/ fillSegTag: 'td', // override the default tag name // Renders a set of rectangles over the given segments of days. // Only returns segments that successfully rendered. renderFill: function(type, segs, className) { var nodes = []; var i, seg; var skeletonEl; segs = this.renderFillSegEls(type, segs); // assignes `.el` to each seg. returns successfully rendered segs for (i = 0; i < segs.length; i++) { seg = segs[i]; skeletonEl = this.renderFillRow(type, seg, className); this.rowEls.eq(seg.row).append(skeletonEl); nodes.push(skeletonEl[0]); } this.elsByFill[type] = $(nodes); return segs; }, // Generates the HTML needed for one row of a fill. Requires the seg's el to be rendered. renderFillRow: function(type, seg, className) { var colCnt = this.colCnt; var startCol = seg.leftCol; var endCol = seg.rightCol + 1; var skeletonEl; var trEl; className = className || type.toLowerCase(); skeletonEl = $( '<div class="fc-' + className + '-skeleton">' + '<table><tr/></table>' + '</div>' ); trEl = skeletonEl.find('tr'); if (startCol > 0) { trEl.append('<td colspan="' + startCol + '"/>'); } trEl.append( seg.el.attr('colspan', endCol - startCol) ); if (endCol < colCnt) { trEl.append('<td colspan="' + (colCnt - endCol) + '"/>'); } this.bookendCells(trEl, type); return skeletonEl; } }); ;; /* Event-rendering methods for the DayGrid class ----------------------------------------------------------------------------------------------------------------------*/ DayGrid.mixin({ rowStructs: null, // an array of objects, each holding information about a row's foreground event-rendering // Unrenders all events currently rendered on the grid destroyEvents: function() { this.destroySegPopover(); // removes the "more.." events popover Grid.prototype.destroyEvents.apply(this, arguments); // calls the super-method }, // Retrieves all rendered segment objects currently rendered on the grid getEventSegs: function() { return Grid.prototype.getEventSegs.call(this) // get the segments from the super-method .concat(this.popoverSegs || []); // append the segments from the "more..." popover }, // Renders the given background event segments onto the grid renderBgSegs: function(segs) { // don't render timed background events var allDaySegs = $.grep(segs, function(seg) { return seg.event.allDay; }); return Grid.prototype.renderBgSegs.call(this, allDaySegs); // call the super-method }, // Renders the given foreground event segments onto the grid renderFgSegs: function(segs) { var rowStructs; // render an `.el` on each seg // returns a subset of the segs. segs that were actually rendered segs = this.renderFgSegEls(segs); rowStructs = this.rowStructs = this.renderSegRows(segs); // append to each row's content skeleton this.rowEls.each(function(i, rowNode) { $(rowNode).find('.fc-content-skeleton > table').append( rowStructs[i].tbodyEl ); }); return segs; // return only the segs that were actually rendered }, // Unrenders all currently rendered foreground event segments destroyFgSegs: function() { var rowStructs = this.rowStructs || []; var rowStruct; while ((rowStruct = rowStructs.pop())) { rowStruct.tbodyEl.remove(); } this.rowStructs = null; }, // Uses the given events array to generate <tbody> elements that should be appended to each row's content skeleton. // Returns an array of rowStruct objects (see the bottom of `renderSegRow`). // PRECONDITION: each segment shoud already have a rendered and assigned `.el` renderSegRows: function(segs) { var rowStructs = []; var segRows; var row; segRows = this.groupSegRows(segs); // group into nested arrays // iterate each row of segment groupings for (row = 0; row < segRows.length; row++) { rowStructs.push( this.renderSegRow(row, segRows[row]) ); } return rowStructs; }, // Builds the HTML to be used for the default element for an individual segment fgSegHtml: function(seg, disableResizing) { var view = this.view; var event = seg.event; var isDraggable = view.isEventDraggable(event); var isResizableFromStart = !disableResizing && event.allDay && seg.isStart && view.isEventResizableFromStart(event); var isResizableFromEnd = !disableResizing && event.allDay && seg.isEnd && view.isEventResizableFromEnd(event); var classes = this.getSegClasses(seg, isDraggable, isResizableFromStart || isResizableFromEnd); var skinCss = cssToStr(this.getEventSkinCss(event)); var timeHtml = ''; var timeText; var titleHtml; classes.unshift('fc-day-grid-event', 'fc-h-event'); // Only display a timed events time if it is the starting segment if (seg.isStart) { timeText = this.getEventTimeText(event); if (timeText) { timeHtml = '<span class="fc-time">' + htmlEscape(timeText) + '</span>'; } } titleHtml = '<span class="fc-title">' + (htmlEscape(event.title || '') || '&nbsp;') + // we always want one line of height '</span>'; return '<a class="' + classes.join(' ') + '"' + (event.url ? ' href="' + htmlEscape(event.url) + '"' : '' ) + (skinCss ? ' style="' + skinCss + '"' : '' ) + '>' + '<div class="fc-content">' + (this.isRTL ? titleHtml + ' ' + timeHtml : // put a natural space in between timeHtml + ' ' + titleHtml // ) + '</div>' + (isResizableFromStart ? '<div class="fc-resizer fc-start-resizer" />' : '' ) + (isResizableFromEnd ? '<div class="fc-resizer fc-end-resizer" />' : '' ) + '</a>'; }, // Given a row # and an array of segments all in the same row, render a <tbody> element, a skeleton that contains // the segments. Returns object with a bunch of internal data about how the render was calculated. // NOTE: modifies rowSegs renderSegRow: function(row, rowSegs) { var colCnt = this.colCnt; var segLevels = this.buildSegLevels(rowSegs); // group into sub-arrays of levels var levelCnt = Math.max(1, segLevels.length); // ensure at least one level var tbody = $('<tbody/>'); var segMatrix = []; // lookup for which segments are rendered into which level+col cells var cellMatrix = []; // lookup for all <td> elements of the level+col matrix var loneCellMatrix = []; // lookup for <td> elements that only take up a single column var i, levelSegs; var col; var tr; var j, seg; var td; // populates empty cells from the current column (`col`) to `endCol` function emptyCellsUntil(endCol) { while (col < endCol) { // try to grab a cell from the level above and extend its rowspan. otherwise, create a fresh cell td = (loneCellMatrix[i - 1] || [])[col]; if (td) { td.attr( 'rowspan', parseInt(td.attr('rowspan') || 1, 10) + 1 ); } else { td = $('<td/>'); tr.append(td); } cellMatrix[i][col] = td; loneCellMatrix[i][col] = td; col++; } } for (i = 0; i < levelCnt; i++) { // iterate through all levels levelSegs = segLevels[i]; col = 0; tr = $('<tr/>'); segMatrix.push([]); cellMatrix.push([]); loneCellMatrix.push([]); // levelCnt might be 1 even though there are no actual levels. protect against this. // this single empty row is useful for styling. if (levelSegs) { for (j = 0; j < levelSegs.length; j++) { // iterate through segments in level seg = levelSegs[j]; emptyCellsUntil(seg.leftCol); // create a container that occupies or more columns. append the event element. td = $('<td class="fc-event-container"/>').append(seg.el); if (seg.leftCol != seg.rightCol) { td.attr('colspan', seg.rightCol - seg.leftCol + 1); } else { // a single-column segment loneCellMatrix[i][col] = td; } while (col <= seg.rightCol) { cellMatrix[i][col] = td; segMatrix[i][col] = seg; col++; } tr.append(td); } } emptyCellsUntil(colCnt); // finish off the row this.bookendCells(tr, 'eventSkeleton'); tbody.append(tr); } return { // a "rowStruct" row: row, // the row number tbodyEl: tbody, cellMatrix: cellMatrix, segMatrix: segMatrix, segLevels: segLevels, segs: rowSegs }; }, // Stacks a flat array of segments, which are all assumed to be in the same row, into subarrays of vertical levels. // NOTE: modifies segs buildSegLevels: function(segs) { var levels = []; var i, seg; var j; // Give preference to elements with certain criteria, so they have // a chance to be closer to the top. segs.sort(compareSegs); for (i = 0; i < segs.length; i++) { seg = segs[i]; // loop through levels, starting with the topmost, until the segment doesn't collide with other segments for (j = 0; j < levels.length; j++) { if (!isDaySegCollision(seg, levels[j])) { break; } } // `j` now holds the desired subrow index seg.level = j; // create new level array if needed and append segment (levels[j] || (levels[j] = [])).push(seg); } // order segments left-to-right. very important if calendar is RTL for (j = 0; j < levels.length; j++) { levels[j].sort(compareDaySegCols); } return levels; }, // Given a flat array of segments, return an array of sub-arrays, grouped by each segment's row groupSegRows: function(segs) { var segRows = []; var i; for (i = 0; i < this.rowCnt; i++) { segRows.push([]); } for (i = 0; i < segs.length; i++) { segRows[segs[i].row].push(segs[i]); } return segRows; } }); // Computes whether two segments' columns collide. They are assumed to be in the same row. function isDaySegCollision(seg, otherSegs) { var i, otherSeg; for (i = 0; i < otherSegs.length; i++) { otherSeg = otherSegs[i]; if ( otherSeg.leftCol <= seg.rightCol && otherSeg.rightCol >= seg.leftCol ) { return true; } } return false; } // A cmp function for determining the leftmost event function compareDaySegCols(a, b) { return a.leftCol - b.leftCol; } ;; /* Methods relate to limiting the number events for a given day on a DayGrid ----------------------------------------------------------------------------------------------------------------------*/ // NOTE: all the segs being passed around in here are foreground segs DayGrid.mixin({ segPopover: null, // the Popover that holds events that can't fit in a cell. null when not visible popoverSegs: null, // an array of segment objects that the segPopover holds. null when not visible destroySegPopover: function() { if (this.segPopover) { this.segPopover.hide(); // will trigger destruction of `segPopover` and `popoverSegs` } }, // Limits the number of "levels" (vertically stacking layers of events) for each row of the grid. // `levelLimit` can be false (don't limit), a number, or true (should be computed). limitRows: function(levelLimit) { var rowStructs = this.rowStructs || []; var row; // row # var rowLevelLimit; for (row = 0; row < rowStructs.length; row++) { this.unlimitRow(row); if (!levelLimit) { rowLevelLimit = false; } else if (typeof levelLimit === 'number') { rowLevelLimit = levelLimit; } else { rowLevelLimit = this.computeRowLevelLimit(row); } if (rowLevelLimit !== false) { this.limitRow(row, rowLevelLimit); } } }, // Computes the number of levels a row will accomodate without going outside its bounds. // Assumes the row is "rigid" (maintains a constant height regardless of what is inside). // `row` is the row number. computeRowLevelLimit: function(row) { var rowEl = this.rowEls.eq(row); // the containing "fake" row div var rowHeight = rowEl.height(); // TODO: cache somehow? var trEls = this.rowStructs[row].tbodyEl.children(); var i, trEl; var trHeight; function iterInnerHeights(i, childNode) { trHeight = Math.max(trHeight, $(childNode).outerHeight()); } // Reveal one level <tr> at a time and stop when we find one out of bounds for (i = 0; i < trEls.length; i++) { trEl = trEls.eq(i).removeClass('fc-limited'); // reset to original state (reveal) // with rowspans>1 and IE8, trEl.outerHeight() would return the height of the largest cell, // so instead, find the tallest inner content element. trHeight = 0; trEl.find('> td > :first-child').each(iterInnerHeights); if (trEl.position().top + trHeight > rowHeight) { return i; } } return false; // should not limit at all }, // Limits the given grid row to the maximum number of levels and injects "more" links if necessary. // `row` is the row number. // `levelLimit` is a number for the maximum (inclusive) number of levels allowed. limitRow: function(row, levelLimit) { var _this = this; var rowStruct = this.rowStructs[row]; var moreNodes = []; // array of "more" <a> links and <td> DOM nodes var col = 0; // col #, left-to-right (not chronologically) var cell; var levelSegs; // array of segment objects in the last allowable level, ordered left-to-right var cellMatrix; // a matrix (by level, then column) of all <td> jQuery elements in the row var limitedNodes; // array of temporarily hidden level <tr> and segment <td> DOM nodes var i, seg; var segsBelow; // array of segment objects below `seg` in the current `col` var totalSegsBelow; // total number of segments below `seg` in any of the columns `seg` occupies var colSegsBelow; // array of segment arrays, below seg, one for each column (offset from segs's first column) var td, rowspan; var segMoreNodes; // array of "more" <td> cells that will stand-in for the current seg's cell var j; var moreTd, moreWrap, moreLink; // Iterates through empty level cells and places "more" links inside if need be function emptyCellsUntil(endCol) { // goes from current `col` to `endCol` while (col < endCol) { cell = _this.getCell(row, col); segsBelow = _this.getCellSegs(cell, levelLimit); if (segsBelow.length) { td = cellMatrix[levelLimit - 1][col]; moreLink = _this.renderMoreLink(cell, segsBelow); moreWrap = $('<div/>').append(moreLink); td.append(moreWrap); moreNodes.push(moreWrap[0]); } col++; } } if (levelLimit && levelLimit < rowStruct.segLevels.length) { // is it actually over the limit? levelSegs = rowStruct.segLevels[levelLimit - 1]; cellMatrix = rowStruct.cellMatrix; limitedNodes = rowStruct.tbodyEl.children().slice(levelLimit) // get level <tr> elements past the limit .addClass('fc-limited').get(); // hide elements and get a simple DOM-nodes array // iterate though segments in the last allowable level for (i = 0; i < levelSegs.length; i++) { seg = levelSegs[i]; emptyCellsUntil(seg.leftCol); // process empty cells before the segment // determine *all* segments below `seg` that occupy the same columns colSegsBelow = []; totalSegsBelow = 0; while (col <= seg.rightCol) { cell = this.getCell(row, col); segsBelow = this.getCellSegs(cell, levelLimit); colSegsBelow.push(segsBelow); totalSegsBelow += segsBelow.length; col++; } if (totalSegsBelow) { // do we need to replace this segment with one or many "more" links? td = cellMatrix[levelLimit - 1][seg.leftCol]; // the segment's parent cell rowspan = td.attr('rowspan') || 1; segMoreNodes = []; // make a replacement <td> for each column the segment occupies. will be one for each colspan for (j = 0; j < colSegsBelow.length; j++) { moreTd = $('<td class="fc-more-cell"/>').attr('rowspan', rowspan); segsBelow = colSegsBelow[j]; cell = this.getCell(row, seg.leftCol + j); moreLink = this.renderMoreLink(cell, [ seg ].concat(segsBelow)); // count seg as hidden too moreWrap = $('<div/>').append(moreLink); moreTd.append(moreWrap); segMoreNodes.push(moreTd[0]); moreNodes.push(moreTd[0]); } td.addClass('fc-limited').after($(segMoreNodes)); // hide original <td> and inject replacements limitedNodes.push(td[0]); } } emptyCellsUntil(this.colCnt); // finish off the level rowStruct.moreEls = $(moreNodes); // for easy undoing later rowStruct.limitedEls = $(limitedNodes); // for easy undoing later } }, // Reveals all levels and removes all "more"-related elements for a grid's row. // `row` is a row number. unlimitRow: function(row) { var rowStruct = this.rowStructs[row]; if (rowStruct.moreEls) { rowStruct.moreEls.remove(); rowStruct.moreEls = null; } if (rowStruct.limitedEls) { rowStruct.limitedEls.removeClass('fc-limited'); rowStruct.limitedEls = null; } }, // Renders an <a> element that represents hidden event element for a cell. // Responsible for attaching click handler as well. renderMoreLink: function(cell, hiddenSegs) { var _this = this; var view = this.view; return $('<a class="fc-more"/>') .text( this.getMoreLinkText(hiddenSegs.length) ) .on('click', function(ev) { var clickOption = view.opt('eventLimitClick'); var date = cell.start; var moreEl = $(this); var dayEl = _this.getCellDayEl(cell); var allSegs = _this.getCellSegs(cell); // rescope the segments to be within the cell's date var reslicedAllSegs = _this.resliceDaySegs(allSegs, date); var reslicedHiddenSegs = _this.resliceDaySegs(hiddenSegs, date); if (typeof clickOption === 'function') { // the returned value can be an atomic option clickOption = view.trigger('eventLimitClick', null, { date: date, dayEl: dayEl, moreEl: moreEl, segs: reslicedAllSegs, hiddenSegs: reslicedHiddenSegs }, ev); } if (clickOption === 'popover') { _this.showSegPopover(cell, moreEl, reslicedAllSegs); } else if (typeof clickOption === 'string') { // a view name view.calendar.zoomTo(date, clickOption); } }); }, // Reveals the popover that displays all events within a cell showSegPopover: function(cell, moreLink, segs) { var _this = this; var view = this.view; var moreWrap = moreLink.parent(); // the <div> wrapper around the <a> var topEl; // the element we want to match the top coordinate of var options; if (this.rowCnt == 1) { topEl = view.el; // will cause the popover to cover any sort of header } else { topEl = this.rowEls.eq(cell.row); // will align with top of row } options = { className: 'fc-more-popover', content: this.renderSegPopoverContent(cell, segs), parentEl: this.el, top: topEl.offset().top, autoHide: true, // when the user clicks elsewhere, hide the popover viewportConstrain: view.opt('popoverViewportConstrain'), hide: function() { // destroy everything when the popover is hidden _this.segPopover.destroy(); _this.segPopover = null; _this.popoverSegs = null; } }; // Determine horizontal coordinate. // We use the moreWrap instead of the <td> to avoid border confusion. if (this.isRTL) { options.right = moreWrap.offset().left + moreWrap.outerWidth() + 1; // +1 to be over cell border } else { options.left = moreWrap.offset().left - 1; // -1 to be over cell border } this.segPopover = new Popover(options); this.segPopover.show(); }, // Builds the inner DOM contents of the segment popover renderSegPopoverContent: function(cell, segs) { var view = this.view; var isTheme = view.opt('theme'); var title = cell.start.format(view.opt('dayPopoverFormat')); var content = $( '<div class="fc-header ' + view.widgetHeaderClass + '">' + '<span class="fc-close ' + (isTheme ? 'ui-icon ui-icon-closethick' : 'fc-icon fc-icon-x') + '"></span>' + '<span class="fc-title">' + htmlEscape(title) + '</span>' + '<div class="fc-clear"/>' + '</div>' + '<div class="fc-body ' + view.widgetContentClass + '">' + '<div class="fc-event-container"></div>' + '</div>' ); var segContainer = content.find('.fc-event-container'); var i; // render each seg's `el` and only return the visible segs segs = this.renderFgSegEls(segs, true); // disableResizing=true this.popoverSegs = segs; for (i = 0; i < segs.length; i++) { // because segments in the popover are not part of a grid coordinate system, provide a hint to any // grids that want to do drag-n-drop about which cell it came from segs[i].cell = cell; segContainer.append(segs[i].el); } return content; }, // Given the events within an array of segment objects, reslice them to be in a single day resliceDaySegs: function(segs, dayDate) { // build an array of the original events var events = $.map(segs, function(seg) { return seg.event; }); var dayStart = dayDate.clone().stripTime(); var dayEnd = dayStart.clone().add(1, 'days'); var dayRange = { start: dayStart, end: dayEnd }; // slice the events with a custom slicing function segs = this.eventsToSegs( events, function(range) { var seg = intersectionToSeg(range, dayRange); // undefind if no intersection return seg ? [ seg ] : []; // must return an array of segments } ); // force an order because eventsToSegs doesn't guarantee one segs.sort(compareSegs); return segs; }, // Generates the text that should be inside a "more" link, given the number of events it represents getMoreLinkText: function(num) { var opt = this.view.opt('eventLimitText'); if (typeof opt === 'function') { return opt(num); } else { return '+' + num + ' ' + opt; } }, // Returns segments within a given cell. // If `startLevel` is specified, returns only events including and below that level. Otherwise returns all segs. getCellSegs: function(cell, startLevel) { var segMatrix = this.rowStructs[cell.row].segMatrix; var level = startLevel || 0; var segs = []; var seg; while (level < segMatrix.length) { seg = segMatrix[level][cell.col]; if (seg) { segs.push(seg); } level++; } return segs; } }); ;; /* A component that renders one or more columns of vertical time slots ----------------------------------------------------------------------------------------------------------------------*/ var TimeGrid = Grid.extend({ slotDuration: null, // duration of a "slot", a distinct time segment on given day, visualized by lines snapDuration: null, // granularity of time for dragging and selecting minTime: null, // Duration object that denotes the first visible time of any given day maxTime: null, // Duration object that denotes the exclusive visible end time of any given day axisFormat: null, // formatting string for times running along vertical axis dayEls: null, // cells elements in the day-row background slatEls: null, // elements running horizontally across all columns slatTops: null, // an array of top positions, relative to the container. last item holds bottom of last slot helperEl: null, // cell skeleton element for rendering the mock event "helper" businessHourSegs: null, constructor: function() { Grid.apply(this, arguments); // call the super-constructor this.processOptions(); }, // Renders the time grid into `this.el`, which should already be assigned. // Relies on the view's colCnt. In the future, this component should probably be self-sufficient. renderDates: function() { this.el.html(this.renderHtml()); this.dayEls = this.el.find('.fc-day'); this.slatEls = this.el.find('.fc-slats tr'); }, renderBusinessHours: function() { var events = this.view.calendar.getBusinessHoursEvents(); this.businessHourSegs = this.renderFill('businessHours', this.eventsToSegs(events), 'bgevent'); }, // Renders the basic HTML skeleton for the grid renderHtml: function() { return '' + '<div class="fc-bg">' + '<table>' + this.rowHtml('slotBg') + // leverages RowRenderer, which will call slotBgCellHtml '</table>' + '</div>' + '<div class="fc-slats">' + '<table>' + this.slatRowHtml() + '</table>' + '</div>'; }, // Renders the HTML for a vertical background cell behind the slots. // This method is distinct from 'bg' because we wanted a new `rowType` so the View could customize the rendering. slotBgCellHtml: function(cell) { return this.bgCellHtml(cell); }, // Generates the HTML for the horizontal "slats" that run width-wise. Has a time axis on a side. Depends on RTL. slatRowHtml: function() { var view = this.view; var isRTL = this.isRTL; var html = ''; var slotNormal = this.slotDuration.asMinutes() % 15 === 0; var slotTime = moment.duration(+this.minTime); // wish there was .clone() for durations var slotDate; // will be on the view's first day, but we only care about its time var minutes; var axisHtml; // Calculate the time for each slot while (slotTime < this.maxTime) { slotDate = this.start.clone().time(slotTime); // will be in UTC but that's good. to avoid DST issues minutes = slotDate.minutes(); axisHtml = '<td class="fc-axis fc-time ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '>' + ((!slotNormal || !minutes) ? // if irregular slot duration, or on the hour, then display the time '<span>' + // for matchCellWidths htmlEscape(slotDate.format(this.axisFormat)) + '</span>' : '' ) + '</td>'; html += '<tr ' + (!minutes ? '' : 'class="fc-minor"') + '>' + (!isRTL ? axisHtml : '') + '<td class="' + view.widgetContentClass + '"/>' + (isRTL ? axisHtml : '') + "</tr>"; slotTime.add(this.slotDuration); } return html; }, /* Options ------------------------------------------------------------------------------------------------------------------*/ // Parses various options into properties of this object processOptions: function() { var view = this.view; var slotDuration = view.opt('slotDuration'); var snapDuration = view.opt('snapDuration'); slotDuration = moment.duration(slotDuration); snapDuration = snapDuration ? moment.duration(snapDuration) : slotDuration; this.slotDuration = slotDuration; this.snapDuration = snapDuration; this.cellDuration = snapDuration; // for Grid system this.minTime = moment.duration(view.opt('minTime')); this.maxTime = moment.duration(view.opt('maxTime')); this.axisFormat = view.opt('axisFormat') || view.opt('smallTimeFormat'); }, // Computes a default column header formatting string if `colFormat` is not explicitly defined computeColHeadFormat: function() { if (this.colCnt > 1) { // multiple days, so full single date string WON'T be in title text return this.view.opt('dayOfMonthFormat'); // "Sat 12/10" } else { // single day, so full single date string will probably be in title text return 'dddd'; // "Saturday" } }, // Computes a default event time formatting string if `timeFormat` is not explicitly defined computeEventTimeFormat: function() { return this.view.opt('noMeridiemTimeFormat'); // like "6:30" (no AM/PM) }, // Computes a default `displayEventEnd` value if one is not expliclty defined computeDisplayEventEnd: function() { return true; }, /* Cell System ------------------------------------------------------------------------------------------------------------------*/ // Initializes row/col information updateCells: function() { var view = this.view; var colData = []; var date; date = this.start.clone(); while (date.isBefore(this.end)) { colData.push({ day: date.clone() }); date.add(1, 'day'); date = view.skipHiddenDays(date); } if (this.isRTL) { colData.reverse(); } this.colData = colData; this.colCnt = colData.length; this.rowCnt = Math.ceil((this.maxTime - this.minTime) / this.snapDuration); // # of vertical snaps }, // Given a cell object, generates its start date. Returns a reference-free copy. computeCellDate: function(cell) { var time = this.computeSnapTime(cell.row); return this.view.calendar.rezoneDate(cell.day).time(time); }, // Retrieves the element representing the given column getColEl: function(col) { return this.dayEls.eq(col); }, /* Dates ------------------------------------------------------------------------------------------------------------------*/ // Given a row number of the grid, representing a "snap", returns a time (Duration) from its start-of-day computeSnapTime: function(row) { return moment.duration(this.minTime + this.snapDuration * row); }, // Slices up a date range by column into an array of segments rangeToSegs: function(range) { var colCnt = this.colCnt; var segs = []; var seg; var col; var colDate; var colRange; // normalize :( range = { start: range.start.clone().stripZone(), end: range.end.clone().stripZone() }; for (col = 0; col < colCnt; col++) { colDate = this.colData[col].day; // will be ambig time/timezone colRange = { start: colDate.clone().time(this.minTime), end: colDate.clone().time(this.maxTime) }; seg = intersectionToSeg(range, colRange); // both will be ambig timezone if (seg) { seg.col = col; segs.push(seg); } } return segs; }, /* Coordinates ------------------------------------------------------------------------------------------------------------------*/ updateSize: function(isResize) { // NOT a standard Grid method this.computeSlatTops(); if (isResize) { this.updateSegVerticals(); } }, // Computes the top/bottom coordinates of each "snap" rows computeRowCoords: function() { var originTop = this.el.offset().top; var items = []; var i; var item; for (i = 0; i < this.rowCnt; i++) { item = { top: originTop + this.computeTimeTop(this.computeSnapTime(i)) }; if (i > 0) { items[i - 1].bottom = item.top; } items.push(item); } item.bottom = item.top + this.computeTimeTop(this.computeSnapTime(i)); return items; }, // Computes the top coordinate, relative to the bounds of the grid, of the given date. // A `startOfDayDate` must be given for avoiding ambiguity over how to treat midnight. computeDateTop: function(date, startOfDayDate) { return this.computeTimeTop( moment.duration( date.clone().stripZone() - startOfDayDate.clone().stripTime() ) ); }, // Computes the top coordinate, relative to the bounds of the grid, of the given time (a Duration). computeTimeTop: function(time) { var slatCoverage = (time - this.minTime) / this.slotDuration; // floating-point value of # of slots covered var slatIndex; var slatRemainder; var slatTop; var slatBottom; // constrain. because minTime/maxTime might be customized slatCoverage = Math.max(0, slatCoverage); slatCoverage = Math.min(this.slatEls.length, slatCoverage); slatIndex = Math.floor(slatCoverage); // an integer index of the furthest whole slot slatRemainder = slatCoverage - slatIndex; slatTop = this.slatTops[slatIndex]; // the top position of the furthest whole slot if (slatRemainder) { // time spans part-way into the slot slatBottom = this.slatTops[slatIndex + 1]; return slatTop + (slatBottom - slatTop) * slatRemainder; // part-way between slots } else { return slatTop; } }, // Queries each `slatEl` for its position relative to the grid's container and stores it in `slatTops`. // Includes the the bottom of the last slat as the last item in the array. computeSlatTops: function() { var tops = []; var top; this.slatEls.each(function(i, node) { top = $(node).position().top; tops.push(top); }); tops.push(top + this.slatEls.last().outerHeight()); // bottom of the last slat this.slatTops = tops; }, /* Event Drag Visualization ------------------------------------------------------------------------------------------------------------------*/ // Renders a visual indication of an event being dragged over the specified date(s). // dropLocation's end might be null, as well as `seg`. See Grid::renderDrag for more info. // A returned value of `true` signals that a mock "helper" event has been rendered. renderDrag: function(dropLocation, seg) { if (seg) { // if there is event information for this drag, render a helper event this.renderRangeHelper(dropLocation, seg); this.applyDragOpacity(this.helperEl); return true; // signal that a helper has been rendered } else { // otherwise, just render a highlight this.renderHighlight( this.view.calendar.ensureVisibleEventRange(dropLocation) // needs to be a proper range ); } }, // Unrenders any visual indication of an event being dragged destroyDrag: function() { this.destroyHelper(); this.destroyHighlight(); }, /* Event Resize Visualization ------------------------------------------------------------------------------------------------------------------*/ // Renders a visual indication of an event being resized renderEventResize: function(range, seg) { this.renderRangeHelper(range, seg); }, // Unrenders any visual indication of an event being resized destroyEventResize: function() { this.destroyHelper(); }, /* Event Helper ------------------------------------------------------------------------------------------------------------------*/ // Renders a mock "helper" event. `sourceSeg` is the original segment object and might be null (an external drag) renderHelper: function(event, sourceSeg) { var segs = this.eventsToSegs([ event ]); var tableEl; var i, seg; var sourceEl; segs = this.renderFgSegEls(segs); // assigns each seg's el and returns a subset of segs that were rendered tableEl = this.renderSegTable(segs); // Try to make the segment that is in the same row as sourceSeg look the same for (i = 0; i < segs.length; i++) { seg = segs[i]; if (sourceSeg && sourceSeg.col === seg.col) { sourceEl = sourceSeg.el; seg.el.css({ left: sourceEl.css('left'), right: sourceEl.css('right'), 'margin-left': sourceEl.css('margin-left'), 'margin-right': sourceEl.css('margin-right') }); } } this.helperEl = $('<div class="fc-helper-skeleton"/>') .append(tableEl) .appendTo(this.el); }, // Unrenders any mock helper event destroyHelper: function() { if (this.helperEl) { this.helperEl.remove(); this.helperEl = null; } }, /* Selection ------------------------------------------------------------------------------------------------------------------*/ // Renders a visual indication of a selection. Overrides the default, which was to simply render a highlight. renderSelection: function(range) { if (this.view.opt('selectHelper')) { // this setting signals that a mock helper event should be rendered this.renderRangeHelper(range); } else { this.renderHighlight(range); } }, // Unrenders any visual indication of a selection destroySelection: function() { this.destroyHelper(); this.destroyHighlight(); }, /* Fill System (highlight, background events, business hours) ------------------------------------------------------------------------------------------------------------------*/ // Renders a set of rectangles over the given time segments. // Only returns segments that successfully rendered. renderFill: function(type, segs, className) { var segCols; var skeletonEl; var trEl; var col, colSegs; var tdEl; var containerEl; var dayDate; var i, seg; if (segs.length) { segs = this.renderFillSegEls(type, segs); // assignes `.el` to each seg. returns successfully rendered segs segCols = this.groupSegCols(segs); // group into sub-arrays, and assigns 'col' to each seg className = className || type.toLowerCase(); skeletonEl = $( '<div class="fc-' + className + '-skeleton">' + '<table><tr/></table>' + '</div>' ); trEl = skeletonEl.find('tr'); for (col = 0; col < segCols.length; col++) { colSegs = segCols[col]; tdEl = $('<td/>').appendTo(trEl); if (colSegs.length) { containerEl = $('<div class="fc-' + className + '-container"/>').appendTo(tdEl); dayDate = this.colData[col].day; for (i = 0; i < colSegs.length; i++) { seg = colSegs[i]; containerEl.append( seg.el.css({ top: this.computeDateTop(seg.start, dayDate), bottom: -this.computeDateTop(seg.end, dayDate) // the y position of the bottom edge }) ); } } } this.bookendCells(trEl, type); this.el.append(skeletonEl); this.elsByFill[type] = skeletonEl; } return segs; } }); ;; /* Event-rendering methods for the TimeGrid class ----------------------------------------------------------------------------------------------------------------------*/ TimeGrid.mixin({ eventSkeletonEl: null, // has cells with event-containers, which contain absolutely positioned event elements // Renders the given foreground event segments onto the grid renderFgSegs: function(segs) { segs = this.renderFgSegEls(segs); // returns a subset of the segs. segs that were actually rendered this.el.append( this.eventSkeletonEl = $('<div class="fc-content-skeleton"/>') .append(this.renderSegTable(segs)) ); return segs; // return only the segs that were actually rendered }, // Unrenders all currently rendered foreground event segments destroyFgSegs: function(segs) { if (this.eventSkeletonEl) { this.eventSkeletonEl.remove(); this.eventSkeletonEl = null; } }, // Renders and returns the <table> portion of the event-skeleton. // Returns an object with properties 'tbodyEl' and 'segs'. renderSegTable: function(segs) { var tableEl = $('<table><tr/></table>'); var trEl = tableEl.find('tr'); var segCols; var i, seg; var col, colSegs; var containerEl; segCols = this.groupSegCols(segs); // group into sub-arrays, and assigns 'col' to each seg this.computeSegVerticals(segs); // compute and assign top/bottom for (col = 0; col < segCols.length; col++) { // iterate each column grouping colSegs = segCols[col]; placeSlotSegs(colSegs); // compute horizontal coordinates, z-index's, and reorder the array containerEl = $('<div class="fc-event-container"/>'); // assign positioning CSS and insert into container for (i = 0; i < colSegs.length; i++) { seg = colSegs[i]; seg.el.css(this.generateSegPositionCss(seg)); // if the height is short, add a className for alternate styling if (seg.bottom - seg.top < 30) { seg.el.addClass('fc-short'); } containerEl.append(seg.el); } trEl.append($('<td/>').append(containerEl)); } this.bookendCells(trEl, 'eventSkeleton'); return tableEl; }, // Refreshes the CSS top/bottom coordinates for each segment element. Probably after a window resize/zoom. // Repositions business hours segs too, so not just for events. Maybe shouldn't be here. updateSegVerticals: function() { var allSegs = (this.segs || []).concat(this.businessHourSegs || []); var i; this.computeSegVerticals(allSegs); for (i = 0; i < allSegs.length; i++) { allSegs[i].el.css( this.generateSegVerticalCss(allSegs[i]) ); } }, // For each segment in an array, computes and assigns its top and bottom properties computeSegVerticals: function(segs) { var i, seg; for (i = 0; i < segs.length; i++) { seg = segs[i]; seg.top = this.computeDateTop(seg.start, seg.start); seg.bottom = this.computeDateTop(seg.end, seg.start); } }, // Renders the HTML for a single event segment's default rendering fgSegHtml: function(seg, disableResizing) { var view = this.view; var event = seg.event; var isDraggable = view.isEventDraggable(event); var isResizableFromStart = !disableResizing && seg.isStart && view.isEventResizableFromStart(event); var isResizableFromEnd = !disableResizing && seg.isEnd && view.isEventResizableFromEnd(event); var classes = this.getSegClasses(seg, isDraggable, isResizableFromStart || isResizableFromEnd); var skinCss = cssToStr(this.getEventSkinCss(event)); var timeText; var fullTimeText; // more verbose time text. for the print stylesheet var startTimeText; // just the start time text classes.unshift('fc-time-grid-event', 'fc-v-event'); if (view.isMultiDayEvent(event)) { // if the event appears to span more than one day... // Don't display time text on segments that run entirely through a day. // That would appear as midnight-midnight and would look dumb. // Otherwise, display the time text for the *segment's* times (like 6pm-midnight or midnight-10am) if (seg.isStart || seg.isEnd) { timeText = this.getEventTimeText(seg); fullTimeText = this.getEventTimeText(seg, 'LT'); startTimeText = this.getEventTimeText(seg, null, false); // displayEnd=false } } else { // Display the normal time text for the *event's* times timeText = this.getEventTimeText(event); fullTimeText = this.getEventTimeText(event, 'LT'); startTimeText = this.getEventTimeText(event, null, false); // displayEnd=false } return '<a class="' + classes.join(' ') + '"' + (event.url ? ' href="' + htmlEscape(event.url) + '"' : '' ) + (skinCss ? ' style="' + skinCss + '"' : '' ) + '>' + '<div class="fc-content">' + (timeText ? '<div class="fc-time"' + ' data-start="' + htmlEscape(startTimeText) + '"' + ' data-full="' + htmlEscape(fullTimeText) + '"' + '>' + '<span>' + htmlEscape(timeText) + '</span>' + '</div>' : '' ) + (event.title ? '<div class="fc-title">' + htmlEscape(event.title) + '</div>' : '' ) + '</div>' + '<div class="fc-bg"/>' + /* TODO: write CSS for this (isResizableFromStart ? '<div class="fc-resizer fc-start-resizer" />' : '' ) + */ (isResizableFromEnd ? '<div class="fc-resizer fc-end-resizer" />' : '' ) + '</a>'; }, // Generates an object with CSS properties/values that should be applied to an event segment element. // Contains important positioning-related properties that should be applied to any event element, customized or not. generateSegPositionCss: function(seg) { var shouldOverlap = this.view.opt('slotEventOverlap'); var backwardCoord = seg.backwardCoord; // the left side if LTR. the right side if RTL. floating-point var forwardCoord = seg.forwardCoord; // the right side if LTR. the left side if RTL. floating-point var props = this.generateSegVerticalCss(seg); // get top/bottom first var left; // amount of space from left edge, a fraction of the total width var right; // amount of space from right edge, a fraction of the total width if (shouldOverlap) { // double the width, but don't go beyond the maximum forward coordinate (1.0) forwardCoord = Math.min(1, backwardCoord + (forwardCoord - backwardCoord) * 2); } if (this.isRTL) { left = 1 - forwardCoord; right = backwardCoord; } else { left = backwardCoord; right = 1 - forwardCoord; } props.zIndex = seg.level + 1; // convert from 0-base to 1-based props.left = left * 100 + '%'; props.right = right * 100 + '%'; if (shouldOverlap && seg.forwardPressure) { // add padding to the edge so that forward stacked events don't cover the resizer's icon props[this.isRTL ? 'marginLeft' : 'marginRight'] = 10 * 2; // 10 is a guesstimate of the icon's width } return props; }, // Generates an object with CSS properties for the top/bottom coordinates of a segment element generateSegVerticalCss: function(seg) { return { top: seg.top, bottom: -seg.bottom // flipped because needs to be space beyond bottom edge of event container }; }, // Given a flat array of segments, return an array of sub-arrays, grouped by each segment's col groupSegCols: function(segs) { var segCols = []; var i; for (i = 0; i < this.colCnt; i++) { segCols.push([]); } for (i = 0; i < segs.length; i++) { segCols[segs[i].col].push(segs[i]); } return segCols; } }); // Given an array of segments that are all in the same column, sets the backwardCoord and forwardCoord on each. // NOTE: Also reorders the given array by date! function placeSlotSegs(segs) { var levels; var level0; var i; segs.sort(compareSegs); // order by date levels = buildSlotSegLevels(segs); computeForwardSlotSegs(levels); if ((level0 = levels[0])) { for (i = 0; i < level0.length; i++) { computeSlotSegPressures(level0[i]); } for (i = 0; i < level0.length; i++) { computeSlotSegCoords(level0[i], 0, 0); } } } // Builds an array of segments "levels". The first level will be the leftmost tier of segments if the calendar is // left-to-right, or the rightmost if the calendar is right-to-left. Assumes the segments are already ordered by date. function buildSlotSegLevels(segs) { var levels = []; var i, seg; var j; for (i=0; i<segs.length; i++) { seg = segs[i]; // go through all the levels and stop on the first level where there are no collisions for (j=0; j<levels.length; j++) { if (!computeSlotSegCollisions(seg, levels[j]).length) { break; } } seg.level = j; (levels[j] || (levels[j] = [])).push(seg); } return levels; } // For every segment, figure out the other segments that are in subsequent // levels that also occupy the same vertical space. Accumulate in seg.forwardSegs function computeForwardSlotSegs(levels) { var i, level; var j, seg; var k; for (i=0; i<levels.length; i++) { level = levels[i]; for (j=0; j<level.length; j++) { seg = level[j]; seg.forwardSegs = []; for (k=i+1; k<levels.length; k++) { computeSlotSegCollisions(seg, levels[k], seg.forwardSegs); } } } } // Figure out which path forward (via seg.forwardSegs) results in the longest path until // the furthest edge is reached. The number of segments in this path will be seg.forwardPressure function computeSlotSegPressures(seg) { var forwardSegs = seg.forwardSegs; var forwardPressure = 0; var i, forwardSeg; if (seg.forwardPressure === undefined) { // not already computed for (i=0; i<forwardSegs.length; i++) { forwardSeg = forwardSegs[i]; // figure out the child's maximum forward path computeSlotSegPressures(forwardSeg); // either use the existing maximum, or use the child's forward pressure // plus one (for the forwardSeg itself) forwardPressure = Math.max( forwardPressure, 1 + forwardSeg.forwardPressure ); } seg.forwardPressure = forwardPressure; } } // Calculate seg.forwardCoord and seg.backwardCoord for the segment, where both values range // from 0 to 1. If the calendar is left-to-right, the seg.backwardCoord maps to "left" and // seg.forwardCoord maps to "right" (via percentage). Vice-versa if the calendar is right-to-left. // // The segment might be part of a "series", which means consecutive segments with the same pressure // who's width is unknown until an edge has been hit. `seriesBackwardPressure` is the number of // segments behind this one in the current series, and `seriesBackwardCoord` is the starting // coordinate of the first segment in the series. function computeSlotSegCoords(seg, seriesBackwardPressure, seriesBackwardCoord) { var forwardSegs = seg.forwardSegs; var i; if (seg.forwardCoord === undefined) { // not already computed if (!forwardSegs.length) { // if there are no forward segments, this segment should butt up against the edge seg.forwardCoord = 1; } else { // sort highest pressure first forwardSegs.sort(compareForwardSlotSegs); // this segment's forwardCoord will be calculated from the backwardCoord of the // highest-pressure forward segment. computeSlotSegCoords(forwardSegs[0], seriesBackwardPressure + 1, seriesBackwardCoord); seg.forwardCoord = forwardSegs[0].backwardCoord; } // calculate the backwardCoord from the forwardCoord. consider the series seg.backwardCoord = seg.forwardCoord - (seg.forwardCoord - seriesBackwardCoord) / // available width for series (seriesBackwardPressure + 1); // # of segments in the series // use this segment's coordinates to computed the coordinates of the less-pressurized // forward segments for (i=0; i<forwardSegs.length; i++) { computeSlotSegCoords(forwardSegs[i], 0, seg.forwardCoord); } } } // Find all the segments in `otherSegs` that vertically collide with `seg`. // Append into an optionally-supplied `results` array and return. function computeSlotSegCollisions(seg, otherSegs, results) { results = results || []; for (var i=0; i<otherSegs.length; i++) { if (isSlotSegCollision(seg, otherSegs[i])) { results.push(otherSegs[i]); } } return results; } // Do these segments occupy the same vertical space? function isSlotSegCollision(seg1, seg2) { return seg1.bottom > seg2.top && seg1.top < seg2.bottom; } // A cmp function for determining which forward segment to rely on more when computing coordinates. function compareForwardSlotSegs(seg1, seg2) { // put higher-pressure first return seg2.forwardPressure - seg1.forwardPressure || // put segments that are closer to initial edge first (and favor ones with no coords yet) (seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) || // do normal sorting... compareSegs(seg1, seg2); } ;; /* An abstract class from which other views inherit from ----------------------------------------------------------------------------------------------------------------------*/ var View = fc.View = Class.extend({ type: null, // subclass' view name (string) name: null, // deprecated. use `type` instead title: null, // the text that will be displayed in the header's title calendar: null, // owner Calendar object options: null, // hash containing all options. already merged with view-specific-options coordMap: null, // a CoordMap object for converting pixel regions to dates el: null, // the view's containing element. set by Calendar isDisplayed: false, isSkeletonRendered: false, isEventsRendered: false, // range the view is actually displaying (moments) start: null, end: null, // exclusive // range the view is formally responsible for (moments) // may be different from start/end. for example, a month view might have 1st-31st, excluding padded dates intervalStart: null, intervalEnd: null, // exclusive intervalDuration: null, intervalUnit: null, // name of largest unit being displayed, like "month" or "week" isSelected: false, // boolean whether a range of time is user-selected or not // subclasses can optionally use a scroll container scrollerEl: null, // the element that will most likely scroll when content is too tall scrollTop: null, // cached vertical scroll value // classNames styled by jqui themes widgetHeaderClass: null, widgetContentClass: null, highlightStateClass: null, // for date utils, computed from options nextDayThreshold: null, isHiddenDayHash: null, // document handlers, bound to `this` object documentMousedownProxy: null, // TODO: doesn't work with touch constructor: function(calendar, type, options, intervalDuration) { this.calendar = calendar; this.type = this.name = type; // .name is deprecated this.options = options; this.intervalDuration = intervalDuration || moment.duration(1, 'day'); this.nextDayThreshold = moment.duration(this.opt('nextDayThreshold')); this.initThemingProps(); this.initHiddenDays(); this.documentMousedownProxy = proxy(this, 'documentMousedown'); this.initialize(); }, // A good place for subclasses to initialize member variables initialize: function() { // subclasses can implement }, // Retrieves an option with the given name opt: function(name) { return this.options[name]; }, // Triggers handlers that are view-related. Modifies args before passing to calendar. trigger: function(name, thisObj) { // arguments beyond thisObj are passed along var calendar = this.calendar; return calendar.trigger.apply( calendar, [name, thisObj || this].concat( Array.prototype.slice.call(arguments, 2), // arguments beyond thisObj [ this ] // always make the last argument a reference to the view. TODO: deprecate ) ); }, /* Dates ------------------------------------------------------------------------------------------------------------------*/ // Updates all internal dates to center around the given current date setDate: function(date) { this.setRange(this.computeRange(date)); }, // Updates all internal dates for displaying the given range. // Expects all values to be normalized (like what computeRange does). setRange: function(range) { $.extend(this, range); this.updateTitle(); }, // Given a single current date, produce information about what range to display. // Subclasses can override. Must return all properties. computeRange: function(date) { var intervalUnit = computeIntervalUnit(this.intervalDuration); var intervalStart = date.clone().startOf(intervalUnit); var intervalEnd = intervalStart.clone().add(this.intervalDuration); var start, end; // normalize the range's time-ambiguity if (/year|month|week|day/.test(intervalUnit)) { // whole-days? intervalStart.stripTime(); intervalEnd.stripTime(); } else { // needs to have a time? if (!intervalStart.hasTime()) { intervalStart = this.calendar.rezoneDate(intervalStart); // convert to current timezone, with 00:00 } if (!intervalEnd.hasTime()) { intervalEnd = this.calendar.rezoneDate(intervalEnd); // convert to current timezone, with 00:00 } } start = intervalStart.clone(); start = this.skipHiddenDays(start); end = intervalEnd.clone(); end = this.skipHiddenDays(end, -1, true); // exclusively move backwards return { intervalUnit: intervalUnit, intervalStart: intervalStart, intervalEnd: intervalEnd, start: start, end: end }; }, // Computes the new date when the user hits the prev button, given the current date computePrevDate: function(date) { return this.massageCurrentDate( date.clone().startOf(this.intervalUnit).subtract(this.intervalDuration), -1 ); }, // Computes the new date when the user hits the next button, given the current date computeNextDate: function(date) { return this.massageCurrentDate( date.clone().startOf(this.intervalUnit).add(this.intervalDuration) ); }, // Given an arbitrarily calculated current date of the calendar, returns a date that is ensured to be completely // visible. `direction` is optional and indicates which direction the current date was being // incremented or decremented (1 or -1). massageCurrentDate: function(date, direction) { if (this.intervalDuration.as('days') <= 1) { // if the view displays a single day or smaller if (this.isHiddenDay(date)) { date = this.skipHiddenDays(date, direction); date.startOf('day'); } } return date; }, /* Title and Date Formatting ------------------------------------------------------------------------------------------------------------------*/ // Sets the view's title property to the most updated computed value updateTitle: function() { this.title = this.computeTitle(); }, // Computes what the title at the top of the calendar should be for this view computeTitle: function() { return this.formatRange( { start: this.intervalStart, end: this.intervalEnd }, this.opt('titleFormat') || this.computeTitleFormat(), this.opt('titleRangeSeparator') ); }, // Generates the format string that should be used to generate the title for the current date range. // Attempts to compute the most appropriate format if not explicitly specified with `titleFormat`. computeTitleFormat: function() { if (this.intervalUnit == 'year') { return 'YYYY'; } else if (this.intervalUnit == 'month') { return this.opt('monthYearFormat'); // like "September 2014" } else if (this.intervalDuration.as('days') > 1) { return 'll'; // multi-day range. shorter, like "Sep 9 - 10 2014" } else { return 'LL'; // one day. longer, like "September 9 2014" } }, // Utility for formatting a range. Accepts a range object, formatting string, and optional separator. // Displays all-day ranges naturally, with an inclusive end. Takes the current isRTL into account. formatRange: function(range, formatStr, separator) { var end = range.end; if (!end.hasTime()) { // all-day? end = end.clone().subtract(1); // convert to inclusive. last ms of previous day } return formatRange(range.start, end, formatStr, separator, this.opt('isRTL')); }, /* Rendering ------------------------------------------------------------------------------------------------------------------*/ // Sets the container element that the view should render inside of. // Does other DOM-related initializations. setElement: function(el) { this.el = el; this.bindGlobalHandlers(); }, // Removes the view's container element from the DOM, clearing any content beforehand. // Undoes any other DOM-related attachments. removeElement: function() { this.clear(); // clears all content // clean up the skeleton if (this.isSkeletonRendered) { this.destroySkeleton(); this.isSkeletonRendered = false; } this.unbindGlobalHandlers(); this.el.remove(); // NOTE: don't null-out this.el in case the View was destroyed within an API callback. // We don't null-out the View's other jQuery element references upon destroy, so why should we kill this.el? }, // Does everything necessary to display the view centered around the given date. // Does every type of rendering EXCEPT rendering events. display: function(date) { var scrollState = null; if (this.isDisplayed) { scrollState = this.queryScroll(); } this.clear(); // clear the old content this.setDate(date); this.render(); this.updateSize(); this.renderBusinessHours(); // might need coordinates, so should go after updateSize() this.isDisplayed = true; scrollState = this.computeInitialScroll(scrollState); this.forceScroll(scrollState); this.triggerRender(); }, // Does everything necessary to clear the content of the view. // Clears dates and events. Does not clear the skeleton. clear: function() { // clears the view of *content* but not the skeleton if (this.isDisplayed) { this.unselect(); this.clearEvents(); this.triggerDestroy(); this.destroyBusinessHours(); this.destroy(); this.isDisplayed = false; } }, // Renders the view's date-related content, rendering the view's non-content skeleton if necessary render: function() { if (!this.isSkeletonRendered) { this.renderSkeleton(); this.isSkeletonRendered = true; } this.renderDates(); }, // Unrenders the view's date-related content. // Call this instead of destroyDates directly in case the View subclass wants to use a render/destroy pattern // where both the skeleton and the content always get rendered/unrendered together. destroy: function() { this.destroyDates(); }, // Renders the basic structure of the view before any content is rendered renderSkeleton: function() { // subclasses should implement }, // Unrenders the basic structure of the view destroySkeleton: function() { // subclasses should implement }, // Renders the view's date-related content (like cells that represent days/times). // Assumes setRange has already been called and the skeleton has already been rendered. renderDates: function() { // subclasses should implement }, // Unrenders the view's date-related content destroyDates: function() { // subclasses should override }, // Renders business-hours onto the view. Assumes updateSize has already been called. renderBusinessHours: function() { // subclasses should implement }, // Unrenders previously-rendered business-hours destroyBusinessHours: function() { // subclasses should implement }, // Signals that the view's content has been rendered triggerRender: function() { this.trigger('viewRender', this, this, this.el); }, // Signals that the view's content is about to be unrendered triggerDestroy: function() { this.trigger('viewDestroy', this, this, this.el); }, // Binds DOM handlers to elements that reside outside the view container, such as the document bindGlobalHandlers: function() { $(document).on('mousedown', this.documentMousedownProxy); }, // Unbinds DOM handlers from elements that reside outside the view container unbindGlobalHandlers: function() { $(document).off('mousedown', this.documentMousedownProxy); }, // Initializes internal variables related to theming initThemingProps: function() { var tm = this.opt('theme') ? 'ui' : 'fc'; this.widgetHeaderClass = tm + '-widget-header'; this.widgetContentClass = tm + '-widget-content'; this.highlightStateClass = tm + '-state-highlight'; }, /* Dimensions ------------------------------------------------------------------------------------------------------------------*/ // Refreshes anything dependant upon sizing of the container element of the grid updateSize: function(isResize) { var scrollState; if (isResize) { scrollState = this.queryScroll(); } this.updateHeight(); this.updateWidth(); if (isResize) { this.setScroll(scrollState); } }, // Refreshes the horizontal dimensions of the calendar updateWidth: function() { // subclasses should implement }, // Refreshes the vertical dimensions of the calendar updateHeight: function() { var calendar = this.calendar; // we poll the calendar for height information this.setHeight( calendar.getSuggestedViewHeight(), calendar.isHeightAuto() ); }, // Updates the vertical dimensions of the calendar to the specified height. // if `isAuto` is set to true, height becomes merely a suggestion and the view should use its "natural" height. setHeight: function(height, isAuto) { // subclasses should implement }, /* Scroller ------------------------------------------------------------------------------------------------------------------*/ // Given the total height of the view, return the number of pixels that should be used for the scroller. // Utility for subclasses. computeScrollerHeight: function(totalHeight) { var scrollerEl = this.scrollerEl; var both; var otherHeight; // cumulative height of everything that is not the scrollerEl in the view (header+borders) both = this.el.add(scrollerEl); // fuckin IE8/9/10/11 sometimes returns 0 for dimensions. this weird hack was the only thing that worked both.css({ position: 'relative', // cause a reflow, which will force fresh dimension recalculation left: -1 // ensure reflow in case the el was already relative. negative is less likely to cause new scroll }); otherHeight = this.el.outerHeight() - scrollerEl.height(); // grab the dimensions both.css({ position: '', left: '' }); // undo hack return totalHeight - otherHeight; }, // Computes the initial pre-configured scroll state prior to allowing the user to change it. // Given the scroll state from the previous rendering. If first time rendering, given null. computeInitialScroll: function(previousScrollState) { return 0; }, // Retrieves the view's current natural scroll state. Can return an arbitrary format. queryScroll: function() { if (this.scrollerEl) { return this.scrollerEl.scrollTop(); // operates on scrollerEl by default } }, // Sets the view's scroll state. Will accept the same format computeInitialScroll and queryScroll produce. setScroll: function(scrollState) { if (this.scrollerEl) { return this.scrollerEl.scrollTop(scrollState); // operates on scrollerEl by default } }, // Sets the scroll state, making sure to overcome any predefined scroll value the browser has in mind forceScroll: function(scrollState) { var _this = this; this.setScroll(scrollState); setTimeout(function() { _this.setScroll(scrollState); }, 0); }, /* Event Elements / Segments ------------------------------------------------------------------------------------------------------------------*/ // Does everything necessary to display the given events onto the current view displayEvents: function(events) { var scrollState = this.queryScroll(); this.clearEvents(); this.renderEvents(events); this.isEventsRendered = true; this.setScroll(scrollState); this.triggerEventRender(); }, // Does everything necessary to clear the view's currently-rendered events clearEvents: function() { if (this.isEventsRendered) { this.triggerEventDestroy(); this.destroyEvents(); this.isEventsRendered = false; } }, // Renders the events onto the view. renderEvents: function(events) { // subclasses should implement }, // Removes event elements from the view. destroyEvents: function() { // subclasses should implement }, // Signals that all events have been rendered triggerEventRender: function() { this.renderedEventSegEach(function(seg) { this.trigger('eventAfterRender', seg.event, seg.event, seg.el); }); this.trigger('eventAfterAllRender'); }, // Signals that all event elements are about to be removed triggerEventDestroy: function() { this.renderedEventSegEach(function(seg) { this.trigger('eventDestroy', seg.event, seg.event, seg.el); }); }, // Given an event and the default element used for rendering, returns the element that should actually be used. // Basically runs events and elements through the eventRender hook. resolveEventEl: function(event, el) { var custom = this.trigger('eventRender', event, event, el); if (custom === false) { // means don't render at all el = null; } else if (custom && custom !== true) { el = $(custom); } return el; }, // Hides all rendered event segments linked to the given event showEvent: function(event) { this.renderedEventSegEach(function(seg) { seg.el.css('visibility', ''); }, event); }, // Shows all rendered event segments linked to the given event hideEvent: function(event) { this.renderedEventSegEach(function(seg) { seg.el.css('visibility', 'hidden'); }, event); }, // Iterates through event segments that have been rendered (have an el). Goes through all by default. // If the optional `event` argument is specified, only iterates through segments linked to that event. // The `this` value of the callback function will be the view. renderedEventSegEach: function(func, event) { var segs = this.getEventSegs(); var i; for (i = 0; i < segs.length; i++) { if (!event || segs[i].event._id === event._id) { if (segs[i].el) { func.call(this, segs[i]); } } } }, // Retrieves all the rendered segment objects for the view getEventSegs: function() { // subclasses must implement return []; }, /* Event Drag-n-Drop ------------------------------------------------------------------------------------------------------------------*/ // Computes if the given event is allowed to be dragged by the user isEventDraggable: function(event) { var source = event.source || {}; return firstDefined( event.startEditable, source.startEditable, this.opt('eventStartEditable'), event.editable, source.editable, this.opt('editable') ); }, // Must be called when an event in the view is dropped onto new location. // `dropLocation` is an object that contains the new start/end/allDay values for the event. reportEventDrop: function(event, dropLocation, largeUnit, el, ev) { var calendar = this.calendar; var mutateResult = calendar.mutateEvent(event, dropLocation, largeUnit); var undoFunc = function() { mutateResult.undo(); calendar.reportEventChange(); }; this.triggerEventDrop(event, mutateResult.dateDelta, undoFunc, el, ev); calendar.reportEventChange(); // will rerender events }, // Triggers event-drop handlers that have subscribed via the API triggerEventDrop: function(event, dateDelta, undoFunc, el, ev) { this.trigger('eventDrop', el[0], event, dateDelta, undoFunc, ev, {}); // {} = jqui dummy }, /* External Element Drag-n-Drop ------------------------------------------------------------------------------------------------------------------*/ // Must be called when an external element, via jQuery UI, has been dropped onto the calendar. // `meta` is the parsed data that has been embedded into the dragging event. // `dropLocation` is an object that contains the new start/end/allDay values for the event. reportExternalDrop: function(meta, dropLocation, el, ev, ui) { var eventProps = meta.eventProps; var eventInput; var event; // Try to build an event object and render it. TODO: decouple the two if (eventProps) { eventInput = $.extend({}, eventProps, dropLocation); event = this.calendar.renderEvent(eventInput, meta.stick)[0]; // renderEvent returns an array } this.triggerExternalDrop(event, dropLocation, el, ev, ui); }, // Triggers external-drop handlers that have subscribed via the API triggerExternalDrop: function(event, dropLocation, el, ev, ui) { // trigger 'drop' regardless of whether element represents an event this.trigger('drop', el[0], dropLocation.start, ev, ui); if (event) { this.trigger('eventReceive', null, event); // signal an external event landed } }, /* Drag-n-Drop Rendering (for both events and external elements) ------------------------------------------------------------------------------------------------------------------*/ // Renders a visual indication of a event or external-element drag over the given drop zone. // If an external-element, seg will be `null` renderDrag: function(dropLocation, seg) { // subclasses must implement }, // Unrenders a visual indication of an event or external-element being dragged. destroyDrag: function() { // subclasses must implement }, /* Event Resizing ------------------------------------------------------------------------------------------------------------------*/ // Computes if the given event is allowed to be resized from its starting edge isEventResizableFromStart: function(event) { return this.opt('eventResizableFromStart') && this.isEventResizable(event); }, // Computes if the given event is allowed to be resized from its ending edge isEventResizableFromEnd: function(event) { return this.isEventResizable(event); }, // Computes if the given event is allowed to be resized by the user at all isEventResizable: function(event) { var source = event.source || {}; return firstDefined( event.durationEditable, source.durationEditable, this.opt('eventDurationEditable'), event.editable, source.editable, this.opt('editable') ); }, // Must be called when an event in the view has been resized to a new length reportEventResize: function(event, resizeLocation, largeUnit, el, ev) { var calendar = this.calendar; var mutateResult = calendar.mutateEvent(event, resizeLocation, largeUnit); var undoFunc = function() { mutateResult.undo(); calendar.reportEventChange(); }; this.triggerEventResize(event, mutateResult.durationDelta, undoFunc, el, ev); calendar.reportEventChange(); // will rerender events }, // Triggers event-resize handlers that have subscribed via the API triggerEventResize: function(event, durationDelta, undoFunc, el, ev) { this.trigger('eventResize', el[0], event, durationDelta, undoFunc, ev, {}); // {} = jqui dummy }, /* Selection ------------------------------------------------------------------------------------------------------------------*/ // Selects a date range on the view. `start` and `end` are both Moments. // `ev` is the native mouse event that begin the interaction. select: function(range, ev) { this.unselect(ev); this.renderSelection(range); this.reportSelection(range, ev); }, // Renders a visual indication of the selection renderSelection: function(range) { // subclasses should implement }, // Called when a new selection is made. Updates internal state and triggers handlers. reportSelection: function(range, ev) { this.isSelected = true; this.trigger('select', null, range.start, range.end, ev); }, // Undoes a selection. updates in the internal state and triggers handlers. // `ev` is the native mouse event that began the interaction. unselect: function(ev) { if (this.isSelected) { this.isSelected = false; this.destroySelection(); this.trigger('unselect', null, ev); } }, // Unrenders a visual indication of selection destroySelection: function() { // subclasses should implement }, // Handler for unselecting when the user clicks something and the 'unselectAuto' setting is on documentMousedown: function(ev) { var ignore; // is there a selection, and has the user made a proper left click? if (this.isSelected && this.opt('unselectAuto') && isPrimaryMouseButton(ev)) { // only unselect if the clicked element is not identical to or inside of an 'unselectCancel' element ignore = this.opt('unselectCancel'); if (!ignore || !$(ev.target).closest(ignore).length) { this.unselect(ev); } } }, /* Date Utils ------------------------------------------------------------------------------------------------------------------*/ // Initializes internal variables related to calculating hidden days-of-week initHiddenDays: function() { var hiddenDays = this.opt('hiddenDays') || []; // array of day-of-week indices that are hidden var isHiddenDayHash = []; // is the day-of-week hidden? (hash with day-of-week-index -> bool) var dayCnt = 0; var i; if (this.opt('weekends') === false) { hiddenDays.push(0, 6); // 0=sunday, 6=saturday } for (i = 0; i < 7; i++) { if ( !(isHiddenDayHash[i] = $.inArray(i, hiddenDays) !== -1) ) { dayCnt++; } } if (!dayCnt) { throw 'invalid hiddenDays'; // all days were hidden? bad. } this.isHiddenDayHash = isHiddenDayHash; }, // Is the current day hidden? // `day` is a day-of-week index (0-6), or a Moment isHiddenDay: function(day) { if (moment.isMoment(day)) { day = day.day(); } return this.isHiddenDayHash[day]; }, // Incrementing the current day until it is no longer a hidden day, returning a copy. // If the initial value of `date` is not a hidden day, don't do anything. // Pass `isExclusive` as `true` if you are dealing with an end date. // `inc` defaults to `1` (increment one day forward each time) skipHiddenDays: function(date, inc, isExclusive) { var out = date.clone(); inc = inc || 1; while ( this.isHiddenDayHash[(out.day() + (isExclusive ? inc : 0) + 7) % 7] ) { out.add(inc, 'days'); } return out; }, // Returns the date range of the full days the given range visually appears to occupy. // Returns a new range object. computeDayRange: function(range) { var startDay = range.start.clone().stripTime(); // the beginning of the day the range starts var end = range.end; var endDay = null; var endTimeMS; if (end) { endDay = end.clone().stripTime(); // the beginning of the day the range exclusively ends endTimeMS = +end.time(); // # of milliseconds into `endDay` // If the end time is actually inclusively part of the next day and is equal to or // beyond the next day threshold, adjust the end to be the exclusive end of `endDay`. // Otherwise, leaving it as inclusive will cause it to exclude `endDay`. if (endTimeMS && endTimeMS >= this.nextDayThreshold) { endDay.add(1, 'days'); } } // If no end was specified, or if it is within `startDay` but not past nextDayThreshold, // assign the default duration of one day. if (!end || endDay <= startDay) { endDay = startDay.clone().add(1, 'days'); } return { start: startDay, end: endDay }; }, // Does the given event visually appear to occupy more than one day? isMultiDayEvent: function(event) { var range = this.computeDayRange(event); // event is range-ish return range.end.diff(range.start, 'days') > 1; } }); ;; var Calendar = fc.Calendar = fc.CalendarBase = Class.extend({ dirDefaults: null, // option defaults related to LTR or RTL langDefaults: null, // option defaults related to current locale overrides: null, // option overrides given to the fullCalendar constructor options: null, // all defaults combined with overrides viewSpecCache: null, // cache of view definitions view: null, // current View object header: null, // a lot of this class' OOP logic is scoped within this constructor function, // but in the future, write individual methods on the prototype. constructor: Calendar_constructor, // Initializes `this.options` and other important options-related objects initOptions: function(overrides) { var lang, langDefaults; var isRTL, dirDefaults; // converts legacy options into non-legacy ones. // in the future, when this is removed, don't use `overrides` reference. make a copy. overrides = massageOverrides(overrides); lang = overrides.lang; langDefaults = langOptionHash[lang]; if (!langDefaults) { lang = Calendar.defaults.lang; langDefaults = langOptionHash[lang] || {}; } isRTL = firstDefined( overrides.isRTL, langDefaults.isRTL, Calendar.defaults.isRTL ); dirDefaults = isRTL ? Calendar.rtlDefaults : {}; this.dirDefaults = dirDefaults; this.langDefaults = langDefaults; this.overrides = overrides; this.options = mergeOptions( // merge defaults and overrides. lowest to highest precedence Calendar.defaults, // global defaults dirDefaults, langDefaults, overrides ); populateInstanceComputableOptions(this.options); this.viewSpecCache = {}; // somewhat unrelated }, // Gets information about how to create a view. Will use a cache. getViewSpec: function(viewType) { var cache = this.viewSpecCache; return cache[viewType] || (cache[viewType] = this.buildViewSpec(viewType)); }, // Given a duration singular unit, like "week" or "day", finds a matching view spec. // Preference is given to views that have corresponding buttons. getUnitViewSpec: function(unit) { var viewTypes; var i; var spec; if ($.inArray(unit, intervalUnits) != -1) { // put views that have buttons first. there will be duplicates, but oh well viewTypes = this.header.getViewsWithButtons(); $.each(fc.views, function(viewType) { // all views viewTypes.push(viewType); }); for (i = 0; i < viewTypes.length; i++) { spec = this.getViewSpec(viewTypes[i]); if (spec) { if (spec.singleUnit == unit) { return spec; } } } } }, // Builds an object with information on how to create a given view buildViewSpec: function(requestedViewType) { var viewOverrides = this.overrides.views || {}; var defaultsChain = []; // for the view. lowest to highest priority var overridesChain = []; // for the view. lowest to highest priority var viewType = requestedViewType; var viewClass; var defaults; // for the view var overrides; // for the view var duration; var unit; var spec; // iterate from the specific view definition to a more general one until we hit an actual View class while (viewType && !viewClass) { defaults = fcViews[viewType] || {}; overrides = viewOverrides[viewType] || {}; duration = duration || overrides.duration || defaults.duration; viewType = overrides.type || defaults.type; // for next iteration if (typeof defaults === 'function') { // a class viewClass = defaults; defaultsChain.unshift(viewClass.defaults || {}); } else { // an options object defaultsChain.unshift(defaults); } overridesChain.unshift(overrides); } if (viewClass) { spec = { 'class': viewClass, type: requestedViewType }; if (duration) { duration = moment.duration(duration); if (!duration.valueOf()) { // invalid? duration = null; } } if (duration) { spec.duration = duration; unit = computeIntervalUnit(duration); // view is a single-unit duration, like "week" or "day" // incorporate options for this. lowest priority if (duration.as(unit) === 1) { spec.singleUnit = unit; overridesChain.unshift(viewOverrides[unit] || {}); } } // collapse into single objects spec.defaults = mergeOptions.apply(null, defaultsChain); spec.overrides = mergeOptions.apply(null, overridesChain); this.buildViewSpecOptions(spec); this.buildViewSpecButtonText(spec, requestedViewType); return spec; } }, // Builds and assigns a view spec's options object from its already-assigned defaults and overrides buildViewSpecOptions: function(spec) { spec.options = mergeOptions( // lowest to highest priority Calendar.defaults, // global defaults spec.defaults, // view's defaults (from ViewSubclass.defaults) this.dirDefaults, this.langDefaults, // locale and dir take precedence over view's defaults! this.overrides, // calendar's overrides (options given to constructor) spec.overrides // view's overrides (view-specific options) ); populateInstanceComputableOptions(spec.options); }, // Computes and assigns a view spec's buttonText-related options buildViewSpecButtonText: function(spec, requestedViewType) { // given an options object with a possible `buttonText` hash, lookup the buttonText for the // requested view, falling back to a generic unit entry like "week" or "day" function queryButtonText(options) { var buttonText = options.buttonText || {}; return buttonText[requestedViewType] || (spec.singleUnit ? buttonText[spec.singleUnit] : null); } // highest to lowest priority spec.buttonTextOverride = queryButtonText(this.overrides) || // constructor-specified buttonText lookup hash takes precedence spec.overrides.buttonText; // `buttonText` for view-specific options is a string // highest to lowest priority. mirrors buildViewSpecOptions spec.buttonTextDefault = queryButtonText(this.langDefaults) || queryButtonText(this.dirDefaults) || spec.defaults.buttonText || // a single string. from ViewSubclass.defaults queryButtonText(Calendar.defaults) || (spec.duration ? this.humanizeDuration(spec.duration) : null) || // like "3 days" requestedViewType; // fall back to given view name }, // Given a view name for a custom view or a standard view, creates a ready-to-go View object instantiateView: function(viewType) { var spec = this.getViewSpec(viewType); return new spec['class'](this, viewType, spec.options, spec.duration); }, // Returns a boolean about whether the view is okay to instantiate at some point isValidViewType: function(viewType) { return Boolean(this.getViewSpec(viewType)); } }); function Calendar_constructor(element, overrides) { var t = this; t.initOptions(overrides || {}); var options = this.options; // Exports // ----------------------------------------------------------------------------------- t.render = render; t.destroy = destroy; t.refetchEvents = refetchEvents; t.reportEvents = reportEvents; t.reportEventChange = reportEventChange; t.rerenderEvents = renderEvents; // `renderEvents` serves as a rerender. an API method t.changeView = renderView; // `renderView` will switch to another view t.select = select; t.unselect = unselect; t.prev = prev; t.next = next; t.prevYear = prevYear; t.nextYear = nextYear; t.today = today; t.gotoDate = gotoDate; t.incrementDate = incrementDate; t.zoomTo = zoomTo; t.getDate = getDate; t.getCalendar = getCalendar; t.getView = getView; t.option = option; t.trigger = trigger; // Language-data Internals // ----------------------------------------------------------------------------------- // Apply overrides to the current language's data var localeData = createObject( // make a cheap copy getMomentLocaleData(options.lang) // will fall back to en ); if (options.monthNames) { localeData._months = options.monthNames; } if (options.monthNamesShort) { localeData._monthsShort = options.monthNamesShort; } if (options.dayNames) { localeData._weekdays = options.dayNames; } if (options.dayNamesShort) { localeData._weekdaysShort = options.dayNamesShort; } if (options.firstDay != null) { var _week = createObject(localeData._week); // _week: { dow: # } _week.dow = options.firstDay; localeData._week = _week; } // assign a normalized value, to be used by our .week() moment extension localeData._fullCalendar_weekCalc = (function(weekCalc) { if (typeof weekCalc === 'function') { return weekCalc; } else if (weekCalc === 'local') { return weekCalc; } else if (weekCalc === 'iso' || weekCalc === 'ISO') { return 'ISO'; } })(options.weekNumberCalculation); // Calendar-specific Date Utilities // ----------------------------------------------------------------------------------- t.defaultAllDayEventDuration = moment.duration(options.defaultAllDayEventDuration); t.defaultTimedEventDuration = moment.duration(options.defaultTimedEventDuration); // Builds a moment using the settings of the current calendar: timezone and language. // Accepts anything the vanilla moment() constructor accepts. t.moment = function() { var mom; if (options.timezone === 'local') { mom = fc.moment.apply(null, arguments); // Force the moment to be local, because fc.moment doesn't guarantee it. if (mom.hasTime()) { // don't give ambiguously-timed moments a local zone mom.local(); } } else if (options.timezone === 'UTC') { mom = fc.moment.utc.apply(null, arguments); // process as UTC } else { mom = fc.moment.parseZone.apply(null, arguments); // let the input decide the zone } if ('_locale' in mom) { // moment 2.8 and above mom._locale = localeData; } else { // pre-moment-2.8 mom._lang = localeData; } return mom; }; // Returns a boolean about whether or not the calendar knows how to calculate // the timezone offset of arbitrary dates in the current timezone. t.getIsAmbigTimezone = function() { return options.timezone !== 'local' && options.timezone !== 'UTC'; }; // Returns a copy of the given date in the current timezone of it is ambiguously zoned. // This will also give the date an unambiguous time. t.rezoneDate = function(date) { return t.moment(date.toArray()); }; // Returns a moment for the current date, as defined by the client's computer, // or overridden by the `now` option. t.getNow = function() { var now = options.now; if (typeof now === 'function') { now = now(); } return t.moment(now); }; // Get an event's normalized end date. If not present, calculate it from the defaults. t.getEventEnd = function(event) { if (event.end) { return event.end.clone(); } else { return t.getDefaultEventEnd(event.allDay, event.start); } }; // Given an event's allDay status and start date, return swhat its fallback end date should be. t.getDefaultEventEnd = function(allDay, start) { // TODO: rename to computeDefaultEventEnd var end = start.clone(); if (allDay) { end.stripTime().add(t.defaultAllDayEventDuration); } else { end.add(t.defaultTimedEventDuration); } if (t.getIsAmbigTimezone()) { end.stripZone(); // we don't know what the tzo should be } return end; }; // Produces a human-readable string for the given duration. // Side-effect: changes the locale of the given duration. t.humanizeDuration = function(duration) { return (duration.locale || duration.lang).call(duration, options.lang) // works moment-pre-2.8 .humanize(); }; // Imports // ----------------------------------------------------------------------------------- EventManager.call(t, options); var isFetchNeeded = t.isFetchNeeded; var fetchEvents = t.fetchEvents; // Locals // ----------------------------------------------------------------------------------- var _element = element[0]; var header; var headerElement; var content; var tm; // for making theme classes var currentView; // NOTE: keep this in sync with this.view var viewsByType = {}; // holds all instantiated view instances, current or not var suggestedViewHeight; var windowResizeProxy; // wraps the windowResize function var ignoreWindowResize = 0; var date; var events = []; // Main Rendering // ----------------------------------------------------------------------------------- if (options.defaultDate != null) { date = t.moment(options.defaultDate); } else { date = t.getNow(); } function render() { if (!content) { initialRender(); } else if (elementVisible()) { // mainly for the public API calcSize(); renderView(); } } function initialRender() { tm = options.theme ? 'ui' : 'fc'; element.addClass('fc'); if (options.isRTL) { element.addClass('fc-rtl'); } else { element.addClass('fc-ltr'); } if (options.theme) { element.addClass('ui-widget'); } else { element.addClass('fc-unthemed'); } content = $("<div class='fc-view-container'/>").prependTo(element); header = t.header = new Header(t, options); headerElement = header.render(); if (headerElement) { element.prepend(headerElement); } renderView(options.defaultView); if (options.handleWindowResize) { windowResizeProxy = debounce(windowResize, options.windowResizeDelay); // prevents rapid calls $(window).resize(windowResizeProxy); } } function destroy() { if (currentView) { currentView.removeElement(); // NOTE: don't null-out currentView/t.view in case API methods are called after destroy. // It is still the "current" view, just not rendered. } header.destroy(); content.remove(); element.removeClass('fc fc-ltr fc-rtl fc-unthemed ui-widget'); if (windowResizeProxy) { $(window).unbind('resize', windowResizeProxy); } } function elementVisible() { return element.is(':visible'); } // View Rendering // ----------------------------------------------------------------------------------- // Renders a view because of a date change, view-type change, or for the first time. // If not given a viewType, keep the current view but render different dates. function renderView(viewType) { ignoreWindowResize++; // if viewType is changing, destroy the old view if (currentView && viewType && currentView.type !== viewType) { header.deactivateButton(currentView.type); freezeContentHeight(); // prevent a scroll jump when view element is removed currentView.removeElement(); currentView = t.view = null; } // if viewType changed, or the view was never created, create a fresh view if (!currentView && viewType) { currentView = t.view = viewsByType[viewType] || (viewsByType[viewType] = t.instantiateView(viewType)); currentView.setElement( $("<div class='fc-view fc-" + viewType + "-view' />").appendTo(content) ); header.activateButton(viewType); } if (currentView) { // in case the view should render a period of time that is completely hidden date = currentView.massageCurrentDate(date); // render or rerender the view if ( !currentView.isDisplayed || !date.isWithin(currentView.intervalStart, currentView.intervalEnd) // implicit date window change ) { if (elementVisible()) { freezeContentHeight(); currentView.display(date); unfreezeContentHeight(); // need to do this after View::render, so dates are calculated updateHeaderTitle(); updateTodayButton(); getAndRenderEvents(); } } } unfreezeContentHeight(); // undo any lone freezeContentHeight calls ignoreWindowResize--; } // Resizing // ----------------------------------------------------------------------------------- t.getSuggestedViewHeight = function() { if (suggestedViewHeight === undefined) { calcSize(); } return suggestedViewHeight; }; t.isHeightAuto = function() { return options.contentHeight === 'auto' || options.height === 'auto'; }; function updateSize(shouldRecalc) { if (elementVisible()) { if (shouldRecalc) { _calcSize(); } ignoreWindowResize++; currentView.updateSize(true); // isResize=true. will poll getSuggestedViewHeight() and isHeightAuto() ignoreWindowResize--; return true; // signal success } } function calcSize() { if (elementVisible()) { _calcSize(); } } function _calcSize() { // assumes elementVisible if (typeof options.contentHeight === 'number') { // exists and not 'auto' suggestedViewHeight = options.contentHeight; } else if (typeof options.height === 'number') { // exists and not 'auto' suggestedViewHeight = options.height - (headerElement ? headerElement.outerHeight(true) : 0); } else { suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5)); } } function windowResize(ev) { if ( !ignoreWindowResize && ev.target === window && // so we don't process jqui "resize" events that have bubbled up currentView.start // view has already been rendered ) { if (updateSize(true)) { currentView.trigger('windowResize', _element); } } } /* Event Fetching/Rendering -----------------------------------------------------------------------------*/ // TODO: going forward, most of this stuff should be directly handled by the view function refetchEvents() { // can be called as an API method destroyEvents(); // so that events are cleared before user starts waiting for AJAX fetchAndRenderEvents(); } function renderEvents() { // destroys old events if previously rendered if (elementVisible()) { freezeContentHeight(); currentView.displayEvents(events); unfreezeContentHeight(); } } function destroyEvents() { freezeContentHeight(); currentView.clearEvents(); unfreezeContentHeight(); } function getAndRenderEvents() { if (!options.lazyFetching || isFetchNeeded(currentView.start, currentView.end)) { fetchAndRenderEvents(); } else { renderEvents(); } } function fetchAndRenderEvents() { fetchEvents(currentView.start, currentView.end); // ... will call reportEvents // ... which will call renderEvents } // called when event data arrives function reportEvents(_events) { events = _events; renderEvents(); } // called when a single event's data has been changed function reportEventChange() { renderEvents(); } /* Header Updating -----------------------------------------------------------------------------*/ function updateHeaderTitle() { header.updateTitle(currentView.title); } function updateTodayButton() { var now = t.getNow(); if (now.isWithin(currentView.intervalStart, currentView.intervalEnd)) { header.disableButton('today'); } else { header.enableButton('today'); } } /* Selection -----------------------------------------------------------------------------*/ function select(start, end) { start = t.moment(start); if (end) { end = t.moment(end); } else if (start.hasTime()) { end = start.clone().add(t.defaultTimedEventDuration); } else { end = start.clone().add(t.defaultAllDayEventDuration); } currentView.select({ start: start, end: end }); // accepts a range } function unselect() { // safe to be called before renderView if (currentView) { currentView.unselect(); } } /* Date -----------------------------------------------------------------------------*/ function prev() { date = currentView.computePrevDate(date); renderView(); } function next() { date = currentView.computeNextDate(date); renderView(); } function prevYear() { date.add(-1, 'years'); renderView(); } function nextYear() { date.add(1, 'years'); renderView(); } function today() { date = t.getNow(); renderView(); } function gotoDate(dateInput) { date = t.moment(dateInput); renderView(); } function incrementDate(delta) { date.add(moment.duration(delta)); renderView(); } // Forces navigation to a view for the given date. // `viewType` can be a specific view name or a generic one like "week" or "day". function zoomTo(newDate, viewType) { var spec; viewType = viewType || 'day'; // day is default zoom spec = t.getViewSpec(viewType) || t.getUnitViewSpec(viewType); date = newDate; renderView(spec ? spec.type : null); } function getDate() { return date.clone(); } /* Height "Freezing" -----------------------------------------------------------------------------*/ // TODO: move this into the view function freezeContentHeight() { content.css({ width: '100%', height: content.height(), overflow: 'hidden' }); } function unfreezeContentHeight() { content.css({ width: '', height: '', overflow: '' }); } /* Misc -----------------------------------------------------------------------------*/ function getCalendar() { return t; } function getView() { return currentView; } function option(name, value) { if (value === undefined) { return options[name]; } if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') { options[name] = value; updateSize(true); // true = allow recalculation of height } } function trigger(name, thisObj) { if (options[name]) { return options[name].apply( thisObj || _element, Array.prototype.slice.call(arguments, 2) ); } } } ;; Calendar.defaults = { titleRangeSeparator: ' \u2014 ', // emphasized dash monthYearFormat: 'MMMM YYYY', // required for en. other languages rely on datepicker computable option defaultTimedEventDuration: '02:00:00', defaultAllDayEventDuration: { days: 1 }, forceEventDuration: false, nextDayThreshold: '09:00:00', // 9am // display defaultView: 'month', aspectRatio: 1.35, header: { left: 'title', center: '', right: 'today prev,next' }, weekends: true, weekNumbers: false, weekNumberTitle: 'W', weekNumberCalculation: 'local', //editable: false, // event ajax lazyFetching: true, startParam: 'start', endParam: 'end', timezoneParam: 'timezone', timezone: false, //allDayDefault: undefined, // locale isRTL: false, buttonText: { prev: "prev", next: "next", prevYear: "prev year", nextYear: "next year", year: 'year', // TODO: locale files need to specify this today: 'today', month: 'month', week: 'week', day: 'day' }, buttonIcons: { prev: 'left-single-arrow', next: 'right-single-arrow', prevYear: 'left-double-arrow', nextYear: 'right-double-arrow' }, // jquery-ui theming theme: false, themeButtonIcons: { prev: 'circle-triangle-w', next: 'circle-triangle-e', prevYear: 'seek-prev', nextYear: 'seek-next' }, //eventResizableFromStart: false, dragOpacity: .75, dragRevertDuration: 500, dragScroll: true, //selectable: false, unselectAuto: true, dropAccept: '*', eventLimit: false, eventLimitText: 'more', eventLimitClick: 'popover', dayPopoverFormat: 'LL', handleWindowResize: true, windowResizeDelay: 200 // milliseconds before an updateSize happens }; Calendar.englishDefaults = { // used by lang.js dayPopoverFormat: 'dddd, MMMM D' }; Calendar.rtlDefaults = { // right-to-left defaults header: { // TODO: smarter solution (first/center/last ?) left: 'next,prev today', center: '', right: 'title' }, buttonIcons: { prev: 'right-single-arrow', next: 'left-single-arrow', prevYear: 'right-double-arrow', nextYear: 'left-double-arrow' }, themeButtonIcons: { prev: 'circle-triangle-e', next: 'circle-triangle-w', nextYear: 'seek-prev', prevYear: 'seek-next' } }; ;; var langOptionHash = fc.langs = {}; // initialize and expose // TODO: document the structure and ordering of a FullCalendar lang file // TODO: rename everything "lang" to "locale", like what the moment project did // Initialize jQuery UI datepicker translations while using some of the translations // Will set this as the default language for datepicker. fc.datepickerLang = function(langCode, dpLangCode, dpOptions) { // get the FullCalendar internal option hash for this language. create if necessary var fcOptions = langOptionHash[langCode] || (langOptionHash[langCode] = {}); // transfer some simple options from datepicker to fc fcOptions.isRTL = dpOptions.isRTL; fcOptions.weekNumberTitle = dpOptions.weekHeader; // compute some more complex options from datepicker $.each(dpComputableOptions, function(name, func) { fcOptions[name] = func(dpOptions); }); // is jQuery UI Datepicker is on the page? if ($.datepicker) { // Register the language data. // FullCalendar and MomentJS use language codes like "pt-br" but Datepicker // does it like "pt-BR" or if it doesn't have the language, maybe just "pt". // Make an alias so the language can be referenced either way. $.datepicker.regional[dpLangCode] = $.datepicker.regional[langCode] = // alias dpOptions; // Alias 'en' to the default language data. Do this every time. $.datepicker.regional.en = $.datepicker.regional['']; // Set as Datepicker's global defaults. $.datepicker.setDefaults(dpOptions); } }; // Sets FullCalendar-specific translations. Will set the language as the global default. fc.lang = function(langCode, newFcOptions) { var fcOptions; var momOptions; // get the FullCalendar internal option hash for this language. create if necessary fcOptions = langOptionHash[langCode] || (langOptionHash[langCode] = {}); // provided new options for this language? merge them in if (newFcOptions) { fcOptions = langOptionHash[langCode] = mergeOptions(fcOptions, newFcOptions); } // compute language options that weren't defined. // always do this. newFcOptions can be undefined when initializing from i18n file, // so no way to tell if this is an initialization or a default-setting. momOptions = getMomentLocaleData(langCode); // will fall back to en $.each(momComputableOptions, function(name, func) { if (fcOptions[name] == null) { fcOptions[name] = func(momOptions, fcOptions); } }); // set it as the default language for FullCalendar Calendar.defaults.lang = langCode; }; // NOTE: can't guarantee any of these computations will run because not every language has datepicker // configs, so make sure there are English fallbacks for these in the defaults file. var dpComputableOptions = { buttonText: function(dpOptions) { return { // the translations sometimes wrongly contain HTML entities prev: stripHtmlEntities(dpOptions.prevText), next: stripHtmlEntities(dpOptions.nextText), today: stripHtmlEntities(dpOptions.currentText) }; }, // Produces format strings like "MMMM YYYY" -> "September 2014" monthYearFormat: function(dpOptions) { return dpOptions.showMonthAfterYear ? 'YYYY[' + dpOptions.yearSuffix + '] MMMM' : 'MMMM YYYY[' + dpOptions.yearSuffix + ']'; } }; var momComputableOptions = { // Produces format strings like "ddd M/D" -> "Fri 9/15" dayOfMonthFormat: function(momOptions, fcOptions) { var format = momOptions.longDateFormat('l'); // for the format like "M/D/YYYY" // strip the year off the edge, as well as other misc non-whitespace chars format = format.replace(/^Y+[^\w\s]*|[^\w\s]*Y+$/g, ''); if (fcOptions.isRTL) { format += ' ddd'; // for RTL, add day-of-week to end } else { format = 'ddd ' + format; // for LTR, add day-of-week to beginning } return format; }, // Produces format strings like "h:mma" -> "6:00pm" mediumTimeFormat: function(momOptions) { // can't be called `timeFormat` because collides with option return momOptions.longDateFormat('LT') .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand }, // Produces format strings like "h(:mm)a" -> "6pm" / "6:30pm" smallTimeFormat: function(momOptions) { return momOptions.longDateFormat('LT') .replace(':mm', '(:mm)') .replace(/(\Wmm)$/, '($1)') // like above, but for foreign langs .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand }, // Produces format strings like "h(:mm)t" -> "6p" / "6:30p" extraSmallTimeFormat: function(momOptions) { return momOptions.longDateFormat('LT') .replace(':mm', '(:mm)') .replace(/(\Wmm)$/, '($1)') // like above, but for foreign langs .replace(/\s*a$/i, 't'); // convert to AM/PM/am/pm to lowercase one-letter. remove any spaces beforehand }, // Produces format strings like "ha" / "H" -> "6pm" / "18" hourFormat: function(momOptions) { return momOptions.longDateFormat('LT') .replace(':mm', '') .replace(/(\Wmm)$/, '') // like above, but for foreign langs .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand }, // Produces format strings like "h:mm" -> "6:30" (with no AM/PM) noMeridiemTimeFormat: function(momOptions) { return momOptions.longDateFormat('LT') .replace(/\s*a$/i, ''); // remove trailing AM/PM } }; // options that should be computed off live calendar options (considers override options) var instanceComputableOptions = { // TODO: best place for this? related to lang? // Produces format strings for results like "Mo 16" smallDayDateFormat: function(options) { return options.isRTL ? 'D dd' : 'dd D'; }, // Produces format strings for results like "Wk 5" weekFormat: function(options) { return options.isRTL ? 'w[ ' + options.weekNumberTitle + ']' : '[' + options.weekNumberTitle + ' ]w'; }, // Produces format strings for results like "Wk5" smallWeekFormat: function(options) { return options.isRTL ? 'w[' + options.weekNumberTitle + ']' : '[' + options.weekNumberTitle + ']w'; } }; function populateInstanceComputableOptions(options) { $.each(instanceComputableOptions, function(name, func) { if (options[name] == null) { options[name] = func(options); } }); } // Returns moment's internal locale data. If doesn't exist, returns English. // Works with moment-pre-2.8 function getMomentLocaleData(langCode) { var func = moment.localeData || moment.langData; return func.call(moment, langCode) || func.call(moment, 'en'); // the newer localData could return null, so fall back to en } // Initialize English by forcing computation of moment-derived options. // Also, sets it as the default. fc.lang('en', Calendar.englishDefaults); ;; /* Top toolbar area with buttons and title ----------------------------------------------------------------------------------------------------------------------*/ // TODO: rename all header-related things to "toolbar" function Header(calendar, options) { var t = this; // exports t.render = render; t.destroy = destroy; t.updateTitle = updateTitle; t.activateButton = activateButton; t.deactivateButton = deactivateButton; t.disableButton = disableButton; t.enableButton = enableButton; t.getViewsWithButtons = getViewsWithButtons; // locals var el = $(); var viewsWithButtons = []; var tm; function render() { var sections = options.header; tm = options.theme ? 'ui' : 'fc'; if (sections) { el = $("<div class='fc-toolbar'/>") .append(renderSection('left')) .append(renderSection('right')) .append(renderSection('center')) .append('<div class="fc-clear"/>'); return el; } } function destroy() { el.remove(); } function renderSection(position) { var sectionEl = $('<div class="fc-' + position + '"/>'); var buttonStr = options.header[position]; if (buttonStr) { $.each(buttonStr.split(' '), function(i) { var groupChildren = $(); var isOnlyButtons = true; var groupEl; $.each(this.split(','), function(j, buttonName) { var viewSpec; var buttonClick; var overrideText; // text explicitly set by calendar's constructor options. overcomes icons var defaultText; var themeIcon; var normalIcon; var innerHtml; var classes; var button; if (buttonName == 'title') { groupChildren = groupChildren.add($('<h2>&nbsp;</h2>')); // we always want it to take up height isOnlyButtons = false; } else { viewSpec = calendar.getViewSpec(buttonName); if (viewSpec) { buttonClick = function() { calendar.changeView(buttonName); }; viewsWithButtons.push(buttonName); overrideText = viewSpec.buttonTextOverride; defaultText = viewSpec.buttonTextDefault; } else if (calendar[buttonName]) { // a calendar method buttonClick = function() { calendar[buttonName](); }; overrideText = (calendar.overrides.buttonText || {})[buttonName]; defaultText = options.buttonText[buttonName]; // everything else is considered default } if (buttonClick) { themeIcon = options.themeButtonIcons[buttonName]; normalIcon = options.buttonIcons[buttonName]; if (overrideText) { innerHtml = htmlEscape(overrideText); } else if (themeIcon && options.theme) { innerHtml = "<span class='ui-icon ui-icon-" + themeIcon + "'></span>"; } else if (normalIcon && !options.theme) { innerHtml = "<span class='fc-icon fc-icon-" + normalIcon + "'></span>"; } else { innerHtml = htmlEscape(defaultText); } classes = [ 'fc-' + buttonName + '-button', tm + '-button', tm + '-state-default' ]; button = $( // type="button" so that it doesn't submit a form '<button type="button" class="' + classes.join(' ') + '">' + innerHtml + '</button>' ) .click(function() { // don't process clicks for disabled buttons if (!button.hasClass(tm + '-state-disabled')) { buttonClick(); // after the click action, if the button becomes the "active" tab, or disabled, // it should never have a hover class, so remove it now. if ( button.hasClass(tm + '-state-active') || button.hasClass(tm + '-state-disabled') ) { button.removeClass(tm + '-state-hover'); } } }) .mousedown(function() { // the *down* effect (mouse pressed in). // only on buttons that are not the "active" tab, or disabled button .not('.' + tm + '-state-active') .not('.' + tm + '-state-disabled') .addClass(tm + '-state-down'); }) .mouseup(function() { // undo the *down* effect button.removeClass(tm + '-state-down'); }) .hover( function() { // the *hover* effect. // only on buttons that are not the "active" tab, or disabled button .not('.' + tm + '-state-active') .not('.' + tm + '-state-disabled') .addClass(tm + '-state-hover'); }, function() { // undo the *hover* effect button .removeClass(tm + '-state-hover') .removeClass(tm + '-state-down'); // if mouseleave happens before mouseup } ); groupChildren = groupChildren.add(button); } } }); if (isOnlyButtons) { groupChildren .first().addClass(tm + '-corner-left').end() .last().addClass(tm + '-corner-right').end(); } if (groupChildren.length > 1) { groupEl = $('<div/>'); if (isOnlyButtons) { groupEl.addClass('fc-button-group'); } groupEl.append(groupChildren); sectionEl.append(groupEl); } else { sectionEl.append(groupChildren); // 1 or 0 children } }); } return sectionEl; } function updateTitle(text) { el.find('h2').text(text); } function activateButton(buttonName) { el.find('.fc-' + buttonName + '-button') .addClass(tm + '-state-active'); } function deactivateButton(buttonName) { el.find('.fc-' + buttonName + '-button') .removeClass(tm + '-state-active'); } function disableButton(buttonName) { el.find('.fc-' + buttonName + '-button') .attr('disabled', 'disabled') .addClass(tm + '-state-disabled'); } function enableButton(buttonName) { el.find('.fc-' + buttonName + '-button') .removeAttr('disabled') .removeClass(tm + '-state-disabled'); } function getViewsWithButtons() { return viewsWithButtons; } } ;; fc.sourceNormalizers = []; fc.sourceFetchers = []; var ajaxDefaults = { dataType: 'json', cache: false }; var eventGUID = 1; function EventManager(options) { // assumed to be a calendar var t = this; // exports t.isFetchNeeded = isFetchNeeded; t.fetchEvents = fetchEvents; t.addEventSource = addEventSource; t.removeEventSource = removeEventSource; t.updateEvent = updateEvent; t.renderEvent = renderEvent; t.removeEvents = removeEvents; t.clientEvents = clientEvents; t.mutateEvent = mutateEvent; t.normalizeEventRange = normalizeEventRange; t.normalizeEventRangeTimes = normalizeEventRangeTimes; t.ensureVisibleEventRange = ensureVisibleEventRange; // imports var trigger = t.trigger; var getView = t.getView; var reportEvents = t.reportEvents; // locals var stickySource = { events: [] }; var sources = [ stickySource ]; var rangeStart, rangeEnd; var currentFetchID = 0; var pendingSourceCnt = 0; var loadingLevel = 0; var cache = []; // holds events that have already been expanded $.each( (options.events ? [ options.events ] : []).concat(options.eventSources || []), function(i, sourceInput) { var source = buildEventSource(sourceInput); if (source) { sources.push(source); } } ); /* Fetching -----------------------------------------------------------------------------*/ function isFetchNeeded(start, end) { return !rangeStart || // nothing has been fetched yet? // or, a part of the new range is outside of the old range? (after normalizing) start.clone().stripZone() < rangeStart.clone().stripZone() || end.clone().stripZone() > rangeEnd.clone().stripZone(); } function fetchEvents(start, end) { rangeStart = start; rangeEnd = end; cache = []; var fetchID = ++currentFetchID; var len = sources.length; pendingSourceCnt = len; for (var i=0; i<len; i++) { fetchEventSource(sources[i], fetchID); } } function fetchEventSource(source, fetchID) { _fetchEventSource(source, function(eventInputs) { var isArraySource = $.isArray(source.events); var i, eventInput; var abstractEvent; if (fetchID == currentFetchID) { if (eventInputs) { for (i = 0; i < eventInputs.length; i++) { eventInput = eventInputs[i]; if (isArraySource) { // array sources have already been convert to Event Objects abstractEvent = eventInput; } else { abstractEvent = buildEventFromInput(eventInput, source); } if (abstractEvent) { // not false (an invalid event) cache.push.apply( cache, expandEvent(abstractEvent) // add individual expanded events to the cache ); } } } pendingSourceCnt--; if (!pendingSourceCnt) { reportEvents(cache); } } }); } function _fetchEventSource(source, callback) { var i; var fetchers = fc.sourceFetchers; var res; for (i=0; i<fetchers.length; i++) { res = fetchers[i].call( t, // this, the Calendar object source, rangeStart.clone(), rangeEnd.clone(), options.timezone, callback ); if (res === true) { // the fetcher is in charge. made its own async request return; } else if (typeof res == 'object') { // the fetcher returned a new source. process it _fetchEventSource(res, callback); return; } } var events = source.events; if (events) { if ($.isFunction(events)) { pushLoading(); events.call( t, // this, the Calendar object rangeStart.clone(), rangeEnd.clone(), options.timezone, function(events) { callback(events); popLoading(); } ); } else if ($.isArray(events)) { callback(events); } else { callback(); } }else{ var url = source.url; if (url) { var success = source.success; var error = source.error; var complete = source.complete; // retrieve any outbound GET/POST $.ajax data from the options var customData; if ($.isFunction(source.data)) { // supplied as a function that returns a key/value object customData = source.data(); } else { // supplied as a straight key/value object customData = source.data; } // use a copy of the custom data so we can modify the parameters // and not affect the passed-in object. var data = $.extend({}, customData || {}); var startParam = firstDefined(source.startParam, options.startParam); var endParam = firstDefined(source.endParam, options.endParam); var timezoneParam = firstDefined(source.timezoneParam, options.timezoneParam); if (startParam) { data[startParam] = rangeStart.format(); } if (endParam) { data[endParam] = rangeEnd.format(); } if (options.timezone && options.timezone != 'local') { data[timezoneParam] = options.timezone; } pushLoading(); $.ajax($.extend({}, ajaxDefaults, source, { data: data, success: function(events) { events = events || []; var res = applyAll(success, this, arguments); if ($.isArray(res)) { events = res; } callback(events); }, error: function() { applyAll(error, this, arguments); callback(); }, complete: function() { applyAll(complete, this, arguments); popLoading(); } })); }else{ callback(); } } } /* Sources -----------------------------------------------------------------------------*/ function addEventSource(sourceInput) { var source = buildEventSource(sourceInput); if (source) { sources.push(source); pendingSourceCnt++; fetchEventSource(source, currentFetchID); // will eventually call reportEvents } } function buildEventSource(sourceInput) { // will return undefined if invalid source var normalizers = fc.sourceNormalizers; var source; var i; if ($.isFunction(sourceInput) || $.isArray(sourceInput)) { source = { events: sourceInput }; } else if (typeof sourceInput === 'string') { source = { url: sourceInput }; } else if (typeof sourceInput === 'object') { source = $.extend({}, sourceInput); // shallow copy } if (source) { // TODO: repeat code, same code for event classNames if (source.className) { if (typeof source.className === 'string') { source.className = source.className.split(/\s+/); } // otherwise, assumed to be an array } else { source.className = []; } // for array sources, we convert to standard Event Objects up front if ($.isArray(source.events)) { source.origArray = source.events; // for removeEventSource source.events = $.map(source.events, function(eventInput) { return buildEventFromInput(eventInput, source); }); } for (i=0; i<normalizers.length; i++) { normalizers[i].call(t, source); } return source; } } function removeEventSource(source) { sources = $.grep(sources, function(src) { return !isSourcesEqual(src, source); }); // remove all client events from that source cache = $.grep(cache, function(e) { return !isSourcesEqual(e.source, source); }); reportEvents(cache); } function isSourcesEqual(source1, source2) { return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2); } function getSourcePrimitive(source) { return ( (typeof source === 'object') ? // a normalized event source? (source.origArray || source.googleCalendarId || source.url || source.events) : // get the primitive null ) || source; // the given argument *is* the primitive } /* Manipulation -----------------------------------------------------------------------------*/ // Only ever called from the externally-facing API function updateEvent(event) { // massage start/end values, even if date string values event.start = t.moment(event.start); if (event.end) { event.end = t.moment(event.end); } else { event.end = null; } mutateEvent(event, getMiscEventProps(event)); // will handle start/end/allDay normalization reportEvents(cache); // reports event modifications (so we can redraw) } // Returns a hash of misc event properties that should be copied over to related events. function getMiscEventProps(event) { var props = {}; $.each(event, function(name, val) { if (isMiscEventPropName(name)) { if (val !== undefined && isAtomic(val)) { // a defined non-object props[name] = val; } } }); return props; } // non-date-related, non-id-related, non-secret function isMiscEventPropName(name) { return !/^_|^(id|allDay|start|end)$/.test(name); } // returns the expanded events that were created function renderEvent(eventInput, stick) { var abstractEvent = buildEventFromInput(eventInput); var events; var i, event; if (abstractEvent) { // not false (a valid input) events = expandEvent(abstractEvent); for (i = 0; i < events.length; i++) { event = events[i]; if (!event.source) { if (stick) { stickySource.events.push(event); event.source = stickySource; } cache.push(event); } } reportEvents(cache); return events; } return []; } function removeEvents(filter) { var eventID; var i; if (filter == null) { // null or undefined. remove all events filter = function() { return true; }; // will always match } else if (!$.isFunction(filter)) { // an event ID eventID = filter + ''; filter = function(event) { return event._id == eventID; }; } // Purge event(s) from our local cache cache = $.grep(cache, filter, true); // inverse=true // Remove events from array sources. // This works because they have been converted to official Event Objects up front. // (and as a result, event._id has been calculated). for (i=0; i<sources.length; i++) { if ($.isArray(sources[i].events)) { sources[i].events = $.grep(sources[i].events, filter, true); } } reportEvents(cache); } function clientEvents(filter) { if ($.isFunction(filter)) { return $.grep(cache, filter); } else if (filter != null) { // not null, not undefined. an event ID filter += ''; return $.grep(cache, function(e) { return e._id == filter; }); } return cache; // else, return all } /* Loading State -----------------------------------------------------------------------------*/ function pushLoading() { if (!(loadingLevel++)) { trigger('loading', null, true, getView()); } } function popLoading() { if (!(--loadingLevel)) { trigger('loading', null, false, getView()); } } /* Event Normalization -----------------------------------------------------------------------------*/ // Given a raw object with key/value properties, returns an "abstract" Event object. // An "abstract" event is an event that, if recurring, will not have been expanded yet. // Will return `false` when input is invalid. // `source` is optional function buildEventFromInput(input, source) { var out = {}; var start, end; var allDay; if (options.eventDataTransform) { input = options.eventDataTransform(input); } if (source && source.eventDataTransform) { input = source.eventDataTransform(input); } // Copy all properties over to the resulting object. // The special-case properties will be copied over afterwards. $.extend(out, input); if (source) { out.source = source; } out._id = input._id || (input.id === undefined ? '_fc' + eventGUID++ : input.id + ''); if (input.className) { if (typeof input.className == 'string') { out.className = input.className.split(/\s+/); } else { // assumed to be an array out.className = input.className; } } else { out.className = []; } start = input.start || input.date; // "date" is an alias for "start" end = input.end; // parse as a time (Duration) if applicable if (isTimeString(start)) { start = moment.duration(start); } if (isTimeString(end)) { end = moment.duration(end); } if (input.dow || moment.isDuration(start) || moment.isDuration(end)) { // the event is "abstract" (recurring) so don't calculate exact start/end dates just yet out.start = start ? moment.duration(start) : null; // will be a Duration or null out.end = end ? moment.duration(end) : null; // will be a Duration or null out._recurring = true; // our internal marker } else { if (start) { start = t.moment(start); if (!start.isValid()) { return false; } } if (end) { end = t.moment(end); if (!end.isValid()) { end = null; // let defaults take over } } allDay = input.allDay; if (allDay === undefined) { // still undefined? fallback to default allDay = firstDefined( source ? source.allDayDefault : undefined, options.allDayDefault ); // still undefined? normalizeEventRange will calculate it } assignDatesToEvent(start, end, allDay, out); } return out; } // Normalizes and assigns the given dates to the given partially-formed event object. // NOTE: mutates the given start/end moments. does not make a copy. function assignDatesToEvent(start, end, allDay, event) { event.start = start; event.end = end; event.allDay = allDay; normalizeEventRange(event); backupEventDates(event); } // Ensures proper values for allDay/start/end. Accepts an Event object, or a plain object with event-ish properties. // NOTE: Will modify the given object. function normalizeEventRange(props) { normalizeEventRangeTimes(props); if (props.end && !props.end.isAfter(props.start)) { props.end = null; } if (!props.end) { if (options.forceEventDuration) { props.end = t.getDefaultEventEnd(props.allDay, props.start); } else { props.end = null; } } } // Ensures the allDay property exists and the timeliness of the start/end dates are consistent function normalizeEventRangeTimes(range) { if (range.allDay == null) { range.allDay = !(range.start.hasTime() || (range.end && range.end.hasTime())); } if (range.allDay) { range.start.stripTime(); if (range.end) { // TODO: consider nextDayThreshold here? If so, will require a lot of testing and adjustment range.end.stripTime(); } } else { if (!range.start.hasTime()) { range.start = t.rezoneDate(range.start); // will assign a 00:00 time } if (range.end && !range.end.hasTime()) { range.end = t.rezoneDate(range.end); // will assign a 00:00 time } } } // If `range` is a proper range with a start and end, returns the original object. // If missing an end, computes a new range with an end, computing it as if it were an event. // TODO: make this a part of the event -> eventRange system function ensureVisibleEventRange(range) { var allDay; if (!range.end) { allDay = range.allDay; // range might be more event-ish than we think if (allDay == null) { allDay = !range.start.hasTime(); } range = $.extend({}, range); // make a copy, copying over other misc properties range.end = t.getDefaultEventEnd(allDay, range.start); } return range; } // If the given event is a recurring event, break it down into an array of individual instances. // If not a recurring event, return an array with the single original event. // If given a falsy input (probably because of a failed buildEventFromInput call), returns an empty array. // HACK: can override the recurring window by providing custom rangeStart/rangeEnd (for businessHours). function expandEvent(abstractEvent, _rangeStart, _rangeEnd) { var events = []; var dowHash; var dow; var i; var date; var startTime, endTime; var start, end; var event; _rangeStart = _rangeStart || rangeStart; _rangeEnd = _rangeEnd || rangeEnd; if (abstractEvent) { if (abstractEvent._recurring) { // make a boolean hash as to whether the event occurs on each day-of-week if ((dow = abstractEvent.dow)) { dowHash = {}; for (i = 0; i < dow.length; i++) { dowHash[dow[i]] = true; } } // iterate through every day in the current range date = _rangeStart.clone().stripTime(); // holds the date of the current day while (date.isBefore(_rangeEnd)) { if (!dowHash || dowHash[date.day()]) { // if everyday, or this particular day-of-week startTime = abstractEvent.start; // the stored start and end properties are times (Durations) endTime = abstractEvent.end; // " start = date.clone(); end = null; if (startTime) { start = start.time(startTime); } if (endTime) { end = date.clone().time(endTime); } event = $.extend({}, abstractEvent); // make a copy of the original assignDatesToEvent( start, end, !startTime && !endTime, // allDay? event ); events.push(event); } date.add(1, 'days'); } } else { events.push(abstractEvent); // return the original event. will be a one-item array } } return events; } /* Event Modification Math -----------------------------------------------------------------------------------------*/ // Modifies an event and all related events by applying the given properties. // Special date-diffing logic is used for manipulation of dates. // If `props` does not contain start/end dates, the updated values are assumed to be the event's current start/end. // All date comparisons are done against the event's pristine _start and _end dates. // Returns an object with delta information and a function to undo all operations. // For making computations in a granularity greater than day/time, specify largeUnit. // NOTE: The given `newProps` might be mutated for normalization purposes. function mutateEvent(event, newProps, largeUnit) { var miscProps = {}; var oldProps; var clearEnd; var startDelta; var endDelta; var durationDelta; var undoFunc; // diffs the dates in the appropriate way, returning a duration function diffDates(date1, date0) { // date1 - date0 if (largeUnit) { return diffByUnit(date1, date0, largeUnit); } else if (newProps.allDay) { return diffDay(date1, date0); } else { return diffDayTime(date1, date0); } } newProps = newProps || {}; // normalize new date-related properties if (!newProps.start) { newProps.start = event.start.clone(); } if (newProps.end === undefined) { newProps.end = event.end ? event.end.clone() : null; } if (newProps.allDay == null) { // is null or undefined? newProps.allDay = event.allDay; } normalizeEventRange(newProps); // create normalized versions of the original props to compare against // need a real end value, for diffing oldProps = { start: event._start.clone(), end: event._end ? event._end.clone() : t.getDefaultEventEnd(event._allDay, event._start), allDay: newProps.allDay // normalize the dates in the same regard as the new properties }; normalizeEventRange(oldProps); // need to clear the end date if explicitly changed to null clearEnd = event._end !== null && newProps.end === null; // compute the delta for moving the start date startDelta = diffDates(newProps.start, oldProps.start); // compute the delta for moving the end date if (newProps.end) { endDelta = diffDates(newProps.end, oldProps.end); durationDelta = endDelta.subtract(startDelta); } else { durationDelta = null; } // gather all non-date-related properties $.each(newProps, function(name, val) { if (isMiscEventPropName(name)) { if (val !== undefined) { miscProps[name] = val; } } }); // apply the operations to the event and all related events undoFunc = mutateEvents( clientEvents(event._id), // get events with this ID clearEnd, newProps.allDay, startDelta, durationDelta, miscProps ); return { dateDelta: startDelta, durationDelta: durationDelta, undo: undoFunc }; } // Modifies an array of events in the following ways (operations are in order): // - clear the event's `end` // - convert the event to allDay // - add `dateDelta` to the start and end // - add `durationDelta` to the event's duration // - assign `miscProps` to the event // // Returns a function that can be called to undo all the operations. // // TODO: don't use so many closures. possible memory issues when lots of events with same ID. // function mutateEvents(events, clearEnd, allDay, dateDelta, durationDelta, miscProps) { var isAmbigTimezone = t.getIsAmbigTimezone(); var undoFunctions = []; // normalize zero-length deltas to be null if (dateDelta && !dateDelta.valueOf()) { dateDelta = null; } if (durationDelta && !durationDelta.valueOf()) { durationDelta = null; } $.each(events, function(i, event) { var oldProps; var newProps; // build an object holding all the old values, both date-related and misc. // for the undo function. oldProps = { start: event.start.clone(), end: event.end ? event.end.clone() : null, allDay: event.allDay }; $.each(miscProps, function(name) { oldProps[name] = event[name]; }); // new date-related properties. work off the original date snapshot. // ok to use references because they will be thrown away when backupEventDates is called. newProps = { start: event._start, end: event._end, allDay: allDay // normalize the dates in the same regard as the new properties }; normalizeEventRange(newProps); // massages start/end/allDay // strip or ensure the end date if (clearEnd) { newProps.end = null; } else if (durationDelta && !newProps.end) { // the duration translation requires an end date newProps.end = t.getDefaultEventEnd(newProps.allDay, newProps.start); } if (dateDelta) { newProps.start.add(dateDelta); if (newProps.end) { newProps.end.add(dateDelta); } } if (durationDelta) { newProps.end.add(durationDelta); // end already ensured above } // if the dates have changed, and we know it is impossible to recompute the // timezone offsets, strip the zone. if ( isAmbigTimezone && !newProps.allDay && (dateDelta || durationDelta) ) { newProps.start.stripZone(); if (newProps.end) { newProps.end.stripZone(); } } $.extend(event, miscProps, newProps); // copy over misc props, then date-related props backupEventDates(event); // regenerate internal _start/_end/_allDay undoFunctions.push(function() { $.extend(event, oldProps); backupEventDates(event); // regenerate internal _start/_end/_allDay }); }); return function() { for (var i = 0; i < undoFunctions.length; i++) { undoFunctions[i](); } }; } /* Business Hours -----------------------------------------------------------------------------------------*/ t.getBusinessHoursEvents = getBusinessHoursEvents; // Returns an array of events as to when the business hours occur in the given view. // Abuse of our event system :( function getBusinessHoursEvents(wholeDay) { var optionVal = options.businessHours; var defaultVal = { className: 'fc-nonbusiness', start: '09:00', end: '17:00', dow: [ 1, 2, 3, 4, 5 ], // monday - friday rendering: 'inverse-background' }; var view = t.getView(); var eventInput; if (optionVal) { // `true` (which means "use the defaults") or an override object eventInput = $.extend( {}, // copy to a new object in either case defaultVal, typeof optionVal === 'object' ? optionVal : {} // override the defaults ); } if (eventInput) { // if a whole-day series is requested, clear the start/end times if (wholeDay) { eventInput.start = null; eventInput.end = null; } return expandEvent( buildEventFromInput(eventInput), view.start, view.end ); } return []; } /* Overlapping / Constraining -----------------------------------------------------------------------------------------*/ t.isEventRangeAllowed = isEventRangeAllowed; t.isSelectionRangeAllowed = isSelectionRangeAllowed; t.isExternalDropRangeAllowed = isExternalDropRangeAllowed; function isEventRangeAllowed(range, event) { var source = event.source || {}; var constraint = firstDefined( event.constraint, source.constraint, options.eventConstraint ); var overlap = firstDefined( event.overlap, source.overlap, options.eventOverlap ); range = ensureVisibleEventRange(range); // ensure a proper range with an end for isRangeAllowed return isRangeAllowed(range, constraint, overlap, event); } function isSelectionRangeAllowed(range) { return isRangeAllowed(range, options.selectConstraint, options.selectOverlap); } // when `eventProps` is defined, consider this an event. // `eventProps` can contain misc non-date-related info about the event. function isExternalDropRangeAllowed(range, eventProps) { var eventInput; var event; // note: very similar logic is in View's reportExternalDrop if (eventProps) { eventInput = $.extend({}, eventProps, range); event = expandEvent(buildEventFromInput(eventInput))[0]; } if (event) { return isEventRangeAllowed(range, event); } else { // treat it as a selection range = ensureVisibleEventRange(range); // ensure a proper range with an end for isSelectionRangeAllowed return isSelectionRangeAllowed(range); } } // Returns true if the given range (caused by an event drop/resize or a selection) is allowed to exist // according to the constraint/overlap settings. // `event` is not required if checking a selection. function isRangeAllowed(range, constraint, overlap, event) { var constraintEvents; var anyContainment; var peerEvents; var i, peerEvent; var peerOverlap; // normalize. fyi, we're normalizing in too many places :( range = $.extend({}, range); // copy all properties in case there are misc non-date properties range.start = range.start.clone().stripZone(); range.end = range.end.clone().stripZone(); // the range must be fully contained by at least one of produced constraint events if (constraint != null) { // not treated as an event! intermediate data structure // TODO: use ranges in the future constraintEvents = constraintToEvents(constraint); anyContainment = false; for (i = 0; i < constraintEvents.length; i++) { if (eventContainsRange(constraintEvents[i], range)) { anyContainment = true; break; } } if (!anyContainment) { return false; } } peerEvents = t.getPeerEvents(event, range); for (i = 0; i < peerEvents.length; i++) { peerEvent = peerEvents[i]; // there needs to be an actual intersection before disallowing anything if (eventIntersectsRange(peerEvent, range)) { // evaluate overlap for the given range and short-circuit if necessary if (overlap === false) { return false; } // if the event's overlap is a test function, pass the peer event in question as the first param else if (typeof overlap === 'function' && !overlap(peerEvent, event)) { return false; } // if we are computing if the given range is allowable for an event, consider the other event's // EventObject-specific or Source-specific `overlap` property if (event) { peerOverlap = firstDefined( peerEvent.overlap, (peerEvent.source || {}).overlap // we already considered the global `eventOverlap` ); if (peerOverlap === false) { return false; } // if the peer event's overlap is a test function, pass the subject event as the first param if (typeof peerOverlap === 'function' && !peerOverlap(event, peerEvent)) { return false; } } } } return true; } // Given an event input from the API, produces an array of event objects. Possible event inputs: // 'businessHours' // An event ID (number or string) // An object with specific start/end dates or a recurring event (like what businessHours accepts) function constraintToEvents(constraintInput) { if (constraintInput === 'businessHours') { return getBusinessHoursEvents(); } if (typeof constraintInput === 'object') { return expandEvent(buildEventFromInput(constraintInput)); } return clientEvents(constraintInput); // probably an ID } // Does the event's date range fully contain the given range? // start/end already assumed to have stripped zones :( function eventContainsRange(event, range) { var eventStart = event.start.clone().stripZone(); var eventEnd = t.getEventEnd(event).stripZone(); return range.start >= eventStart && range.end <= eventEnd; } // Does the event's date range intersect with the given range? // start/end already assumed to have stripped zones :( function eventIntersectsRange(event, range) { var eventStart = event.start.clone().stripZone(); var eventEnd = t.getEventEnd(event).stripZone(); return range.start < eventEnd && range.end > eventStart; } t.getEventCache = function() { return cache; }; } // Returns a list of events that the given event should be compared against when being considered for a move to // the specified range. Attached to the Calendar's prototype because EventManager is a mixin for a Calendar. Calendar.prototype.getPeerEvents = function(event, range) { var cache = this.getEventCache(); var peerEvents = []; var i, otherEvent; for (i = 0; i < cache.length; i++) { otherEvent = cache[i]; if ( !event || event._id !== otherEvent._id // don't compare the event to itself or other related [repeating] events ) { peerEvents.push(otherEvent); } } return peerEvents; }; // updates the "backup" properties, which are preserved in order to compute diffs later on. function backupEventDates(event) { event._allDay = event.allDay; event._start = event.start.clone(); event._end = event.end ? event.end.clone() : null; } ;; /* An abstract class for the "basic" views, as well as month view. Renders one or more rows of day cells. ----------------------------------------------------------------------------------------------------------------------*/ // It is a manager for a DayGrid subcomponent, which does most of the heavy lifting. // It is responsible for managing width/height. var BasicView = fcViews.basic = View.extend({ dayGrid: null, // the main subcomponent that does most of the heavy lifting dayNumbersVisible: false, // display day numbers on each day cell? weekNumbersVisible: false, // display week numbers along the side? weekNumberWidth: null, // width of all the week-number cells running down the side headRowEl: null, // the fake row element of the day-of-week header initialize: function() { this.dayGrid = new DayGrid(this); this.coordMap = this.dayGrid.coordMap; // the view's date-to-cell mapping is identical to the subcomponent's }, // Sets the display range and computes all necessary dates setRange: function(range) { View.prototype.setRange.call(this, range); // call the super-method this.dayGrid.breakOnWeeks = /year|month|week/.test(this.intervalUnit); // do before setRange this.dayGrid.setRange(range); }, // Compute the value to feed into setRange. Overrides superclass. computeRange: function(date) { var range = View.prototype.computeRange.call(this, date); // get value from the super-method // year and month views should be aligned with weeks. this is already done for week if (/year|month/.test(range.intervalUnit)) { range.start.startOf('week'); range.start = this.skipHiddenDays(range.start); // make end-of-week if not already if (range.end.weekday()) { range.end.add(1, 'week').startOf('week'); range.end = this.skipHiddenDays(range.end, -1, true); // exclusively move backwards } } return range; }, // Renders the view into `this.el`, which should already be assigned render: function() { this.dayNumbersVisible = this.dayGrid.rowCnt > 1; // TODO: make grid responsible this.weekNumbersVisible = this.opt('weekNumbers'); this.dayGrid.numbersVisible = this.dayNumbersVisible || this.weekNumbersVisible; this.el.addClass('fc-basic-view').html(this.renderHtml()); this.headRowEl = this.el.find('thead .fc-row'); this.scrollerEl = this.el.find('.fc-day-grid-container'); this.dayGrid.coordMap.containerEl = this.scrollerEl; // constrain clicks/etc to the dimensions of the scroller this.dayGrid.setElement(this.el.find('.fc-day-grid')); this.dayGrid.renderDates(this.hasRigidRows()); }, // Unrenders the content of the view. Since we haven't separated skeleton rendering from date rendering, // always completely kill the dayGrid's rendering. destroy: function() { this.dayGrid.destroyDates(); this.dayGrid.removeElement(); }, renderBusinessHours: function() { this.dayGrid.renderBusinessHours(); }, // Builds the HTML skeleton for the view. // The day-grid component will render inside of a container defined by this HTML. renderHtml: function() { return '' + '<table>' + '<thead class="fc-head">' + '<tr>' + '<td class="' + this.widgetHeaderClass + '">' + this.dayGrid.headHtml() + // render the day-of-week headers '</td>' + '</tr>' + '</thead>' + '<tbody class="fc-body">' + '<tr>' + '<td class="' + this.widgetContentClass + '">' + '<div class="fc-day-grid-container">' + '<div class="fc-day-grid"/>' + '</div>' + '</td>' + '</tr>' + '</tbody>' + '</table>'; }, // Generates the HTML that will go before the day-of week header cells. // Queried by the DayGrid subcomponent when generating rows. Ordering depends on isRTL. headIntroHtml: function() { if (this.weekNumbersVisible) { return '' + '<th class="fc-week-number ' + this.widgetHeaderClass + '" ' + this.weekNumberStyleAttr() + '>' + '<span>' + // needed for matchCellWidths htmlEscape(this.opt('weekNumberTitle')) + '</span>' + '</th>'; } }, // Generates the HTML that will go before content-skeleton cells that display the day/week numbers. // Queried by the DayGrid subcomponent. Ordering depends on isRTL. numberIntroHtml: function(row) { if (this.weekNumbersVisible) { return '' + '<td class="fc-week-number" ' + this.weekNumberStyleAttr() + '>' + '<span>' + // needed for matchCellWidths this.dayGrid.getCell(row, 0).start.format('w') + '</span>' + '</td>'; } }, // Generates the HTML that goes before the day bg cells for each day-row. // Queried by the DayGrid subcomponent. Ordering depends on isRTL. dayIntroHtml: function() { if (this.weekNumbersVisible) { return '<td class="fc-week-number ' + this.widgetContentClass + '" ' + this.weekNumberStyleAttr() + '></td>'; } }, // Generates the HTML that goes before every other type of row generated by DayGrid. Ordering depends on isRTL. // Affects helper-skeleton and highlight-skeleton rows. introHtml: function() { if (this.weekNumbersVisible) { return '<td class="fc-week-number" ' + this.weekNumberStyleAttr() + '></td>'; } }, // Generates the HTML for the <td>s of the "number" row in the DayGrid's content skeleton. // The number row will only exist if either day numbers or week numbers are turned on. numberCellHtml: function(cell) { var date = cell.start; var classes; if (!this.dayNumbersVisible) { // if there are week numbers but not day numbers return '<td/>'; // will create an empty space above events :( } classes = this.dayGrid.getDayClasses(date); classes.unshift('fc-day-number'); return '' + '<td class="' + classes.join(' ') + '" data-date="' + date.format() + '">' + date.date() + '</td>'; }, // Generates an HTML attribute string for setting the width of the week number column, if it is known weekNumberStyleAttr: function() { if (this.weekNumberWidth !== null) { return 'style="width:' + this.weekNumberWidth + 'px"'; } return ''; }, // Determines whether each row should have a constant height hasRigidRows: function() { var eventLimit = this.opt('eventLimit'); return eventLimit && typeof eventLimit !== 'number'; }, /* Dimensions ------------------------------------------------------------------------------------------------------------------*/ // Refreshes the horizontal dimensions of the view updateWidth: function() { if (this.weekNumbersVisible) { // Make sure all week number cells running down the side have the same width. // Record the width for cells created later. this.weekNumberWidth = matchCellWidths( this.el.find('.fc-week-number') ); } }, // Adjusts the vertical dimensions of the view to the specified values setHeight: function(totalHeight, isAuto) { var eventLimit = this.opt('eventLimit'); var scrollerHeight; // reset all heights to be natural unsetScroller(this.scrollerEl); uncompensateScroll(this.headRowEl); this.dayGrid.destroySegPopover(); // kill the "more" popover if displayed // is the event limit a constant level number? if (eventLimit && typeof eventLimit === 'number') { this.dayGrid.limitRows(eventLimit); // limit the levels first so the height can redistribute after } scrollerHeight = this.computeScrollerHeight(totalHeight); this.setGridHeight(scrollerHeight, isAuto); // is the event limit dynamically calculated? if (eventLimit && typeof eventLimit !== 'number') { this.dayGrid.limitRows(eventLimit); // limit the levels after the grid's row heights have been set } if (!isAuto && setPotentialScroller(this.scrollerEl, scrollerHeight)) { // using scrollbars? compensateScroll(this.headRowEl, getScrollbarWidths(this.scrollerEl)); // doing the scrollbar compensation might have created text overflow which created more height. redo scrollerHeight = this.computeScrollerHeight(totalHeight); this.scrollerEl.height(scrollerHeight); } }, // Sets the height of just the DayGrid component in this view setGridHeight: function(height, isAuto) { if (isAuto) { undistributeHeight(this.dayGrid.rowEls); // let the rows be their natural height with no expanding } else { distributeHeight(this.dayGrid.rowEls, height, true); // true = compensate for height-hogging rows } }, /* Events ------------------------------------------------------------------------------------------------------------------*/ // Renders the given events onto the view and populates the segments array renderEvents: function(events) { this.dayGrid.renderEvents(events); this.updateHeight(); // must compensate for events that overflow the row }, // Retrieves all segment objects that are rendered in the view getEventSegs: function() { return this.dayGrid.getEventSegs(); }, // Unrenders all event elements and clears internal segment data destroyEvents: function() { this.dayGrid.destroyEvents(); // we DON'T need to call updateHeight() because: // A) a renderEvents() call always happens after this, which will eventually call updateHeight() // B) in IE8, this causes a flash whenever events are rerendered }, /* Dragging (for both events and external elements) ------------------------------------------------------------------------------------------------------------------*/ // A returned value of `true` signals that a mock "helper" event has been rendered. renderDrag: function(dropLocation, seg) { return this.dayGrid.renderDrag(dropLocation, seg); }, destroyDrag: function() { this.dayGrid.destroyDrag(); }, /* Selection ------------------------------------------------------------------------------------------------------------------*/ // Renders a visual indication of a selection renderSelection: function(range) { this.dayGrid.renderSelection(range); }, // Unrenders a visual indications of a selection destroySelection: function() { this.dayGrid.destroySelection(); } }); ;; /* A month view with day cells running in rows (one-per-week) and columns ----------------------------------------------------------------------------------------------------------------------*/ var MonthView = fcViews.month = BasicView.extend({ // Produces information about what range to display computeRange: function(date) { var range = BasicView.prototype.computeRange.call(this, date); // get value from super-method var rowCnt; // ensure 6 weeks if (this.isFixedWeeks()) { rowCnt = Math.ceil(range.end.diff(range.start, 'weeks', true)); // could be partial weeks due to hiddenDays range.end.add(6 - rowCnt, 'weeks'); } return range; }, // Overrides the default BasicView behavior to have special multi-week auto-height logic setGridHeight: function(height, isAuto) { isAuto = isAuto || this.opt('weekMode') === 'variable'; // LEGACY: weekMode is deprecated // if auto, make the height of each row the height that it would be if there were 6 weeks if (isAuto) { height *= this.rowCnt / 6; } distributeHeight(this.dayGrid.rowEls, height, !isAuto); // if auto, don't compensate for height-hogging rows }, isFixedWeeks: function() { var weekMode = this.opt('weekMode'); // LEGACY: weekMode is deprecated if (weekMode) { return weekMode === 'fixed'; // if any other type of weekMode, assume NOT fixed } return this.opt('fixedWeekCount'); } }); MonthView.duration = { months: 1 }; // important for prev/next MonthView.defaults = { fixedWeekCount: true }; ;; /* A week view with simple day cells running horizontally ----------------------------------------------------------------------------------------------------------------------*/ fcViews.basicWeek = { type: 'basic', duration: { weeks: 1 } }; ;; /* A view with a single simple day cell ----------------------------------------------------------------------------------------------------------------------*/ fcViews.basicDay = { type: 'basic', duration: { days: 1 } }; ;; /* An abstract class for all agenda-related views. Displays one more columns with time slots running vertically. ----------------------------------------------------------------------------------------------------------------------*/ // Is a manager for the TimeGrid subcomponent and possibly the DayGrid subcomponent (if allDaySlot is on). // Responsible for managing width/height. var AGENDA_DEFAULTS = { allDaySlot: true, allDayText: 'all-day', scrollTime: '06:00:00', slotDuration: '00:30:00', minTime: '00:00:00', maxTime: '24:00:00', slotEventOverlap: true // a bad name. confused with overlap/constraint system }; var AGENDA_ALL_DAY_EVENT_LIMIT = 5; var AgendaView = fcViews.agenda = View.extend({ timeGrid: null, // the main time-grid subcomponent of this view dayGrid: null, // the "all-day" subcomponent. if all-day is turned off, this will be null axisWidth: null, // the width of the time axis running down the side noScrollRowEls: null, // set of fake row elements that must compensate when scrollerEl has scrollbars // when the time-grid isn't tall enough to occupy the given height, we render an <hr> underneath bottomRuleEl: null, bottomRuleHeight: null, initialize: function() { this.timeGrid = new TimeGrid(this); if (this.opt('allDaySlot')) { // should we display the "all-day" area? this.dayGrid = new DayGrid(this); // the all-day subcomponent of this view // the coordinate grid will be a combination of both subcomponents' grids this.coordMap = new ComboCoordMap([ this.dayGrid.coordMap, this.timeGrid.coordMap ]); } else { this.coordMap = this.timeGrid.coordMap; } }, /* Rendering ------------------------------------------------------------------------------------------------------------------*/ // Sets the display range and computes all necessary dates setRange: function(range) { View.prototype.setRange.call(this, range); // call the super-method this.timeGrid.setRange(range); if (this.dayGrid) { this.dayGrid.setRange(range); } }, // Renders the view into `this.el`, which has already been assigned render: function() { this.el.addClass('fc-agenda-view').html(this.renderHtml()); // the element that wraps the time-grid that will probably scroll this.scrollerEl = this.el.find('.fc-time-grid-container'); this.timeGrid.coordMap.containerEl = this.scrollerEl; // don't accept clicks/etc outside of this this.timeGrid.setElement(this.el.find('.fc-time-grid')); this.timeGrid.renderDates(); // the <hr> that sometimes displays under the time-grid this.bottomRuleEl = $('<hr class="fc-divider ' + this.widgetHeaderClass + '"/>') .appendTo(this.timeGrid.el); // inject it into the time-grid if (this.dayGrid) { this.dayGrid.setElement(this.el.find('.fc-day-grid')); this.dayGrid.renderDates(); // have the day-grid extend it's coordinate area over the <hr> dividing the two grids this.dayGrid.bottomCoordPadding = this.dayGrid.el.next('hr').outerHeight(); } this.noScrollRowEls = this.el.find('.fc-row:not(.fc-scroller *)'); // fake rows not within the scroller }, // Unrenders the content of the view. Since we haven't separated skeleton rendering from date rendering, // always completely kill each grid's rendering. destroy: function() { this.timeGrid.destroyDates(); this.timeGrid.removeElement(); if (this.dayGrid) { this.dayGrid.destroyDates(); this.dayGrid.removeElement(); } }, renderBusinessHours: function() { this.timeGrid.renderBusinessHours(); if (this.dayGrid) { this.dayGrid.renderBusinessHours(); } }, // Builds the HTML skeleton for the view. // The day-grid and time-grid components will render inside containers defined by this HTML. renderHtml: function() { return '' + '<table>' + '<thead class="fc-head">' + '<tr>' + '<td class="' + this.widgetHeaderClass + '">' + this.timeGrid.headHtml() + // render the day-of-week headers '</td>' + '</tr>' + '</thead>' + '<tbody class="fc-body">' + '<tr>' + '<td class="' + this.widgetContentClass + '">' + (this.dayGrid ? '<div class="fc-day-grid"/>' + '<hr class="fc-divider ' + this.widgetHeaderClass + '"/>' : '' ) + '<div class="fc-time-grid-container">' + '<div class="fc-time-grid"/>' + '</div>' + '</td>' + '</tr>' + '</tbody>' + '</table>'; }, // Generates the HTML that will go before the day-of week header cells. // Queried by the TimeGrid subcomponent when generating rows. Ordering depends on isRTL. headIntroHtml: function() { var date; var weekText; if (this.opt('weekNumbers')) { date = this.timeGrid.getCell(0).start; weekText = date.format(this.opt('smallWeekFormat')); return '' + '<th class="fc-axis fc-week-number ' + this.widgetHeaderClass + '" ' + this.axisStyleAttr() + '>' + '<span>' + // needed for matchCellWidths htmlEscape(weekText) + '</span>' + '</th>'; } else { return '<th class="fc-axis ' + this.widgetHeaderClass + '" ' + this.axisStyleAttr() + '></th>'; } }, // Generates the HTML that goes before the all-day cells. // Queried by the DayGrid subcomponent when generating rows. Ordering depends on isRTL. dayIntroHtml: function() { return '' + '<td class="fc-axis ' + this.widgetContentClass + '" ' + this.axisStyleAttr() + '>' + '<span>' + // needed for matchCellWidths (this.opt('allDayHtml') || htmlEscape(this.opt('allDayText'))) + '</span>' + '</td>'; }, // Generates the HTML that goes before the bg of the TimeGrid slot area. Long vertical column. slotBgIntroHtml: function() { return '<td class="fc-axis ' + this.widgetContentClass + '" ' + this.axisStyleAttr() + '></td>'; }, // Generates the HTML that goes before all other types of cells. // Affects content-skeleton, helper-skeleton, highlight-skeleton for both the time-grid and day-grid. // Queried by the TimeGrid and DayGrid subcomponents when generating rows. Ordering depends on isRTL. introHtml: function() { return '<td class="fc-axis" ' + this.axisStyleAttr() + '></td>'; }, // Generates an HTML attribute string for setting the width of the axis, if it is known axisStyleAttr: function() { if (this.axisWidth !== null) { return 'style="width:' + this.axisWidth + 'px"'; } return ''; }, /* Dimensions ------------------------------------------------------------------------------------------------------------------*/ updateSize: function(isResize) { this.timeGrid.updateSize(isResize); View.prototype.updateSize.call(this, isResize); // call the super-method }, // Refreshes the horizontal dimensions of the view updateWidth: function() { // make all axis cells line up, and record the width so newly created axis cells will have it this.axisWidth = matchCellWidths(this.el.find('.fc-axis')); }, // Adjusts the vertical dimensions of the view to the specified values setHeight: function(totalHeight, isAuto) { var eventLimit; var scrollerHeight; if (this.bottomRuleHeight === null) { // calculate the height of the rule the very first time this.bottomRuleHeight = this.bottomRuleEl.outerHeight(); } this.bottomRuleEl.hide(); // .show() will be called later if this <hr> is necessary // reset all dimensions back to the original state this.scrollerEl.css('overflow', ''); unsetScroller(this.scrollerEl); uncompensateScroll(this.noScrollRowEls); // limit number of events in the all-day area if (this.dayGrid) { this.dayGrid.destroySegPopover(); // kill the "more" popover if displayed eventLimit = this.opt('eventLimit'); if (eventLimit && typeof eventLimit !== 'number') { eventLimit = AGENDA_ALL_DAY_EVENT_LIMIT; // make sure "auto" goes to a real number } if (eventLimit) { this.dayGrid.limitRows(eventLimit); } } if (!isAuto) { // should we force dimensions of the scroll container, or let the contents be natural height? scrollerHeight = this.computeScrollerHeight(totalHeight); if (setPotentialScroller(this.scrollerEl, scrollerHeight)) { // using scrollbars? // make the all-day and header rows lines up compensateScroll(this.noScrollRowEls, getScrollbarWidths(this.scrollerEl)); // the scrollbar compensation might have changed text flow, which might affect height, so recalculate // and reapply the desired height to the scroller. scrollerHeight = this.computeScrollerHeight(totalHeight); this.scrollerEl.height(scrollerHeight); } else { // no scrollbars // still, force a height and display the bottom rule (marks the end of day) this.scrollerEl.height(scrollerHeight).css('overflow', 'hidden'); // in case <hr> goes outside this.bottomRuleEl.show(); } } }, // Computes the initial pre-configured scroll state prior to allowing the user to change it computeInitialScroll: function() { var scrollTime = moment.duration(this.opt('scrollTime')); var top = this.timeGrid.computeTimeTop(scrollTime); // zoom can give weird floating-point values. rather scroll a little bit further top = Math.ceil(top); if (top) { top++; // to overcome top border that slots beyond the first have. looks better } return top; }, /* Events ------------------------------------------------------------------------------------------------------------------*/ // Renders events onto the view and populates the View's segment array renderEvents: function(events) { var dayEvents = []; var timedEvents = []; var daySegs = []; var timedSegs; var i; // separate the events into all-day and timed for (i = 0; i < events.length; i++) { if (events[i].allDay) { dayEvents.push(events[i]); } else { timedEvents.push(events[i]); } } // render the events in the subcomponents timedSegs = this.timeGrid.renderEvents(timedEvents); if (this.dayGrid) { daySegs = this.dayGrid.renderEvents(dayEvents); } // the all-day area is flexible and might have a lot of events, so shift the height this.updateHeight(); }, // Retrieves all segment objects that are rendered in the view getEventSegs: function() { return this.timeGrid.getEventSegs().concat( this.dayGrid ? this.dayGrid.getEventSegs() : [] ); }, // Unrenders all event elements and clears internal segment data destroyEvents: function() { // destroy the events in the subcomponents this.timeGrid.destroyEvents(); if (this.dayGrid) { this.dayGrid.destroyEvents(); } // we DON'T need to call updateHeight() because: // A) a renderEvents() call always happens after this, which will eventually call updateHeight() // B) in IE8, this causes a flash whenever events are rerendered }, /* Dragging (for events and external elements) ------------------------------------------------------------------------------------------------------------------*/ // A returned value of `true` signals that a mock "helper" event has been rendered. renderDrag: function(dropLocation, seg) { if (dropLocation.start.hasTime()) { return this.timeGrid.renderDrag(dropLocation, seg); } else if (this.dayGrid) { return this.dayGrid.renderDrag(dropLocation, seg); } }, destroyDrag: function() { this.timeGrid.destroyDrag(); if (this.dayGrid) { this.dayGrid.destroyDrag(); } }, /* Selection ------------------------------------------------------------------------------------------------------------------*/ // Renders a visual indication of a selection renderSelection: function(range) { if (range.start.hasTime() || range.end.hasTime()) { this.timeGrid.renderSelection(range); } else if (this.dayGrid) { this.dayGrid.renderSelection(range); } }, // Unrenders a visual indications of a selection destroySelection: function() { this.timeGrid.destroySelection(); if (this.dayGrid) { this.dayGrid.destroySelection(); } } }); AgendaView.defaults = AGENDA_DEFAULTS; ;; /* A week view with an all-day cell area at the top, and a time grid below ----------------------------------------------------------------------------------------------------------------------*/ fcViews.agendaWeek = { type: 'agenda', duration: { weeks: 1 } }; ;; /* A day view with an all-day cell area at the top, and a time grid below ----------------------------------------------------------------------------------------------------------------------*/ fcViews.agendaDay = { type: 'agenda', duration: { days: 1 } }; ;; });
//1 unit = 1cm /*$(document).ready(function () { });*/ var players = [], currentPlayer, otherPlayer; var container; var camera, scene, renderer, loader, textureManager; var keyboardControl; var clock; var poolTable, ballArray, holeArray, playBallStart, eightballstart; var startPosArray; var collisionArray = [], collisionCount; var ballShot = false; var windowHalfX, windowHalfY; function initPlayers() { var player1 = document.getElementById("player1Name"); var player2 = document.getElementById("player2Name"); players[0] = new Player(player1.value, "player1"); players[1] = new Player(player2.value, "player2"); currentPlayer = 0; otherPlayer = 1; $("#currentPlayer").text("It is " + players[currentPlayer].Name + "'s turn"); updateScore(0, 0); updateScore(1, 0); $(".GameOverlay").show(); $(".loaderElement").hide(); init(); } function init() { windowHalfX = window.innerWidth / 2; windowHalfY = window.innerHeight / 2; container = document.createElement("div"); document.body.appendChild(container); keyboardControl = new Control(); textureManager = new THREE.LoadingManager(); loader = new THREE.TextureLoader(textureManager); renderer = new THREE.WebGLRenderer({antialias: true}); renderer.setSize(window.innerWidth, window.innerHeight); renderer.setPixelRatio(window.devicePixelRatio); renderer.setClearColor(0xFFFFFF); renderer.shadowMap.enabled = true; container.appendChild(renderer.domElement); camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000); camera.position.z = 200; camera.position.y = 100; scene = new THREE.Scene(); clock = new THREE.Clock(); var amLight = new THREE.AmbientLight(0x777777); amLight.position.y = 15; var light = new THREE.PointLight(0xffffff, 1.5, 500); light.position.y = 50; light.castShadow = true; poolTable = new PoolTable(); holeArray = [ new Hole(72.5, -147.5, 1), new Hole(-72.5, -147.5, 2), new Hole(72.5, 0, 3), new Hole(-72.5, 0, 4), new Hole(72.5, 147.5, 5), new Hole(-72.5, 147.5, 6) ]; ballArray = [ new PlayBall(0, 0, poolTable.children), new PoolBall(1, 1), new PoolBall(2, 1), new PoolBall(3, 1), new PoolBall(4, 1), new PoolBall(5, 1), new PoolBall(6, 1), new PoolBall(7, 1), new PoolBall(8, 8), new PoolBall(9, 2), new PoolBall(10, 2), new PoolBall(11, 2), new PoolBall(12, 2), new PoolBall(13, 2), new PoolBall(14, 2), new PoolBall(15, 2) ]; playBallStart = new THREE.Vector2(0, 75); eightballstart = new THREE.Vector2(0, -87); startPosArray = [ [0, -75], [-3, -81],[3, -81], [-6, -87],[6, -87], [-9, -93],[3, -93],[-3, -93],[9, -93], [-12, -99],[-6, -99],[0, -99],[6, -99],[12, -99] ]; setBallPositions(); for(let i = 0; i < ballArray.length; i++) { //Add Textures if(i >= 1 && i <= 15) ballArray[i].Material.map = loader.load("assets/textures/Ball" + i + ".png"); //Populate collision array var tempArray = []; for(let j = i + 1; j < ballArray.length; j++) { tempArray[j] = false; } collisionArray[i] = tempArray; } scene.add(amLight); scene.add(light); scene.add(poolTable.mesh); scene.add(ballArray[0].mesh); scene.add(ballArray[0].ceuMesh); for(let i = 1; i < ballArray.length; i++) { scene.add(ballArray[i].mesh); } for(let i = 0; i < holeArray.length; i++) { scene.add(holeArray[i].mesh); } window.addEventListener('resize', onWindowResize, false); document.addEventListener('onCollision', function () { collisionCount++; }); document.addEventListener('onShoot', function () { players[currentPlayer].ClearBalls(); ballShot = true; collisionCount = 0; }); textureManager.onLoad = function () { animate(); }; } function animate() { requestAnimationFrame(animate); render(); } function render() { var clockDelta = clock.getDelta(); var player = players[currentPlayer]; for(let i = 0; i < ballArray.length; i++) { if(ballArray[i].inScene) ballArray[i].CalcFrame(clockDelta, poolTable.children); } for(let i = 0; i < ballArray.length; i++) { for(let j = i + 1; j < ballArray.length; j++) { if(ballArray[i].inScene && ballArray[j].inScene) { if (collisionArray[i][j] == false) { ballArray[i].BallCollision(ballArray[j]); } collisionArray[i][j] = ballArray[i].CheckBallCollision(ballArray[j]); } } } for(let i = 0; i < holeArray.length; i++) { for(let j = 0; j < ballArray.length; j++) { if(ballArray[j].inScene) { var col = holeArray[i].CheckBall(ballArray[j]); if (col != null) { console.log(col.name + " was deleted"); player.AddBall(col); if(col.Type != 0 && col.Type != 8) { col.inScene = false; scene.remove(col.mesh); } else { col.ResetPos(); } } } } } checkKeys(); if(checkMovingBalls()) { ballArray[0].SetVisibility(false); } else { if(ballShot == true) { applyRules(); ballShot = false; } ballArray[0].SetVisibility(true); ballArray[0].CheckKeys(keyboardControl); scene.remove(ballArray[0].Line); ballArray[0].CalcNewLine(); scene.add(ballArray[0].Line); } camera.lookAt(new THREE.Vector3(0,0,0)); renderer.render(scene, camera); } function checkKeys() { var center = new THREE.Vector3(0,0,0); if(keyboardControl.GetKey("left") == true) { var newRot = calcNewRot(camera.position.x, camera.position.z, 0.05, center); camera.position.set(newRot.x, camera.position.y, newRot.y); } if(keyboardControl.GetKey("right") == true) { var newRot = calcNewRot(camera.position.x, camera.position.z, -0.05, center); camera.position.set(newRot.x, camera.position.y, newRot.y); } if(keyboardControl.GetKey("up")) { if(camera.position.y < 200) camera.position.y += 5; } if(keyboardControl.GetKey("down")) { if(camera.position.y > 20) camera.position.y += -5; } } function calcNewRot(x,y, rotation, center){ var center = new THREE.Vector2(center.x,center.y); var vector = new THREE.Vector2(x,y); vector.rotateAround(center, rotation); return vector; } function checkMovingBalls() { for(let i = 0; i < ballArray.length; i++) { if(ballArray[i].speed > 0 && ballArray[i].inScene) return true; } return false; } function setBallPositions() { var fullCornerSet = false; var halfCornerSet = false; var indexArray = [1,2,3,4,5,6,7,8,10,11,12]; var ballIndexArray = [2,3,4,5,6,7,9,10,11,12,13,14,15]; ballArray[0].SetPosition(playBallStart.x, playBallStart.y); ballArray[1].SetPosition(startPosArray[0][0], startPosArray[0][1]); ballArray[8].SetPosition(eightballstart.x, eightballstart.y); while(indexArray.length > 0 && ballIndexArray.length > 0) { //Select random ball var ranBallIndex = Math.floor(Math.random() * ballIndexArray.length); var ballIndex = ballIndexArray[ranBallIndex]; if(ballArray[ballIndex].type == 1 && !fullCornerSet) { ballArray[ballIndex].SetPosition(startPosArray[9][0], startPosArray[9][1]); fullCornerSet = true; } else if(ballArray[ballIndex].type == 2 && !halfCornerSet) { ballArray[ballIndex].SetPosition(startPosArray[13][0], startPosArray[13][1]); halfCornerSet = true; } else { var ranPosIndex = Math.floor(Math.random() * indexArray.length); var posIndex = indexArray[ranPosIndex]; indexArray.splice(ranPosIndex, 1); ballArray[ballIndex].SetPosition(startPosArray[posIndex][0], startPosArray[posIndex][1]); } ballIndexArray.splice(ranBallIndex, 1); } } function onWindowResize() { windowHalfX = window.innerWidth /2; windowHalfY = window.innerHeight /2; camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); } function applyRules() { var player = players[currentPlayer]; var otherPlay = players[otherPlayer]; var ownPut = false; var otherPut = false; var balls = player.PuttedBalls; if(balls.length > 0) { if(player.BallType == 0) { for(let i = 0; i < balls.length; i++) { switch (balls[i].Type){ case 1: player.BallType = 1; otherPlay.BallType = 2; break; case 2: player.BallType = 2; otherPlay.BallType = 1; break; } if(balls[i].Type != 0 && balls[i].Type != 8) break; } } if(player.BallType != 0) { for (let i = 0; i < balls.length; i++) { switch (balls[i].Type) { case 0: switchPlayer(); break; case 8: if (player.Score >= 7) { balls[i].ResetPos(); switchPlayer(); } else alert(player.Name + " Wins"); break; case 1: if (player.BallType == 1) { updateScore(currentPlayer, 1); ownPut = true; } else if (otherPlay.BallType == 1) { updateScore(otherPlayer, 1); otherPut = true; } break; case 2: if (player.BallType == 2) { updateScore(currentPlayer, 1); ownPut = true; } else if (otherPlay.BallType == 2) { updateScore(otherPlayer, 1); otherPut = true; } break; } } } } if((otherPut && !ownPut) || !ownPut) switchPlayer(); if(collisionCount == 0 && balls.length == 0) switchPlayer(); } function switchPlayer() { if(currentPlayer == 0) { currentPlayer = 1; otherPlayer = 0; } else if(currentPlayer == 1) { currentPlayer = 0; otherPlayer = 1; } $("#currentPlayer").text("It is " + players[currentPlayer].Name + "'s turn"); } function updateScore(playerNr, score) { var player = players[playerNr]; player.BallsPut(score); var playerText = document.getElementById(player.ID); $(playerText).text(player.Name + ": " + player.Score + "/7"); $("#BallAssign").text(players[0].Name + ": " + TypeToString(players[0].BallType) + " " + players[1].Name + ": " + TypeToString(players[1].BallType)); } function TypeToString(nr) { if(nr == 1) return "Whole"; else if(nr == 2) return "Half"; else return "" }
'use strict'; /* ------------------------------------------------------------------------------------------------ CHALLENGE 1 - Review Write a function that iterates over an array of people objects and creates a new list of each person's full name using the array method 'map'. Each object will have the shape {firstName:string, lastName:string} E.g. [ { firstName:"Jane", lastName:"Doe" }, { firstName:"James", lastName:"Bond"}] should convert to ["Jane Doe", "James Bond"] Note the space in between first and last names. You can assume that neither firstName nor lastName will be blank ------------------------------------------------------------------------------------------------ */ const toLastNames = people => { // Solution code here... let array = []; array = people.map(function(a){ return a.firstName + " " + a.lastName }) console.log(array) return array; }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 2 Write a function named addValues that, given an array of numbers as input, uses reduce to add the values in the array. ------------------------------------------------------------------------------------------------ */ const addValues = (arr) => { // Solution code here... return arr.reduce((a,b)=>{ a = a+b; return a; },0) }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 3 Write a function named addPurchases that, given an array of objects as input, uses reduce to find the total amount purchased. Each object contains the keys `item` and `purchasePrice` like the example. { item: 'switch' purchasePrice: 399 } ------------------------------------------------------------------------------------------------ */ const addPurchases = (arr) => { // Solution code here... return arr.reduce((a,b)=>{ a = a+b.purchasePrice; return a; },0) }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 4 Write a function named countNumberOfElements that, given an array as input, uses reduce to count the number of elements in the array. Note: You may not use the array's built-in length property. ------------------------------------------------------------------------------------------------ */ const countNumberOfElements = (arr) => { // Solution code here... return arr.reduce((a,b)=>{ return b; },0) }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 5 Write a function named returnNames that, given the Star Wars data, below, uses reduce to return an array containing the names of the characters. ------------------------------------------------------------------------------------------------ */ let starWarsData = [{ name: 'Luke Skywalker', height: '172', mass: '77', hair_color: 'blond', skin_color: 'fair', eye_color: 'blue', birth_year: '19BBY', gender: 'male', }, { name: 'C-3PO', height: '167', mass: '75', hair_color: 'n/a', skin_color: 'gold', eye_color: 'yellow', birth_year: '112BBY', gender: 'n/a'}, { name: 'R2-D2', height: '96', mass: '32', hair_color: 'n/a', skin_color: 'white, blue', eye_color: 'red', birth_year: '33BBY', gender: 'n/a' }, { name: 'Darth Vader', height: '202', mass: '136', hair_color: 'none', skin_color: 'white', eye_color: 'yellow', birth_year: '41.9BBY', gender: 'male' }, { name: 'Leia Organa', height: '150', mass: '49', hair_color: 'brown', skin_color: 'light', eye_color: 'brown', birth_year: '19BBY', gender: 'female' }]; const returnNames = (arr) => { // Solution code here... let array =[]; return arr.reduce((a,b)=>{ array.push(b.name); return array; },[]) }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 6 Write a function named reversedString that takes in a string and returns a string with the letters in reverse order. Note: You must use reduce for this challenge. You may not use the built-in .reverse() string method. ------------------------------------------------------------------------------------------------ */ const reversedString = (str) => { // Solution code here... let array = []; array=str.split("") return array.reduceRight((a,b)=>{ a = a+b; console.log(a); return a; },) }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 7 - Stretch Goal Write a function named countNumberOfChildren that, given the array of characters, below, uses reduce to return the total number of children in the data set. ------------------------------------------------------------------------------------------------ */ const characters = [ { name: 'Eddard', spouse: 'Catelyn', children: ['Robb', 'Sansa', 'Arya', 'Bran', 'Rickon'], house: 'Stark', }, { name: 'Jon', spouse: 'Lysa', children: ['Robin'], house: 'Arryn', }, { name: 'Cersei', spouse: 'Robert', children: ['Joffrey', 'Myrcella', 'Tommen'], house: 'Lannister', }, { name: 'Daenarys', spouse: 'Khal Drogo', children: ['Drogon', 'Rhaegal', 'Viserion'], house: 'Targaryen', }, { name: 'Mace', spouse: 'Alerie', children: ['Margaery', 'Loras'], house: 'Tyrell', }, { name: 'Sansa', spouse: 'Tyrion', house: 'Stark', }, { name: 'Jon', spouse: null, house: 'Snow', }, ]; const countNumberOfChildren = (arr) => { // Solution code here... }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 8 - Stretch Goal Write a function that, given an array of numbers as input, uses reduce to calculate the array's average value. Hint: The accumulator should begin as { count: 0, sum: 0 } ------------------------------------------------------------------------------------------------ */ const calculateAverage = (arr) => { // Solution code here... }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 9 - Stretch Goal Write a function named countPrimeNumbers that, given an array elements as input, uses reduce to count the number of elements that are prime numbers. You are welcome to use the provided isPrime function. ------------------------------------------------------------------------------------------------ */ const isPrime = (value) => { for (let i = 2; i < value; i++) { if (value % i === 0) { return false; } } return value > 1; }; const countPrimeNumbers = (arr) => { // Solution code here... }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 10 - Stretch Goal Write a function named extractState that, given the snorlaxData, below, uses reduce to return the object whose 'name' property matches the given string. If the input array does not have a stat with that specific name, the function should return null. ------------------------------------------------------------------------------------------------ */ const snorlaxData = { stats: [ { stat: { url: 'https://pokeapi.co/api/v2/stat/6/', name: 'speed', }, effort: 5, baseStat: 30, }, { stat: { url: 'https://pokeapi.co/api/v2/stat/5/', name: 'special-defense', }, effort: 2, baseStat: 110, }, { stat: { url: 'https://pokeapi.co/api/v2/stat/4/', name: 'special-attack', }, effort: 9, baseStat: 65, }, ], name: 'snorlax', weight: 4600, }; const extractStat = (statName, arr) => { // Solution code here... }; /* ------------------------------------------------------------------------------------------------ CHALLENGE 11 - Stretch Goal Write a function named extractChildren that, given the array of characters from challenge 4, accomplishes the following: 1) Uses filter to return an array of the characters that contain the letter 'a' in their name 2) Then, uses reduce to return an array of all the children's names in the filtered array ------------------------------------------------------------------------------------------------ */ const extractChildren = (arr) => { // Solution code here... }; /* ------------------------------------------------------------------------------------------------ TESTS All the code below will verify that your functions are working to solve the challenges. DO NOT CHANGE any of the below code. Run your tests from the console: jest challenges-09.test.js ------------------------------------------------------------------------------------------------ */ describe('Testing challenge 1', () => { test('It should convert object to full name string', () => { const people = [{ firstName: 'Jane', lastName: 'Doe' }, { firstName: 'James', lastName: 'Bond' }]; expect(toLastNames(people)).toStrictEqual(['Jane Doe', 'James Bond']); }); }); describe('Testing challenge 2', () => { test('It should add the values of an array', () => { expect(addValues([1, 2, 3, 4, 5])).toStrictEqual(15); expect(addValues([])).toStrictEqual(0); expect(addValues([1, 2, 3, 4, -5])).toStrictEqual(5); }); }); describe('Testing challenge 3', () => { test('It should add the purchase price', () => { expect(addPurchases([{item: 'switch', purchasePrice: 399}, {item: 'toothpaste', purchasePrice: 2}])).toStrictEqual(401); expect(addPurchases([])).toStrictEqual(0); }); }); describe('Testing challenge 4', () => { test('It should return the length of the array', () => { expect(countNumberOfElements([1, 2, 3, 4, 5])).toStrictEqual(5); }); }); describe('Testing challenge 5', () => { test('It should return an array continaing the names of the characters', () => { expect(returnNames(starWarsData)).toStrictEqual([ 'Luke Skywalker', 'C-3PO', 'R2-D2', 'Darth Vader', 'Leia Organa' ]); expect(returnNames(starWarsData).length).toStrictEqual(5); }); }); describe('Testing challenge 6', () => { test('It should return the string with the characters in reverse order', () => { expect(reversedString('Code 301')).toStrictEqual('103 edoC'); }); }); xdescribe('Testing challenge 7', () => { test('It should return the total number of children', () => { expect(countNumberOfChildren(characters)).toStrictEqual(14); }); }); xdescribe('Testing challenge 8', () => { test('It should return the average of the numbers in the array', () => { expect(calculateAverage([18, 290, 37, 4, 55, 16, 7, 85 ])).toStrictEqual(64); }); }); xdescribe('Testing challenge 9', () => { test('It should return a count of the prime numbers in the array', () => { expect(countPrimeNumbers([1, 2, 13, 64, 45, 56, 17, 8])).toStrictEqual(3); }); }); xdescribe('Testing challenge 10', () => { test('It should return any stats that match the input', () => { expect(extractStat('speed', snorlaxData.stats)).toStrictEqual({ stat: { url: 'https://pokeapi.co/api/v2/stat/6/', name: 'speed' }, effort: 5, baseStat: 30 }); }); }); xdescribe('Testing challenge 11', () => { test('It should return an array containing the names of the children', () => { expect(extractChildren(characters)).toStrictEqual([ 'Robb', 'Sansa', 'Arya', 'Bran', 'Rickon', 'Drogon', 'Rhaegal', 'Viserion', 'Margaery', 'Loras' ]); expect(extractChildren(characters).length).toStrictEqual(10); }); });
import React from 'react'; import PropTypes from 'prop-types'; const Author = ({firstName, lastName}) => { const fullName = (firstName || lastName ) ? `${firstName || ''} ${lastName || ''}` : 'Anonymous'; return ( <span> {`Author: ${fullName}`} </span> ) }; Author.propTypes = { firstName: PropTypes.string.isRequired, lastName: PropTypes.string.isRequired }; export default Author;
ace.define("ace/mode/csound_preprocessor_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var CsoundPreprocessorHighlightRules = function(embeddedRulePrefix) { this.embeddedRulePrefix = embeddedRulePrefix === undefined ? "" : embeddedRulePrefix; this.semicolonComments = { token: "comment.line.semicolon.csound", regex: ";.*$" }; this.comments = [ { token: "punctuation.definition.comment.begin.csound", regex: "/\\*", push: [ { token: "punctuation.definition.comment.end.csound", regex: "\\*/", next: "pop" }, { defaultToken: "comment.block.csound" } ] }, { token: "comment.line.double-slash.csound", regex: "//.*$" }, this.semicolonComments ]; this.macroUses = [ { token: ["entity.name.function.preprocessor.csound", "punctuation.definition.macro-parameter-value-list.begin.csound"], regex: /(\$[A-Z_a-z]\w*\.?)(\()/, next: "macro parameter value list" }, { token: "entity.name.function.preprocessor.csound", regex: /\$[A-Z_a-z]\w*(?:\.|\b)/ } ]; this.numbers = [ { token: "constant.numeric.float.csound", regex: /(?:\d+[Ee][+-]?\d+)|(?:\d+\.\d*|\d*\.\d+)(?:[Ee][+-]?\d+)?/ }, { token: ["storage.type.number.csound", "constant.numeric.integer.hexadecimal.csound"], regex: /(0[Xx])([0-9A-Fa-f]+)/ }, { token: "constant.numeric.integer.decimal.csound", regex: /\d+/ } ]; this.bracedStringContents = [ { token: "constant.character.escape.csound", regex: /\\(?:[\\abnrt"]|[0-7]{1,3})/ }, { token: "constant.character.placeholder.csound", regex: /%[#0\- +]*\d*(?:\.\d+)?[diuoxXfFeEgGaAcs]/ }, { token: "constant.character.escape.csound", regex: /%%/ } ]; this.quotedStringContents = [ this.macroUses, this.bracedStringContents ]; var start = [ this.comments, { token: "keyword.preprocessor.csound", regex: /#(?:e(?:nd(?:if)?|lse)\b|##)|@@?[ \t]*\d+/ }, { token: "keyword.preprocessor.csound", regex: /#include/, push: [ this.comments, { token: "string.csound", regex: /([^ \t])(?:.*?\1)/, next: "pop" } ] }, { token: "keyword.preprocessor.csound", regex: /#includestr/, push: [ this.comments, { token: "string.csound", regex: /([^ \t])(?:.*?\1)/, next: "pop" } ] }, { token: "keyword.preprocessor.csound", regex: /#[ \t]*define/, next: "define directive" }, { token: "keyword.preprocessor.csound", regex: /#(?:ifn?def|undef)\b/, next: "macro directive" }, this.macroUses ]; this.$rules = { "start": start, "define directive": [ this.comments, { token: "entity.name.function.preprocessor.csound", regex: /[A-Z_a-z]\w*/ }, { token: "punctuation.definition.macro-parameter-name-list.begin.csound", regex: /\(/, next: "macro parameter name list" }, { token: "punctuation.definition.macro.begin.csound", regex: /#/, next: "macro body" } ], "macro parameter name list": [ { token: "variable.parameter.preprocessor.csound", regex: /[A-Z_a-z]\w*/ }, { token: "punctuation.definition.macro-parameter-name-list.end.csound", regex: /\)/, next: "define directive" } ], "macro body": [ { token: "constant.character.escape.csound", regex: /\\#/ }, { token: "punctuation.definition.macro.end.csound", regex: /#/, next: "start" }, start ], "macro directive": [ this.comments, { token: "entity.name.function.preprocessor.csound", regex: /[A-Z_a-z]\w*/, next: "start" } ], "macro parameter value list": [ { token: "punctuation.definition.macro-parameter-value-list.end.csound", regex: /\)/, next: "start" }, { token: "punctuation.definition.string.begin.csound", regex: /"/, next: "macro parameter value quoted string" }, this.pushRule({ token: "punctuation.macro-parameter-value-parenthetical.begin.csound", regex: /\(/, next: "macro parameter value parenthetical" }), { token: "punctuation.macro-parameter-value-separator.csound", regex: "[#']" } ], "macro parameter value quoted string": [ { token: "constant.character.escape.csound", regex: /\\[#'()]/ }, { token: "invalid.illegal.csound", regex: /[#'()]/ }, { token: "punctuation.definition.string.end.csound", regex: /"/, next: "macro parameter value list" }, this.quotedStringContents, { defaultToken: "string.quoted.csound" } ], "macro parameter value parenthetical": [ { token: "constant.character.escape.csound", regex: /\\\)/ }, this.popRule({ token: "punctuation.macro-parameter-value-parenthetical.end.csound", regex: /\)/ }), this.pushRule({ token: "punctuation.macro-parameter-value-parenthetical.begin.csound", regex: /\(/, next: "macro parameter value parenthetical" }), start ] }; }; oop.inherits(CsoundPreprocessorHighlightRules, TextHighlightRules); (function() { this.pushRule = function(params) { if (Array.isArray(params.next)) { for (var i = 0; i < params.next.length; i++) { params.next[i] = this.embeddedRulePrefix + params.next[i]; } } return { regex: params.regex, onMatch: function(value, currentState, stack, line) { if (stack.length === 0) stack.push(currentState); if (Array.isArray(params.next)) { for (var i = 0; i < params.next.length; i++) { stack.push(params.next[i]); } } else { stack.push(params.next); } this.next = stack[stack.length - 1]; return params.token; }, get next() { return Array.isArray(params.next) ? params.next[params.next.length - 1] : params.next; }, set next(next) { if (!Array.isArray(params.next)) { params.next = next; } }, get token() { return params.token; } }; }; this.popRule = function(params) { if (params.next) { params.next = this.embeddedRulePrefix + params.next; } return { regex: params.regex, onMatch: function(value, currentState, stack, line) { stack.pop(); if (params.next) { stack.push(params.next); this.next = stack[stack.length - 1]; } else { this.next = stack.length > 1 ? stack[stack.length - 1] : stack.pop(); } return params.token; } }; }; }).call(CsoundPreprocessorHighlightRules.prototype); exports.CsoundPreprocessorHighlightRules = CsoundPreprocessorHighlightRules; }); ace.define("ace/mode/csound_score_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/csound_preprocessor_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var CsoundPreprocessorHighlightRules = require("./csound_preprocessor_highlight_rules").CsoundPreprocessorHighlightRules; var CsoundScoreHighlightRules = function(embeddedRulePrefix) { CsoundPreprocessorHighlightRules.call(this, embeddedRulePrefix); this.quotedStringContents.push({ token: "invalid.illegal.csound-score", regex: /[^"]*$/ }); var start = this.$rules.start; start.push({ token: "keyword.control.csound-score", regex: /[abCdefiqstvxy]/ }, { token: "invalid.illegal.csound-score", regex: /w/ }, { token: "constant.numeric.language.csound-score", regex: /z/ }, { token: ["keyword.control.csound-score", "constant.numeric.integer.decimal.csound-score"], regex: /([nNpP][pP])(\d+)/ }, { token: "keyword.other.csound-score", regex: /[mn]/, push: [ { token: "empty", regex: /$/, next: "pop" }, this.comments, { token: "entity.name.label.csound-score", regex: /[A-Z_a-z]\w*/ } ] }, { token: "keyword.preprocessor.csound-score", regex: /r\b/, next: "repeat section" }, this.numbers, { token: "keyword.operator.csound-score", regex: "[!+\\-*/^%&|<>#~.]" }, this.pushRule({ token: "punctuation.definition.string.begin.csound-score", regex: /"/, next: "quoted string" }), this.pushRule({ token: "punctuation.braced-loop.begin.csound-score", regex: /{/, next: "loop after left brace" }) ); this.addRules({ "repeat section": [ { token: "empty", regex: /$/, next: "start" }, this.comments, { token: "constant.numeric.integer.decimal.csound-score", regex: /\d+/, next: "repeat section before label" } ], "repeat section before label": [ { token: "empty", regex: /$/, next: "start" }, this.comments, { token: "entity.name.label.csound-score", regex: /[A-Z_a-z]\w*/, next: "start" } ], "quoted string": [ this.popRule({ token: "punctuation.definition.string.end.csound-score", regex: /"/ }), this.quotedStringContents, { defaultToken: "string.quoted.csound-score" } ], "loop after left brace": [ this.popRule({ token: "constant.numeric.integer.decimal.csound-score", regex: /\d+/, next: "loop after repeat count" }), this.comments, { token: "invalid.illegal.csound", regex: /\S.*/ } ], "loop after repeat count": [ this.popRule({ token: "entity.name.function.preprocessor.csound-score", regex: /[A-Z_a-z]\w*\b/, next: "loop after macro name" }), this.comments, { token: "invalid.illegal.csound", regex: /\S.*/ } ], "loop after macro name": [ start, this.popRule({ token: "punctuation.braced-loop.end.csound-score", regex: /}/ }) ] }); this.normalizeRules(); }; oop.inherits(CsoundScoreHighlightRules, CsoundPreprocessorHighlightRules); exports.CsoundScoreHighlightRules = CsoundScoreHighlightRules; }); ace.define("ace/mode/lua_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var LuaHighlightRules = function() { var keywords = ( "break|do|else|elseif|end|for|function|if|in|local|repeat|" + "return|then|until|while|or|and|not" ); var builtinConstants = ("true|false|nil|_G|_VERSION"); var functions = ( "string|xpcall|package|tostring|print|os|unpack|require|" + "getfenv|setmetatable|next|assert|tonumber|io|rawequal|" + "collectgarbage|getmetatable|module|rawset|math|debug|" + "pcall|table|newproxy|type|coroutine|_G|select|gcinfo|" + "pairs|rawget|loadstring|ipairs|_VERSION|dofile|setfenv|" + "load|error|loadfile|" + "sub|upper|len|gfind|rep|find|match|char|dump|gmatch|" + "reverse|byte|format|gsub|lower|preload|loadlib|loaded|" + "loaders|cpath|config|path|seeall|exit|setlocale|date|" + "getenv|difftime|remove|time|clock|tmpname|rename|execute|" + "lines|write|close|flush|open|output|type|read|stderr|" + "stdin|input|stdout|popen|tmpfile|log|max|acos|huge|" + "ldexp|pi|cos|tanh|pow|deg|tan|cosh|sinh|random|randomseed|" + "frexp|ceil|floor|rad|abs|sqrt|modf|asin|min|mod|fmod|log10|" + "atan2|exp|sin|atan|getupvalue|debug|sethook|getmetatable|" + "gethook|setmetatable|setlocal|traceback|setfenv|getinfo|" + "setupvalue|getlocal|getregistry|getfenv|setn|insert|getn|" + "foreachi|maxn|foreach|concat|sort|remove|resume|yield|" + "status|wrap|create|running|" + "__add|__sub|__mod|__unm|__concat|__lt|__index|__call|__gc|__metatable|" + "__mul|__div|__pow|__len|__eq|__le|__newindex|__tostring|__mode|__tonumber" ); var stdLibaries = ("string|package|os|io|math|debug|table|coroutine"); var deprecatedIn5152 = ("setn|foreach|foreachi|gcinfo|log10|maxn"); var keywordMapper = this.createKeywordMapper({ "keyword": keywords, "support.function": functions, "keyword.deprecated": deprecatedIn5152, "constant.library": stdLibaries, "constant.language": builtinConstants, "variable.language": "self" }, "identifier"); var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))"; var hexInteger = "(?:0[xX][\\dA-Fa-f]+)"; var integer = "(?:" + decimalInteger + "|" + hexInteger + ")"; var fraction = "(?:\\.\\d+)"; var intPart = "(?:\\d+)"; var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; var floatNumber = "(?:" + pointFloat + ")"; this.$rules = { "start": [{ stateName: "bracketedComment", onMatch: function(value, currentState, stack) { stack.unshift(this.next, value.length - 2, currentState); return "comment"; }, regex: /\-\-\[=*\[/, next: [ { onMatch: function(value, currentState, stack) { if (value.length == stack[1]) { stack.shift(); stack.shift(); this.next = stack.shift(); } else { this.next = ""; } return "comment"; }, regex: /\]=*\]/, next: "start" }, { defaultToken: "comment" } ] }, { token: "comment", regex: "\\-\\-.*$" }, { stateName: "bracketedString", onMatch: function(value, currentState, stack) { stack.unshift(this.next, value.length, currentState); return "string.start"; }, regex: /\[=*\[/, next: [ { onMatch: function(value, currentState, stack) { if (value.length == stack[1]) { stack.shift(); stack.shift(); this.next = stack.shift(); } else { this.next = ""; } return "string.end"; }, regex: /\]=*\]/, next: "start" }, { defaultToken: "string" } ] }, { token: "string", // " string regex: '"(?:[^\\\\]|\\\\.)*?"' }, { token: "string", // ' string regex: "'(?:[^\\\\]|\\\\.)*?'" }, { token: "constant.numeric", // float regex: floatNumber }, { token: "constant.numeric", // integer regex: integer + "\\b" }, { token: keywordMapper, regex: "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token: "keyword.operator", regex: "\\+|\\-|\\*|\\/|%|\\#|\\^|~|<|>|<=|=>|==|~=|=|\\:|\\.\\.\\.|\\.\\." }, { token: "paren.lparen", regex: "[\\[\\(\\{]" }, { token: "paren.rparen", regex: "[\\]\\)\\}]" }, { token: "text", regex: "\\s+|\\w+" }] }; this.normalizeRules(); }; oop.inherits(LuaHighlightRules, TextHighlightRules); exports.LuaHighlightRules = LuaHighlightRules; }); ace.define("ace/mode/python_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var PythonHighlightRules = function() { var keywords = ( "and|as|assert|break|class|continue|def|del|elif|else|except|exec|" + "finally|for|from|global|if|import|in|is|lambda|not|or|pass|print|" + "raise|return|try|while|with|yield|async|await|nonlocal" ); var builtinConstants = ( "True|False|None|NotImplemented|Ellipsis|__debug__" ); var builtinFunctions = ( "abs|divmod|input|open|staticmethod|all|enumerate|int|ord|str|any|" + "eval|isinstance|pow|sum|basestring|execfile|issubclass|print|super|" + "binfile|bin|iter|property|tuple|bool|filter|len|range|type|bytearray|" + "float|list|raw_input|unichr|callable|format|locals|reduce|unicode|" + "chr|frozenset|long|reload|vars|classmethod|getattr|map|repr|xrange|" + "cmp|globals|max|reversed|zip|compile|hasattr|memoryview|round|" + "__import__|complex|hash|min|apply|delattr|help|next|setattr|set|" + "buffer|dict|hex|object|slice|coerce|dir|id|oct|sorted|intern|" + "ascii|breakpoint|bytes" ); var keywordMapper = this.createKeywordMapper({ "invalid.deprecated": "debugger", "support.function": builtinFunctions, "variable.language": "self|cls", "constant.language": builtinConstants, "keyword": keywords }, "identifier"); var strPre = "[uU]?"; var strRawPre = "[rR]"; var strFormatPre = "[fF]"; var strRawFormatPre = "(?:[rR][fF]|[fF][rR])"; var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))"; var octInteger = "(?:0[oO]?[0-7]+)"; var hexInteger = "(?:0[xX][\\dA-Fa-f]+)"; var binInteger = "(?:0[bB][01]+)"; var integer = "(?:" + decimalInteger + "|" + octInteger + "|" + hexInteger + "|" + binInteger + ")"; var exponent = "(?:[eE][+-]?\\d+)"; var fraction = "(?:\\.\\d+)"; var intPart = "(?:\\d+)"; var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; var exponentFloat = "(?:(?:" + pointFloat + "|" + intPart + ")" + exponent + ")"; var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")"; var stringEscape = "\\\\(x[0-9A-Fa-f]{2}|[0-7]{3}|[\\\\abfnrtv'\"]|U[0-9A-Fa-f]{8}|u[0-9A-Fa-f]{4})"; this.$rules = { "start": [{ token: "comment", regex: "#.*$" }, { token: "string", // multi line """ string start regex: strPre + '"{3}', next: "qqstring3" }, { token: "string", // " string regex: strPre + '"(?=.)', next: "qqstring" }, { token: "string", // multi line ''' string start regex: strPre + "'{3}", next: "qstring3" }, { token: "string", // ' string regex: strPre + "'(?=.)", next: "qstring" }, { token: "string", regex: strRawPre + '"{3}', next: "rawqqstring3" }, { token: "string", regex: strRawPre + '"(?=.)', next: "rawqqstring" }, { token: "string", regex: strRawPre + "'{3}", next: "rawqstring3" }, { token: "string", regex: strRawPre + "'(?=.)", next: "rawqstring" }, { token: "string", regex: strFormatPre + '"{3}', next: "fqqstring3" }, { token: "string", regex: strFormatPre + '"(?=.)', next: "fqqstring" }, { token: "string", regex: strFormatPre + "'{3}", next: "fqstring3" }, { token: "string", regex: strFormatPre + "'(?=.)", next: "fqstring" }, { token: "string", regex: strRawFormatPre + '"{3}', next: "rfqqstring3" }, { token: "string", regex: strRawFormatPre + '"(?=.)', next: "rfqqstring" }, { token: "string", regex: strRawFormatPre + "'{3}", next: "rfqstring3" }, { token: "string", regex: strRawFormatPre + "'(?=.)", next: "rfqstring" }, { token: "keyword.operator", regex: "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|%|@|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|=" }, { token: "punctuation", regex: ",|:|;|\\->|\\+=|\\-=|\\*=|\\/=|\\/\\/=|%=|@=|&=|\\|=|^=|>>=|<<=|\\*\\*=" }, { token: "paren.lparen", regex: "[\\[\\(\\{]" }, { token: "paren.rparen", regex: "[\\]\\)\\}]" }, { token: "text", regex: "\\s+" }, { include: "constants" }], "qqstring3": [{ token: "constant.language.escape", regex: stringEscape }, { token: "string", // multi line """ string end regex: '"{3}', next: "start" }, { defaultToken: "string" }], "qstring3": [{ token: "constant.language.escape", regex: stringEscape }, { token: "string", // multi line ''' string end regex: "'{3}", next: "start" }, { defaultToken: "string" }], "qqstring": [{ token: "constant.language.escape", regex: stringEscape }, { token: "string", regex: "\\\\$", next: "qqstring" }, { token: "string", regex: '"|$', next: "start" }, { defaultToken: "string" }], "qstring": [{ token: "constant.language.escape", regex: stringEscape }, { token: "string", regex: "\\\\$", next: "qstring" }, { token: "string", regex: "'|$", next: "start" }, { defaultToken: "string" }], "rawqqstring3": [{ token: "string", // multi line """ string end regex: '"{3}', next: "start" }, { defaultToken: "string" }], "rawqstring3": [{ token: "string", // multi line ''' string end regex: "'{3}", next: "start" }, { defaultToken: "string" }], "rawqqstring": [{ token: "string", regex: "\\\\$", next: "rawqqstring" }, { token: "string", regex: '"|$', next: "start" }, { defaultToken: "string" }], "rawqstring": [{ token: "string", regex: "\\\\$", next: "rawqstring" }, { token: "string", regex: "'|$", next: "start" }, { defaultToken: "string" }], "fqqstring3": [{ token: "constant.language.escape", regex: stringEscape }, { token: "string", // multi line """ string end regex: '"{3}', next: "start" }, { token: "paren.lparen", regex: "{", push: "fqstringParRules" }, { defaultToken: "string" }], "fqstring3": [{ token: "constant.language.escape", regex: stringEscape }, { token: "string", // multi line ''' string end regex: "'{3}", next: "start" }, { token: "paren.lparen", regex: "{", push: "fqstringParRules" }, { defaultToken: "string" }], "fqqstring": [{ token: "constant.language.escape", regex: stringEscape }, { token: "string", regex: "\\\\$", next: "fqqstring" }, { token: "string", regex: '"|$', next: "start" }, { token: "paren.lparen", regex: "{", push: "fqstringParRules" }, { defaultToken: "string" }], "fqstring": [{ token: "constant.language.escape", regex: stringEscape }, { token: "string", regex: "'|$", next: "start" }, { token: "paren.lparen", regex: "{", push: "fqstringParRules" }, { defaultToken: "string" }], "rfqqstring3": [{ token: "string", // multi line """ string end regex: '"{3}', next: "start" }, { token: "paren.lparen", regex: "{", push: "fqstringParRules" }, { defaultToken: "string" }], "rfqstring3": [{ token: "string", // multi line ''' string end regex: "'{3}", next: "start" }, { token: "paren.lparen", regex: "{", push: "fqstringParRules" }, { defaultToken: "string" }], "rfqqstring": [{ token: "string", regex: "\\\\$", next: "rfqqstring" }, { token: "string", regex: '"|$', next: "start" }, { token: "paren.lparen", regex: "{", push: "fqstringParRules" }, { defaultToken: "string" }], "rfqstring": [{ token: "string", regex: "'|$", next: "start" }, { token: "paren.lparen", regex: "{", push: "fqstringParRules" }, { defaultToken: "string" }], "fqstringParRules": [{ //TODO: nested {} token: "paren.lparen", regex: "[\\[\\(]" }, { token: "paren.rparen", regex: "[\\]\\)]" }, { token: "string", regex: "\\s+" }, { token: "string", regex: "'[^']*'" }, { token: "string", regex: '"[^"]*"' }, { token: "function.support", regex: "(!s|!r|!a)" }, { include: "constants" }, { token: 'paren.rparen', regex: "}", next: 'pop' }, { token: 'paren.lparen', regex: "{", push: "fqstringParRules" }], "constants": [{ token: "constant.numeric", // imaginary regex: "(?:" + floatNumber + "|\\d+)[jJ]\\b" }, { token: "constant.numeric", // float regex: floatNumber }, { token: "constant.numeric", // long integer regex: integer + "[lL]\\b" }, { token: "constant.numeric", // integer regex: integer + "\\b" }, { token: ["punctuation", "function.support"], // method regex: "(\\.)([a-zA-Z_]+)\\b" }, { token: keywordMapper, regex: "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }] }; this.normalizeRules(); }; oop.inherits(PythonHighlightRules, TextHighlightRules); exports.PythonHighlightRules = PythonHighlightRules; }); ace.define("ace/mode/csound_orchestra_highlight_rules", ["require", "exports", "module", "ace/lib/lang", "ace/lib/oop", "ace/mode/csound_preprocessor_highlight_rules", "ace/mode/csound_score_highlight_rules", "ace/mode/lua_highlight_rules", "ace/mode/python_highlight_rules"], function(require, exports, module) { "use strict"; var lang = require("../lib/lang"); var oop = require("../lib/oop"); var CsoundPreprocessorHighlightRules = require("./csound_preprocessor_highlight_rules").CsoundPreprocessorHighlightRules; var CsoundScoreHighlightRules = require("./csound_score_highlight_rules").CsoundScoreHighlightRules; var LuaHighlightRules = require("./lua_highlight_rules").LuaHighlightRules; var PythonHighlightRules = require("./python_highlight_rules").PythonHighlightRules; var CsoundOrchestraHighlightRules = function(embeddedRulePrefix) { CsoundPreprocessorHighlightRules.call(this, embeddedRulePrefix); var opcodes = [ "ATSadd", "ATSaddnz", "ATSbufread", "ATScross", "ATSinfo", "ATSinterpread", "ATSpartialtap", "ATSread", "ATSreadnz", "ATSsinnoi", "FLbox", "FLbutBank", "FLbutton", "FLcloseButton", "FLcolor", "FLcolor2", "FLcount", "FLexecButton", "FLgetsnap", "FLgroup", "FLgroupEnd", "FLgroup_end", "FLhide", "FLhvsBox", "FLhvsBoxSetValue", "FLjoy", "FLkeyIn", "FLknob", "FLlabel", "FLloadsnap", "FLmouse", "FLpack", "FLpackEnd", "FLpack_end", "FLpanel", "FLpanelEnd", "FLpanel_end", "FLprintk", "FLprintk2", "FLroller", "FLrun", "FLsavesnap", "FLscroll", "FLscrollEnd", "FLscroll_end", "FLsetAlign", "FLsetBox", "FLsetColor", "FLsetColor2", "FLsetFont", "FLsetPosition", "FLsetSize", "FLsetSnapGroup", "FLsetText", "FLsetTextColor", "FLsetTextSize", "FLsetTextType", "FLsetVal", "FLsetVal_i", "FLsetVali", "FLsetsnap", "FLshow", "FLslidBnk", "FLslidBnk2", "FLslidBnk2Set", "FLslidBnk2Setk", "FLslidBnkGetHandle", "FLslidBnkSet", "FLslidBnkSetk", "FLslider", "FLtabs", "FLtabsEnd", "FLtabs_end", "FLtext", "FLupdate", "FLvalue", "FLvkeybd", "FLvslidBnk", "FLvslidBnk2", "FLxyin", "JackoAudioIn", "JackoAudioInConnect", "JackoAudioOut", "JackoAudioOutConnect", "JackoFreewheel", "JackoInfo", "JackoInit", "JackoMidiInConnect", "JackoMidiOut", "JackoMidiOutConnect", "JackoNoteOut", "JackoOn", "JackoTransport", "K35_hpf", "K35_lpf", "MixerClear", "MixerGetLevel", "MixerReceive", "MixerSend", "MixerSetLevel", "MixerSetLevel_i", "OSCbundle", "OSCcount", "OSCinit", "OSCinitM", "OSClisten", "OSCraw", "OSCsend", "OSCsend_lo", "S", "STKBandedWG", "STKBeeThree", "STKBlowBotl", "STKBlowHole", "STKBowed", "STKBrass", "STKClarinet", "STKDrummer", "STKFMVoices", "STKFlute", "STKHevyMetl", "STKMandolin", "STKModalBar", "STKMoog", "STKPercFlut", "STKPlucked", "STKResonate", "STKRhodey", "STKSaxofony", "STKShakers", "STKSimple", "STKSitar", "STKStifKarp", "STKTubeBell", "STKVoicForm", "STKWhistle", "STKWurley", "a", "abs", "active", "adsr", "adsyn", "adsynt", "adsynt2", "aftouch", "alpass", "alwayson", "ampdb", "ampdbfs", "ampmidi", "ampmidicurve", "ampmidid", "areson", "aresonk", "atone", "atonek", "atonex", "babo", "balance", "balance2", "bamboo", "barmodel", "bbcutm", "bbcuts", "beadsynt", "beosc", "betarand", "bexprnd", "bformdec1", "bformenc1", "binit", "biquad", "biquada", "birnd", "bpf", "bpfcos", "bqrez", "butbp", "butbr", "buthp", "butlp", "butterbp", "butterbr", "butterhp", "butterlp", "button", "buzz", "c2r", "cabasa", "cauchy", "cauchyi", "cbrt", "ceil", "cell", "cent", "centroid", "ceps", "cepsinv", "chanctrl", "changed2", "chani", "chano", "chebyshevpoly", "checkbox", "chn_S", "chn_a", "chn_k", "chnclear", "chnexport", "chnget", "chngeta", "chngeti", "chngetk", "chngetks", "chngets", "chnmix", "chnparams", "chnset", "chnseta", "chnseti", "chnsetk", "chnsetks", "chnsets", "chuap", "clear", "clfilt", "clip", "clockoff", "clockon", "cmp", "cmplxprod", "comb", "combinv", "compilecsd", "compileorc", "compilestr", "compress", "compress2", "connect", "control", "convle", "convolve", "copya2ftab", "copyf2array", "cos", "cosh", "cosinv", "cosseg", "cossegb", "cossegr", "cps2pch", "cpsmidi", "cpsmidib", "cpsmidinn", "cpsoct", "cpspch", "cpstmid", "cpstun", "cpstuni", "cpsxpch", "cpumeter", "cpuprc", "cross2", "crossfm", "crossfmi", "crossfmpm", "crossfmpmi", "crosspm", "crosspmi", "crunch", "ctlchn", "ctrl14", "ctrl21", "ctrl7", "ctrlinit", "cuserrnd", "dam", "date", "dates", "db", "dbamp", "dbfsamp", "dcblock", "dcblock2", "dconv", "dct", "dctinv", "deinterleave", "delay", "delay1", "delayk", "delayr", "delayw", "deltap", "deltap3", "deltapi", "deltapn", "deltapx", "deltapxw", "denorm", "diff", "diode_ladder", "directory", "diskgrain", "diskin", "diskin2", "dispfft", "display", "distort", "distort1", "divz", "doppler", "dot", "downsamp", "dripwater", "dssiactivate", "dssiaudio", "dssictls", "dssiinit", "dssilist", "dumpk", "dumpk2", "dumpk3", "dumpk4", "duserrnd", "dust", "dust2", "envlpx", "envlpxr", "ephasor", "eqfil", "evalstr", "event", "event_i", "exciter", "exitnow", "exp", "expcurve", "expon", "exprand", "exprandi", "expseg", "expsega", "expsegb", "expsegba", "expsegr", "fareylen", "fareyleni", "faustaudio", "faustcompile", "faustctl", "faustdsp", "faustgen", "faustplay", "fft", "fftinv", "ficlose", "filebit", "filelen", "filenchnls", "filepeak", "filescal", "filesr", "filevalid", "fillarray", "filter2", "fin", "fini", "fink", "fiopen", "flanger", "flashtxt", "flooper", "flooper2", "floor", "fluidAllOut", "fluidCCi", "fluidCCk", "fluidControl", "fluidEngine", "fluidInfo", "fluidLoad", "fluidNote", "fluidOut", "fluidProgramSelect", "fluidSetInterpMethod", "fmanal", "fmax", "fmb3", "fmbell", "fmin", "fmmetal", "fmod", "fmpercfl", "fmrhode", "fmvoice", "fmwurlie", "fof", "fof2", "fofilter", "fog", "fold", "follow", "follow2", "foscil", "foscili", "fout", "fouti", "foutir", "foutk", "fprintks", "fprints", "frac", "fractalnoise", "framebuffer", "freeverb", "ftaudio", "ftchnls", "ftconv", "ftcps", "ftexists", "ftfree", "ftgen", "ftgenonce", "ftgentmp", "ftlen", "ftload", "ftloadk", "ftlptim", "ftmorf", "ftom", "ftprint", "ftresize", "ftresizei", "ftsamplebank", "ftsave", "ftsavek", "ftslice", "ftsr", "gain", "gainslider", "gauss", "gaussi", "gausstrig", "gbuzz", "genarray", "genarray_i", "gendy", "gendyc", "gendyx", "getcfg", "getcol", "getftargs", "getrow", "getrowlin", "getseed", "gogobel", "grain", "grain2", "grain3", "granule", "gtf", "guiro", "harmon", "harmon2", "harmon3", "harmon4", "hdf5read", "hdf5write", "hilbert", "hilbert2", "hrtfearly", "hrtfmove", "hrtfmove2", "hrtfreverb", "hrtfstat", "hsboscil", "hvs1", "hvs2", "hvs3", "hypot", "i", "ihold", "imagecreate", "imagefree", "imagegetpixel", "imageload", "imagesave", "imagesetpixel", "imagesize", "in", "in32", "inch", "inh", "init", "initc14", "initc21", "initc7", "inleta", "inletf", "inletk", "inletkid", "inletv", "ino", "inq", "inrg", "ins", "insglobal", "insremot", "int", "integ", "interleave", "interp", "invalue", "inx", "inz", "jacktransport", "jitter", "jitter2", "joystick", "jspline", "k", "la_i_add_mc", "la_i_add_mr", "la_i_add_vc", "la_i_add_vr", "la_i_assign_mc", "la_i_assign_mr", "la_i_assign_t", "la_i_assign_vc", "la_i_assign_vr", "la_i_conjugate_mc", "la_i_conjugate_mr", "la_i_conjugate_vc", "la_i_conjugate_vr", "la_i_distance_vc", "la_i_distance_vr", "la_i_divide_mc", "la_i_divide_mr", "la_i_divide_vc", "la_i_divide_vr", "la_i_dot_mc", "la_i_dot_mc_vc", "la_i_dot_mr", "la_i_dot_mr_vr", "la_i_dot_vc", "la_i_dot_vr", "la_i_get_mc", "la_i_get_mr", "la_i_get_vc", "la_i_get_vr", "la_i_invert_mc", "la_i_invert_mr", "la_i_lower_solve_mc", "la_i_lower_solve_mr", "la_i_lu_det_mc", "la_i_lu_det_mr", "la_i_lu_factor_mc", "la_i_lu_factor_mr", "la_i_lu_solve_mc", "la_i_lu_solve_mr", "la_i_mc_create", "la_i_mc_set", "la_i_mr_create", "la_i_mr_set", "la_i_multiply_mc", "la_i_multiply_mr", "la_i_multiply_vc", "la_i_multiply_vr", "la_i_norm1_mc", "la_i_norm1_mr", "la_i_norm1_vc", "la_i_norm1_vr", "la_i_norm_euclid_mc", "la_i_norm_euclid_mr", "la_i_norm_euclid_vc", "la_i_norm_euclid_vr", "la_i_norm_inf_mc", "la_i_norm_inf_mr", "la_i_norm_inf_vc", "la_i_norm_inf_vr", "la_i_norm_max_mc", "la_i_norm_max_mr", "la_i_print_mc", "la_i_print_mr", "la_i_print_vc", "la_i_print_vr", "la_i_qr_eigen_mc", "la_i_qr_eigen_mr", "la_i_qr_factor_mc", "la_i_qr_factor_mr", "la_i_qr_sym_eigen_mc", "la_i_qr_sym_eigen_mr", "la_i_random_mc", "la_i_random_mr", "la_i_random_vc", "la_i_random_vr", "la_i_size_mc", "la_i_size_mr", "la_i_size_vc", "la_i_size_vr", "la_i_subtract_mc", "la_i_subtract_mr", "la_i_subtract_vc", "la_i_subtract_vr", "la_i_t_assign", "la_i_trace_mc", "la_i_trace_mr", "la_i_transpose_mc", "la_i_transpose_mr", "la_i_upper_solve_mc", "la_i_upper_solve_mr", "la_i_vc_create", "la_i_vc_set", "la_i_vr_create", "la_i_vr_set", "la_k_a_assign", "la_k_add_mc", "la_k_add_mr", "la_k_add_vc", "la_k_add_vr", "la_k_assign_a", "la_k_assign_f", "la_k_assign_mc", "la_k_assign_mr", "la_k_assign_t", "la_k_assign_vc", "la_k_assign_vr", "la_k_conjugate_mc", "la_k_conjugate_mr", "la_k_conjugate_vc", "la_k_conjugate_vr", "la_k_current_f", "la_k_current_vr", "la_k_distance_vc", "la_k_distance_vr", "la_k_divide_mc", "la_k_divide_mr", "la_k_divide_vc", "la_k_divide_vr", "la_k_dot_mc", "la_k_dot_mc_vc", "la_k_dot_mr", "la_k_dot_mr_vr", "la_k_dot_vc", "la_k_dot_vr", "la_k_f_assign", "la_k_get_mc", "la_k_get_mr", "la_k_get_vc", "la_k_get_vr", "la_k_invert_mc", "la_k_invert_mr", "la_k_lower_solve_mc", "la_k_lower_solve_mr", "la_k_lu_det_mc", "la_k_lu_det_mr", "la_k_lu_factor_mc", "la_k_lu_factor_mr", "la_k_lu_solve_mc", "la_k_lu_solve_mr", "la_k_mc_set", "la_k_mr_set", "la_k_multiply_mc", "la_k_multiply_mr", "la_k_multiply_vc", "la_k_multiply_vr", "la_k_norm1_mc", "la_k_norm1_mr", "la_k_norm1_vc", "la_k_norm1_vr", "la_k_norm_euclid_mc", "la_k_norm_euclid_mr", "la_k_norm_euclid_vc", "la_k_norm_euclid_vr", "la_k_norm_inf_mc", "la_k_norm_inf_mr", "la_k_norm_inf_vc", "la_k_norm_inf_vr", "la_k_norm_max_mc", "la_k_norm_max_mr", "la_k_qr_eigen_mc", "la_k_qr_eigen_mr", "la_k_qr_factor_mc", "la_k_qr_factor_mr", "la_k_qr_sym_eigen_mc", "la_k_qr_sym_eigen_mr", "la_k_random_mc", "la_k_random_mr", "la_k_random_vc", "la_k_random_vr", "la_k_subtract_mc", "la_k_subtract_mr", "la_k_subtract_vc", "la_k_subtract_vr", "la_k_t_assign", "la_k_trace_mc", "la_k_trace_mr", "la_k_upper_solve_mc", "la_k_upper_solve_mr", "la_k_vc_set", "la_k_vr_set", "lastcycle", "lenarray", "lfo", "limit", "limit1", "lincos", "line", "linen", "linenr", "lineto", "link_beat_force", "link_beat_get", "link_beat_request", "link_create", "link_enable", "link_is_enabled", "link_metro", "link_peers", "link_tempo_get", "link_tempo_set", "linlin", "linrand", "linseg", "linsegb", "linsegr", "liveconv", "locsend", "locsig", "log", "log10", "log2", "logbtwo", "logcurve", "loopseg", "loopsegp", "looptseg", "loopxseg", "lorenz", "loscil", "loscil3", "loscil3phs", "loscilphs", "loscilx", "lowpass2", "lowres", "lowresx", "lpf18", "lpform", "lpfreson", "lphasor", "lpinterp", "lposcil", "lposcil3", "lposcila", "lposcilsa", "lposcilsa2", "lpread", "lpreson", "lpshold", "lpsholdp", "lpslot", "lua_exec", "lua_iaopcall", "lua_iaopcall_off", "lua_ikopcall", "lua_ikopcall_off", "lua_iopcall", "lua_iopcall_off", "lua_opdef", "mac", "maca", "madsr", "mags", "mandel", "mandol", "maparray", "maparray_i", "marimba", "massign", "max", "max_k", "maxabs", "maxabsaccum", "maxaccum", "maxalloc", "maxarray", "mclock", "mdelay", "median", "mediank", "metro", "metro2", "mfb", "midglobal", "midiarp", "midic14", "midic21", "midic7", "midichannelaftertouch", "midichn", "midicontrolchange", "midictrl", "mididefault", "midifilestatus", "midiin", "midinoteoff", "midinoteoncps", "midinoteonkey", "midinoteonoct", "midinoteonpch", "midion", "midion2", "midiout", "midiout_i", "midipgm", "midipitchbend", "midipolyaftertouch", "midiprogramchange", "miditempo", "midremot", "min", "minabs", "minabsaccum", "minaccum", "minarray", "mincer", "mirror", "mode", "modmatrix", "monitor", "moog", "moogladder", "moogladder2", "moogvcf", "moogvcf2", "moscil", "mp3bitrate", "mp3in", "mp3len", "mp3nchnls", "mp3scal", "mp3sr", "mpulse", "mrtmsg", "mtof", "mton", "multitap", "mute", "mvchpf", "mvclpf1", "mvclpf2", "mvclpf3", "mvclpf4", "mxadsr", "nchnls_hw", "nestedap", "nlalp", "nlfilt", "nlfilt2", "noise", "noteoff", "noteon", "noteondur", "noteondur2", "notnum", "nreverb", "nrpn", "nsamp", "nstance", "nstrnum", "nstrstr", "ntof", "ntom", "ntrpol", "nxtpow2", "octave", "octcps", "octmidi", "octmidib", "octmidinn", "octpch", "olabuffer", "oscbnk", "oscil", "oscil1", "oscil1i", "oscil3", "oscili", "oscilikt", "osciliktp", "oscilikts", "osciln", "oscils", "oscilx", "out", "out32", "outc", "outch", "outh", "outiat", "outic", "outic14", "outipat", "outipb", "outipc", "outkat", "outkc", "outkc14", "outkpat", "outkpb", "outkpc", "outleta", "outletf", "outletk", "outletkid", "outletv", "outo", "outq", "outq1", "outq2", "outq3", "outq4", "outrg", "outs", "outs1", "outs2", "outvalue", "outx", "outz", "p", "p5gconnect", "p5gdata", "pan", "pan2", "pareq", "part2txt", "partials", "partikkel", "partikkelget", "partikkelset", "partikkelsync", "passign", "paulstretch", "pcauchy", "pchbend", "pchmidi", "pchmidib", "pchmidinn", "pchoct", "pchtom", "pconvolve", "pcount", "pdclip", "pdhalf", "pdhalfy", "peak", "pgmassign", "pgmchn", "phaser1", "phaser2", "phasor", "phasorbnk", "phs", "pindex", "pinker", "pinkish", "pitch", "pitchac", "pitchamdf", "planet", "platerev", "plltrack", "pluck", "poisson", "pol2rect", "polyaft", "polynomial", "port", "portk", "poscil", "poscil3", "pow", "powershape", "powoftwo", "pows", "prealloc", "prepiano", "print", "print_type", "printarray", "printf", "printf_i", "printk", "printk2", "printks", "printks2", "prints", "product", "pset", "ptable", "ptable3", "ptablei", "ptablew", "ptrack", "puts", "pvadd", "pvbufread", "pvcross", "pvinterp", "pvoc", "pvread", "pvs2array", "pvs2tab", "pvsadsyn", "pvsanal", "pvsarp", "pvsbandp", "pvsbandr", "pvsbin", "pvsblur", "pvsbuffer", "pvsbufread", "pvsbufread2", "pvscale", "pvscent", "pvsceps", "pvscross", "pvsdemix", "pvsdiskin", "pvsdisp", "pvsenvftw", "pvsfilter", "pvsfread", "pvsfreeze", "pvsfromarray", "pvsftr", "pvsftw", "pvsfwrite", "pvsgain", "pvshift", "pvsifd", "pvsin", "pvsinfo", "pvsinit", "pvslock", "pvsmaska", "pvsmix", "pvsmooth", "pvsmorph", "pvsosc", "pvsout", "pvspitch", "pvstanal", "pvstencil", "pvstrace", "pvsvoc", "pvswarp", "pvsynth", "pwd", "pyassign", "pyassigni", "pyassignt", "pycall", "pycall1", "pycall1i", "pycall1t", "pycall2", "pycall2i", "pycall2t", "pycall3", "pycall3i", "pycall3t", "pycall4", "pycall4i", "pycall4t", "pycall5", "pycall5i", "pycall5t", "pycall6", "pycall6i", "pycall6t", "pycall7", "pycall7i", "pycall7t", "pycall8", "pycall8i", "pycall8t", "pycalli", "pycalln", "pycallni", "pycallt", "pyeval", "pyevali", "pyevalt", "pyexec", "pyexeci", "pyexect", "pyinit", "pylassign", "pylassigni", "pylassignt", "pylcall", "pylcall1", "pylcall1i", "pylcall1t", "pylcall2", "pylcall2i", "pylcall2t", "pylcall3", "pylcall3i", "pylcall3t", "pylcall4", "pylcall4i", "pylcall4t", "pylcall5", "pylcall5i", "pylcall5t", "pylcall6", "pylcall6i", "pylcall6t", "pylcall7", "pylcall7i", "pylcall7t", "pylcall8", "pylcall8i", "pylcall8t", "pylcalli", "pylcalln", "pylcallni", "pylcallt", "pyleval", "pylevali", "pylevalt", "pylexec", "pylexeci", "pylexect", "pylrun", "pylruni", "pylrunt", "pyrun", "pyruni", "pyrunt", "qinf", "qnan", "r2c", "rand", "randc", "randh", "randi", "random", "randomh", "randomi", "rbjeq", "readclock", "readf", "readfi", "readk", "readk2", "readk3", "readk4", "readks", "readscore", "readscratch", "rect2pol", "release", "remoteport", "remove", "repluck", "reshapearray", "reson", "resonk", "resonr", "resonx", "resonxk", "resony", "resonz", "resyn", "reverb", "reverb2", "reverbsc", "rewindscore", "rezzy", "rfft", "rifft", "rms", "rnd", "rnd31", "round", "rspline", "rtclock", "s16b14", "s32b14", "samphold", "sandpaper", "sc_lag", "sc_lagud", "sc_phasor", "sc_trig", "scale", "scalearray", "scanhammer", "scans", "scantable", "scanu", "schedkwhen", "schedkwhennamed", "schedule", "schedulek", "schedwhen", "scoreline", "scoreline_i", "seed", "sekere", "select", "semitone", "sense", "sensekey", "seqtime", "seqtime2", "serialBegin", "serialEnd", "serialFlush", "serialPrint", "serialRead", "serialWrite", "serialWrite_i", "setcol", "setctrl", "setksmps", "setrow", "setscorepos", "sfilist", "sfinstr", "sfinstr3", "sfinstr3m", "sfinstrm", "sfload", "sflooper", "sfpassign", "sfplay", "sfplay3", "sfplay3m", "sfplaym", "sfplist", "sfpreset", "shaker", "shiftin", "shiftout", "signum", "sin", "sinh", "sininv", "sinsyn", "sleighbells", "slicearray", "slicearray_i", "slider16", "slider16f", "slider16table", "slider16tablef", "slider32", "slider32f", "slider32table", "slider32tablef", "slider64", "slider64f", "slider64table", "slider64tablef", "slider8", "slider8f", "slider8table", "slider8tablef", "sliderKawai", "sndloop", "sndwarp", "sndwarpst", "sockrecv", "sockrecvs", "socksend", "socksends", "sorta", "sortd", "soundin", "space", "spat3d", "spat3di", "spat3dt", "spdist", "splitrig", "sprintf", "sprintfk", "spsend", "sqrt", "squinewave", "statevar", "stix", "strcat", "strcatk", "strchar", "strchark", "strcmp", "strcmpk", "strcpy", "strcpyk", "strecv", "streson", "strfromurl", "strget", "strindex", "strindexk", "string2array", "strlen", "strlenk", "strlower", "strlowerk", "strrindex", "strrindexk", "strset", "strstrip", "strsub", "strsubk", "strtod", "strtodk", "strtol", "strtolk", "strupper", "strupperk", "stsend", "subinstr", "subinstrinit", "sum", "sumarray", "svfilter", "syncgrain", "syncloop", "syncphasor", "system", "system_i", "tab", "tab2array", "tab2pvs", "tab_i", "tabifd", "table", "table3", "table3kt", "tablecopy", "tablefilter", "tablefilteri", "tablegpw", "tablei", "tableicopy", "tableigpw", "tableikt", "tableimix", "tablekt", "tablemix", "tableng", "tablera", "tableseg", "tableshuffle", "tableshufflei", "tablew", "tablewa", "tablewkt", "tablexkt", "tablexseg", "tabmorph", "tabmorpha", "tabmorphak", "tabmorphi", "tabplay", "tabrec", "tabrowlin", "tabsum", "tabw", "tabw_i", "tambourine", "tan", "tanh", "taninv", "taninv2", "tbvcf", "tempest", "tempo", "temposcal", "tempoval", "timedseq", "timeinstk", "timeinsts", "timek", "times", "tival", "tlineto", "tone", "tonek", "tonex", "tradsyn", "trandom", "transeg", "transegb", "transegr", "trcross", "trfilter", "trhighest", "trigger", "trigseq", "trim", "trim_i", "trirand", "trlowest", "trmix", "trscale", "trshift", "trsplit", "turnoff", "turnoff2", "turnon", "tvconv", "unirand", "unwrap", "upsamp", "urandom", "urd", "vactrol", "vadd", "vadd_i", "vaddv", "vaddv_i", "vaget", "valpass", "vaset", "vbap", "vbapg", "vbapgmove", "vbaplsinit", "vbapmove", "vbapz", "vbapzmove", "vcella", "vco", "vco2", "vco2ft", "vco2ift", "vco2init", "vcomb", "vcopy", "vcopy_i", "vdel_k", "vdelay", "vdelay3", "vdelayk", "vdelayx", "vdelayxq", "vdelayxs", "vdelayxw", "vdelayxwq", "vdelayxws", "vdivv", "vdivv_i", "vecdelay", "veloc", "vexp", "vexp_i", "vexpseg", "vexpv", "vexpv_i", "vibes", "vibr", "vibrato", "vincr", "vlimit", "vlinseg", "vlowres", "vmap", "vmirror", "vmult", "vmult_i", "vmultv", "vmultv_i", "voice", "vosim", "vphaseseg", "vport", "vpow", "vpow_i", "vpowv", "vpowv_i", "vpvoc", "vrandh", "vrandi", "vsubv", "vsubv_i", "vtaba", "vtabi", "vtabk", "vtable1k", "vtablea", "vtablei", "vtablek", "vtablewa", "vtablewi", "vtablewk", "vtabwa", "vtabwi", "vtabwk", "vwrap", "waveset", "websocket", "weibull", "wgbow", "wgbowedbar", "wgbrass", "wgclar", "wgflute", "wgpluck", "wgpluck2", "wguide1", "wguide2", "wiiconnect", "wiidata", "wiirange", "wiisend", "window", "wrap", "writescratch", "wterrain", "xadsr", "xin", "xout", "xscanmap", "xscans", "xscansmap", "xscanu", "xtratim", "xyscale", "zacl", "zakinit", "zamod", "zar", "zarg", "zaw", "zawm", "zdf_1pole", "zdf_1pole_mode", "zdf_2pole", "zdf_2pole_mode", "zdf_ladder", "zfilter2", "zir", "ziw", "ziwm", "zkcl", "zkmod", "zkr", "zkw", "zkwm" ]; var deprecatedOpcodes = [ "array", "bformdec", "bformenc", "changed", "copy2ftab", "copy2ttab", "hrtfer", "ktableseg", "lentab", "maxtab", "mintab", "pop", "pop_f", "ptableiw", "push", "push_f", "scalet", "sndload", "soundout", "soundouts", "specaddm", "specdiff", "specdisp", "specfilt", "spechist", "specptrk", "specscal", "specsum", "spectrum", "stack", "sumtab", "tabgen", "tableiw", "tabmap", "tabmap_i", "tabslice", "tb0", "tb0_init", "tb1", "tb10", "tb10_init", "tb11", "tb11_init", "tb12", "tb12_init", "tb13", "tb13_init", "tb14", "tb14_init", "tb15", "tb15_init", "tb1_init", "tb2", "tb2_init", "tb3", "tb3_init", "tb4", "tb4_init", "tb5", "tb5_init", "tb6", "tb6_init", "tb7", "tb7_init", "tb8", "tb8_init", "tb9", "tb9_init", "vbap16", "vbap4", "vbap4move", "vbap8", "vbap8move", "xyin" ]; opcodes = lang.arrayToMap(opcodes); deprecatedOpcodes = lang.arrayToMap(deprecatedOpcodes); this.lineContinuations = [ { token: "constant.character.escape.line-continuation.csound", regex: /\\$/ }, this.pushRule({ token: "constant.character.escape.line-continuation.csound", regex: /\\/, next: "line continuation" }) ]; this.comments.push(this.lineContinuations); this.quotedStringContents.push( this.lineContinuations, { token: "invalid.illegal", regex: /[^"\\]*$/ } ); var start = this.$rules.start; start.splice(1, 0, { token: ["text.csound", "entity.name.label.csound", "entity.punctuation.label.csound", "text.csound"], regex: /^([ \t]*)(\w+)(:)([ \t]+|$)/ }); start.push( this.pushRule({ token: "keyword.function.csound", regex: /\binstr\b/, next: "instrument numbers and identifiers" }), this.pushRule({ token: "keyword.function.csound", regex: /\bopcode\b/, next: "after opcode keyword" }), { token: "keyword.other.csound", regex: /\bend(?:in|op)\b/ }, { token: "variable.language.csound", regex: /\b(?:0dbfs|A4|k(?:r|smps)|nchnls(?:_i)?|sr)\b/ }, this.numbers, { token: "keyword.operator.csound", regex: "\\+=|-=|\\*=|/=|<<|>>|<=|>=|==|!=|&&|\\|\\||[~¬]|[=!+\\-*/^%&|<>#?:]" }, this.pushRule({ token: "punctuation.definition.string.begin.csound", regex: /"/, next: "quoted string" }), this.pushRule({ token: "punctuation.definition.string.begin.csound", regex: /{{/, next: "braced string" }), { token: "keyword.control.csound", regex: /\b(?:do|else(?:if)?|end(?:if|until)|fi|i(?:f|then)|kthen|od|r(?:ir)?eturn|then|until|while)\b/ }, this.pushRule({ token: "keyword.control.csound", regex: /\b[ik]?goto\b/, next: "goto before label" }), this.pushRule({ token: "keyword.control.csound", regex: /\b(?:r(?:einit|igoto)|tigoto)\b/, next: "goto before label" }), this.pushRule({ token: "keyword.control.csound", regex: /\bc(?:g|in?|k|nk?)goto\b/, next: ["goto before label", "goto before argument"] }), this.pushRule({ token: "keyword.control.csound", regex: /\btimout\b/, next: ["goto before label", "goto before argument", "goto before argument"] }), this.pushRule({ token: "keyword.control.csound", regex: /\bloop_[gl][et]\b/, next: ["goto before label", "goto before argument", "goto before argument", "goto before argument"] }), this.pushRule({ token: "support.function.csound", regex: /\b(?:readscore|scoreline(?:_i)?)\b/, next: "Csound score opcode" }), this.pushRule({ token: "support.function.csound", regex: /\bpyl?run[it]?\b(?!$)/, next: "Python opcode" }), this.pushRule({ token: "support.function.csound", regex: /\blua_(?:exec|opdef)\b(?!$)/, next: "Lua opcode" }), { token: "support.variable.csound", regex: /\bp\d+\b/ }, { regex: /\b([A-Z_a-z]\w*)(?:(:)([A-Za-z]))?\b/, onMatch: function(value, currentState, stack, line) { var tokens = value.split(this.splitRegex); var name = tokens[1]; var type; if (opcodes.hasOwnProperty(name)) type = "support.function.csound"; else if (deprecatedOpcodes.hasOwnProperty(name)) type = "invalid.deprecated.csound"; if (type) { if (tokens[2]) { return [ { type: type, value: name }, { type: "punctuation.type-annotation.csound", value: tokens[2] }, { type: "type-annotation.storage.type.csound", value: tokens[3] } ]; } return type; } return "text.csound"; } } ); this.$rules["macro parameter value list"].splice(2, 0, { token: "punctuation.definition.string.begin.csound", regex: /{{/, next: "macro parameter value braced string" }); var scoreHighlightRules = new CsoundScoreHighlightRules("csound-score-"); this.addRules({ "macro parameter value braced string": [ { token: "constant.character.escape.csound", regex: /\\[#'()]/ }, { token: "invalid.illegal.csound.csound", regex: /[#'()]/ }, { token: "punctuation.definition.string.end.csound", regex: /}}/, next: "macro parameter value list" }, { defaultToken: "string.braced.csound" } ], "instrument numbers and identifiers": [ this.comments, { token: "entity.name.function.csound", regex: /\d+|[A-Z_a-z]\w*/ }, this.popRule({ token: "empty", regex: /$/ }) ], "after opcode keyword": [ this.comments, this.popRule({ token: "empty", regex: /$/ }), this.popRule({ token: "entity.name.function.opcode.csound", regex: /[A-Z_a-z]\w*/, next: "opcode type signatures" }) ], "opcode type signatures": [ this.comments, this.popRule({ token: "empty", regex: /$/ }), { token: "storage.type.csound", regex: /\b(?:0|[afijkKoOpPStV\[\]]+)/ } ], "quoted string": [ this.popRule({ token: "punctuation.definition.string.end.csound", regex: /"/ }), this.quotedStringContents, { defaultToken: "string.quoted.csound" } ], "braced string": [ this.popRule({ token: "punctuation.definition.string.end.csound", regex: /}}/ }), this.bracedStringContents, { defaultToken: "string.braced.csound" } ], "goto before argument": [ this.popRule({ token: "text.csound", regex: /,/ }), start ], "goto before label": [ { token: "text.csound", regex: /\s+/ }, this.comments, this.popRule({ token: "entity.name.label.csound", regex: /\w+/ }), this.popRule({ token: "empty", regex: /(?!\w)/ }) ], "Csound score opcode": [ this.comments, { token: "punctuation.definition.string.begin.csound", regex: /{{/, next: scoreHighlightRules.embeddedRulePrefix + "start" }, this.popRule({ token: "empty", regex: /$/ }) ], "Python opcode": [ this.comments, { token: "punctuation.definition.string.begin.csound", regex: /{{/, next: "python-start" }, this.popRule({ token: "empty", regex: /$/ }) ], "Lua opcode": [ this.comments, { token: "punctuation.definition.string.begin.csound", regex: /{{/, next: "lua-start" }, this.popRule({ token: "empty", regex: /$/ }) ], "line continuation": [ this.popRule({ token: "empty", regex: /$/ }), this.semicolonComments, { token: "invalid.illegal.csound", regex: /\S.*/ } ] }); var rules = [ this.popRule({ token: "punctuation.definition.string.end.csound", regex: /}}/ }) ]; this.embedRules(scoreHighlightRules.getRules(), scoreHighlightRules.embeddedRulePrefix, rules); this.embedRules(PythonHighlightRules, "python-", rules); this.embedRules(LuaHighlightRules, "lua-", rules); this.normalizeRules(); }; oop.inherits(CsoundOrchestraHighlightRules, CsoundPreprocessorHighlightRules); exports.CsoundOrchestraHighlightRules = CsoundOrchestraHighlightRules; }); ace.define("ace/mode/css_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/lib/lang", "ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var supportType = exports.supportType = "align-content|align-items|align-self|all|animation|animation-delay|animation-direction|animation-duration|animation-fill-mode|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|backface-visibility|background|background-attachment|background-blend-mode|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|border|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|bottom|box-shadow|box-sizing|caption-side|clear|clip|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|cursor|direction|display|empty-cells|filter|flex|flex-basis|flex-direction|flex-flow|flex-grow|flex-shrink|flex-wrap|float|font|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|hanging-punctuation|height|justify-content|left|letter-spacing|line-height|list-style|list-style-image|list-style-position|list-style-type|margin|margin-bottom|margin-left|margin-right|margin-top|max-height|max-width|max-zoom|min-height|min-width|min-zoom|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|order|outline|outline-color|outline-offset|outline-style|outline-width|overflow|overflow-x|overflow-y|padding|padding-bottom|padding-left|padding-right|padding-top|page-break-after|page-break-before|page-break-inside|perspective|perspective-origin|position|quotes|resize|right|tab-size|table-layout|text-align|text-align-last|text-decoration|text-decoration-color|text-decoration-line|text-decoration-style|text-indent|text-justify|text-overflow|text-shadow|text-transform|top|transform|transform-origin|transform-style|transition|transition-delay|transition-duration|transition-property|transition-timing-function|unicode-bidi|user-select|user-zoom|vertical-align|visibility|white-space|width|word-break|word-spacing|word-wrap|z-index"; var supportFunction = exports.supportFunction = "rgb|rgba|url|attr|counter|counters"; var supportConstant = exports.supportConstant = "absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero|zoom"; var supportConstantColor = exports.supportConstantColor = "aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkgrey|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkslategrey|darkturquoise|darkviolet|deeppink|deepskyblue|dimgray|dimgrey|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|grey|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgray|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightslategrey|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|rebeccapurple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|slategrey|snow|springgreen|steelblue|tan|teal|thistle|tomato|turquoise|violet|wheat|white|whitesmoke|yellow|yellowgreen"; var supportConstantFonts = exports.supportConstantFonts = "arial|century|comic|courier|cursive|fantasy|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace"; var numRe = exports.numRe = "\\-?(?:(?:[0-9]+(?:\\.[0-9]+)?)|(?:\\.[0-9]+))"; var pseudoElements = exports.pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = exports.pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var CssHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ "support.function": supportFunction, "support.constant": supportConstant, "support.type": supportType, "support.constant.color": supportConstantColor, "support.constant.fonts": supportConstantFonts }, "text", true); this.$rules = { "start": [{ include: ["strings", "url", "comments"] }, { token: "paren.lparen", regex: "\\{", next: "ruleset" }, { token: "paren.rparen", regex: "\\}" }, { token: "string", regex: "@(?!viewport)", next: "media" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "keyword", regex: "%" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant.numeric", regex: numRe }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "media": [{ include: ["strings", "url", "comments"] }, { token: "paren.lparen", regex: "\\{", next: "start" }, { token: "paren.rparen", regex: "\\}", next: "start" }, { token: "string", regex: ";", next: "start" }, { token: "keyword", regex: "(?:media|supports|document|charset|import|namespace|media|supports|document" + "|page|font|keyframes|viewport|counter-style|font-feature-values" + "|swash|ornaments|annotation|stylistic|styleset|character-variant)" }], "comments": [{ token: "comment", // multi line comment regex: "\\/\\*", push: [{ token: "comment", regex: "\\*\\/", next: "pop" }, { defaultToken: "comment" }] }], "ruleset": [{ regex: "-(webkit|ms|moz|o)-", token: "text" }, { token: "punctuation.operator", regex: "[:;]" }, { token: "paren.rparen", regex: "\\}", next: "start" }, { include: ["strings", "url", "comments"] }, { token: ["constant.numeric", "keyword"], regex: "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vmax|vmin|vm|vw|%)" }, { token: "constant.numeric", regex: numRe }, { token: "constant.numeric", // hex6 color regex: "#[a-f0-9]{6}" }, { token: "constant.numeric", // hex3 color regex: "#[a-f0-9]{3}" }, { token: ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex: pseudoElements }, { token: ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex: pseudoClasses }, { include: "url" }, { token: keywordMapper, regex: "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" }, { caseInsensitive: true }], url: [{ token: "support.function", regex: "(?:url(:?-prefix)?|domain|regexp)\\(", push: [{ token: "support.function", regex: "\\)", next: "pop" }, { defaultToken: "string" }] }], strings: [{ token: "string.start", regex: "'", push: [{ token: "string.end", regex: "'|$", next: "pop" }, { include: "escapes" }, { token: "constant.language.escape", regex: /\\$/, consumeLineEnd: true }, { defaultToken: "string" }] }, { token: "string.start", regex: '"', push: [{ token: "string.end", regex: '"|$', next: "pop" }, { include: "escapes" }, { token: "constant.language.escape", regex: /\\$/, consumeLineEnd: true }, { defaultToken: "string" }] }], escapes: [{ token: "constant.language.escape", regex: /\\([a-fA-F\d]{1,6}|[^a-fA-F\d])/ }] }; this.normalizeRules(); }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); ace.define("ace/mode/doc_comment_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start": [{ token: "comment.doc.tag", regex: "@[\\w\\d_]+" // TODO: fix email addresses }, DocCommentHighlightRules.getTagRule(), { defaultToken: "comment.doc", caseInsensitive: true }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getTagRule = function(start) { return { token: "comment.doc.tag.storage.type", regex: "\\b(?:TODO|FIXME|XXX|HACK)\\b" }; }; DocCommentHighlightRules.getStartRule = function(start) { return { token: "comment.doc", // doc comment regex: "\\/\\*(?=\\*)", next: start }; }; DocCommentHighlightRules.getEndRule = function(start) { return { token: "comment.doc", // closing comment regex: "\\*\\/", next: start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); ace.define("ace/mode/javascript_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/doc_comment_highlight_rules", "ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*"; var JavaScriptHighlightRules = function(options) { var keywordMapper = this.createKeywordMapper({ "variable.language": "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors "Namespace|QName|XML|XMLList|" + // E4X "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors "SyntaxError|TypeError|URIError|" + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions "isNaN|parseFloat|parseInt|" + "JSON|Math|" + // Other "this|arguments|prototype|window|document", // Pseudo "keyword": "const|yield|import|get|set|async|await|" + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|of|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + "__parent__|__count__|escape|unescape|with|__proto__|" + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", "storage.type": "const|let|var|function", "constant.language": "null|Infinity|NaN|undefined", "support.function": "alert", "constant.language.boolean": "true|false" }, "identifier"); var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "u{[0-9a-fA-F]{1,6}}|" + // es6 unicode "[0-2][0-7]{0,2}|" + // oct "3[0-7][0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; this.$rules = { "no_regex": [ DocCommentHighlightRules.getStartRule("doc-start"), comments("no_regex"), { token: "string", regex: "'(?=.)", next: "qstring" }, { token: "string", regex: '"(?=.)', next: "qqstring" }, { token: "constant.numeric", // hexadecimal, octal and binary regex: /0(?:[xX][0-9a-fA-F]+|[oO][0-7]+|[bB][01]+)\b/ }, { token: "constant.numeric", // decimal integers and floats regex: /(?:\d\d*(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+\b)?/ }, { token: [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator" ], regex: "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe + ")(\\s*)(=)", next: "function_arguments" }, { token: [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex: "(" + identifierRe + ")(\\.)(" + identifierRe + ")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token: [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex: "(" + identifierRe + ")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token: [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex: "(" + identifierRe + ")(\\.)(" + identifierRe + ")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", next: "function_arguments" }, { token: [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex: "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { token: [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex: "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token: [ "text", "text", "storage.type", "text", "paren.lparen" ], regex: "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token: "keyword", regex: "from(?=\\s*('|\"))" }, { token: "keyword", regex: "(?:" + kwBeforeRe + ")\\b", next: "start" }, { token: ["support.constant"], regex: /that\b/ }, { token: ["storage.type", "punctuation.operator", "support.function.firebug"], regex: /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ }, { token: keywordMapper, regex: identifierRe }, { token: "punctuation.operator", regex: /[.](?![.])/, next: "property" }, { token: "storage.type", regex: /=>/, next: "start" }, { token: "keyword.operator", regex: /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/, next: "start" }, { token: "punctuation.operator", regex: /[?:,;.]/, next: "start" }, { token: "paren.lparen", regex: /[\[({]/, next: "start" }, { token: "paren.rparen", regex: /[\])}]/ }, { token: "comment", regex: /^#!.*$/ } ], property: [{ token: "text", regex: "\\s+" }, { token: [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex: "(" + identifierRe + ")(\\.)(" + identifierRe + ")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()", next: "function_arguments" }, { token: "punctuation.operator", regex: /[.](?![.])/ }, { token: "support.function", regex: /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token: "support.function.dom", regex: /(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token: "support.constant", regex: /(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token: "identifier", regex: identifierRe }, { regex: "", token: "empty", next: "no_regex" } ], "start": [ DocCommentHighlightRules.getStartRule("doc-start"), comments("start"), { token: "string.regexp", regex: "\\/", next: "regex" }, { token: "text", regex: "\\s+|^$", next: "start" }, { token: "empty", regex: "", next: "no_regex" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp", regex: "/[sxngimy]*", next: "no_regex" }, { token: "invalid", regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ }, { token: "constant.language.escape", regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ }, { token: "constant.language.delimiter", regex: /\|/ }, { token: "constant.language.escape", regex: /\[\^?/, next: "regex_character_class" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp" } ], "regex_character_class": [ { token: "regexp.charclass.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "constant.language.escape", regex: "]", next: "regex" }, { token: "constant.language.escape", regex: "-" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp.charachterclass" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe }, { token: "punctuation.operator", regex: "[, ]+" }, { token: "punctuation.operator", regex: "$" }, { token: "empty", regex: "", next: "no_regex" } ], "qqstring": [ { token: "constant.language.escape", regex: escapedRe }, { token: "string", regex: "\\\\$", consumeLineEnd: true }, { token: "string", regex: '"|$', next: "no_regex" }, { defaultToken: "string" } ], "qstring": [ { token: "constant.language.escape", regex: escapedRe }, { token: "string", regex: "\\\\$", consumeLineEnd: true }, { token: "string", regex: "'|$", next: "no_regex" }, { defaultToken: "string" } ] }; if (!options || !options.noES6) { this.$rules.no_regex.unshift({ regex: "[{}]", onMatch: function(val, state, stack) { this.next = val == "{" ? this.nextState : ""; if (val == "{" && stack.length) { stack.unshift("start", state); } else if (val == "}" && stack.length) { stack.shift(); this.next = stack.shift(); if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1) return "paren.quasi.end"; } return val == "{" ? "paren.lparen" : "paren.rparen"; }, nextState: "start" }, { token: "string.quasi.start", regex: /`/, push: [{ token: "constant.language.escape", regex: escapedRe }, { token: "paren.quasi.start", regex: /\${/, push: "start" }, { token: "string.quasi.end", regex: /`/, next: "pop" }, { defaultToken: "string.quasi" }] }); if (!options || options.jsx != false) JSX.call(this); } this.embedRules(DocCommentHighlightRules, "doc-", [DocCommentHighlightRules.getEndRule("no_regex")]); this.normalizeRules(); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); function JSX() { var tagRegex = identifierRe.replace("\\d", "\\d\\-"); var jsxTag = { onMatch: function(val, state, stack) { var offset = val.charAt(1) == "/" ? 2 : 1; if (offset == 1) { if (state != this.nextState) stack.unshift(this.next, this.nextState, 0); else stack.unshift(this.next); stack[2]++; } else if (offset == 2) { if (state == this.nextState) { stack[1]--; if (!stack[1] || stack[1] < 0) { stack.shift(); stack.shift(); } } } return [{ type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml", value: val.slice(0, offset) }, { type: "meta.tag.tag-name.xml", value: val.substr(offset) }]; }, regex: "</?" + tagRegex + "", next: "jsxAttributes", nextState: "jsx" }; this.$rules.start.unshift(jsxTag); var jsxJsRule = { regex: "{", token: "paren.quasi.start", push: "start" }; this.$rules.jsx = [ jsxJsRule, jsxTag, { include: "reference" }, { defaultToken: "string" } ]; this.$rules.jsxAttributes = [{ token: "meta.tag.punctuation.tag-close.xml", regex: "/?>", onMatch: function(value, currentState, stack) { if (currentState == stack[0]) stack.shift(); if (value.length == 2) { if (stack[0] == this.nextState) stack[1]--; if (!stack[1] || stack[1] < 0) { stack.splice(0, 2); } } this.next = stack[0] || "start"; return [{ type: this.token, value: value }]; }, nextState: "jsx" }, jsxJsRule, comments("jsxAttributes"), { token: "entity.other.attribute-name.xml", regex: tagRegex }, { token: "keyword.operator.attribute-equals.xml", regex: "=" }, { token: "text.tag-whitespace.xml", regex: "\\s+" }, { token: "string.attribute-value.xml", regex: "'", stateName: "jsx_attr_q", push: [ { token: "string.attribute-value.xml", regex: "'", next: "pop" }, { include: "reference" }, { defaultToken: "string.attribute-value.xml" } ] }, { token: "string.attribute-value.xml", regex: '"', stateName: "jsx_attr_qq", push: [ { token: "string.attribute-value.xml", regex: '"', next: "pop" }, { include: "reference" }, { defaultToken: "string.attribute-value.xml" } ] }, jsxTag ]; this.$rules.reference = [{ token: "constant.language.escape.reference.xml", regex: "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }]; } function comments(next) { return [ { token: "comment", // multi line comment regex: /\/\*/, next: [ DocCommentHighlightRules.getTagRule(), { token: "comment", regex: "\\*\\/", next: next || "pop" }, { defaultToken: "comment", caseInsensitive: true } ] }, { token: "comment", regex: "\\/\\/", next: [ DocCommentHighlightRules.getTagRule(), { token: "comment", regex: "$|^", next: next || "pop" }, { defaultToken: "comment", caseInsensitive: true } ] } ]; } exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); ace.define("ace/mode/xml_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function(normalize) { var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*"; this.$rules = { start: [ { token: "string.cdata.xml", regex: "<\\!\\[CDATA\\[", next: "cdata" }, { token: ["punctuation.instruction.xml", "keyword.instruction.xml"], regex: "(<\\?)(" + tagRegex + ")", next: "processing_instruction" }, { token: "comment.start.xml", regex: "<\\!--", next: "comment" }, { token: ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], regex: "(<\\!)(DOCTYPE)(?=[\\s])", next: "doctype", caseInsensitive: true }, { include: "tag" }, { token: "text.end-tag-open.xml", regex: "</" }, { token: "text.tag-open.xml", regex: "<" }, { include: "reference" }, { defaultToken: "text.xml" } ], processing_instruction: [{ token: "entity.other.attribute-name.decl-attribute-name.xml", regex: tagRegex }, { token: "keyword.operator.decl-attribute-equals.xml", regex: "=" }, { include: "whitespace" }, { include: "string" }, { token: "punctuation.xml-decl.xml", regex: "\\?>", next: "start" }], doctype: [ { include: "whitespace" }, { include: "string" }, { token: "xml-pe.doctype.xml", regex: ">", next: "start" }, { token: "xml-pe.xml", regex: "[-_a-zA-Z0-9:]+" }, { token: "punctuation.int-subset", regex: "\\[", push: "int_subset" } ], int_subset: [{ token: "text.xml", regex: "\\s+" }, { token: "punctuation.int-subset.xml", regex: "]", next: "pop" }, { token: ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], regex: "(<\\!)(" + tagRegex + ")", push: [{ token: "text", regex: "\\s+" }, { token: "punctuation.markup-decl.xml", regex: ">", next: "pop" }, { include: "string" }] }], cdata: [ { token: "string.cdata.xml", regex: "\\]\\]>", next: "start" }, { token: "text.xml", regex: "\\s+" }, { token: "text.xml", regex: "(?:[^\\]]|\\](?!\\]>))+" } ], comment: [ { token: "comment.end.xml", regex: "-->", next: "start" }, { defaultToken: "comment.xml" } ], reference: [{ token: "constant.language.escape.reference.xml", regex: "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], attr_reference: [{ token: "constant.language.escape.reference.attribute-value.xml", regex: "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], tag: [{ token: ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], regex: "(?:(<)|(</))((?:" + tagRegex + ":)?" + tagRegex + ")", next: [ { include: "attributes" }, { token: "meta.tag.punctuation.tag-close.xml", regex: "/?>", next: "start" } ] }], tag_whitespace: [ { token: "text.tag-whitespace.xml", regex: "\\s+" } ], whitespace: [ { token: "text.whitespace.xml", regex: "\\s+" } ], string: [{ token: "string.xml", regex: "'", push: [ { token: "string.xml", regex: "'", next: "pop" }, { defaultToken: "string.xml" } ] }, { token: "string.xml", regex: '"', push: [ { token: "string.xml", regex: '"', next: "pop" }, { defaultToken: "string.xml" } ] }], attributes: [{ token: "entity.other.attribute-name.xml", regex: tagRegex }, { token: "keyword.operator.attribute-equals.xml", regex: "=" }, { include: "tag_whitespace" }, { include: "attribute_value" }], attribute_value: [{ token: "string.attribute-value.xml", regex: "'", push: [ { token: "string.attribute-value.xml", regex: "'", next: "pop" }, { include: "attr_reference" }, { defaultToken: "string.attribute-value.xml" } ] }, { token: "string.attribute-value.xml", regex: '"', push: [ { token: "string.attribute-value.xml", regex: '"', next: "pop" }, { include: "attr_reference" }, { defaultToken: "string.attribute-value.xml" } ] }] }; if (this.constructor === XmlHighlightRules) this.normalizeRules(); }; (function() { this.embedTagRules = function(HighlightRules, prefix, tag) { this.$rules.tag.unshift({ token: ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex: "(<)(" + tag + "(?=\\s|>|$))", next: [ { include: "attributes" }, { token: "meta.tag.punctuation.tag-close.xml", regex: "/?>", next: prefix + "start" } ] }); this.$rules[tag + "-end"] = [ { include: "attributes" }, { token: "meta.tag.punctuation.tag-close.xml", regex: "/?>", next: "start", onMatch: function(value, currentState, stack) { stack.splice(0); return this.token; } } ]; this.embedRules(HighlightRules, prefix, [{ token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex: "(</)(" + tag + "(?=\\s|>|$))", next: tag + "-end" }, { token: "string.cdata.xml", regex: "<\\!\\[CDATA\\[" }, { token: "string.cdata.xml", regex: "\\]\\]>" }]); }; }).call(TextHighlightRules.prototype); oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); ace.define("ace/mode/html_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/lib/lang", "ace/mode/css_highlight_rules", "ace/mode/javascript_highlight_rules", "ace/mode/xml_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var tagMap = lang.createMap({ a: 'anchor', button: 'form', form: 'form', img: 'image', input: 'form', label: 'form', option: 'form', script: 'script', select: 'form', textarea: 'form', style: 'style', table: 'table', tbody: 'table', td: 'table', tfoot: 'table', th: 'table', tr: 'table' }); var HtmlHighlightRules = function() { XmlHighlightRules.call(this); this.addRules({ attributes: [{ include: "tag_whitespace" }, { token: "entity.other.attribute-name.xml", regex: "[-_a-zA-Z0-9:.]+" }, { token: "keyword.operator.attribute-equals.xml", regex: "=", push: [{ include: "tag_whitespace" }, { token: "string.unquoted.attribute-value.html", regex: "[^<>='\"`\\s]+", next: "pop" }, { token: "empty", regex: "", next: "pop" }] }, { include: "attribute_value" }], tag: [{ token: function(start, tag) { var group = tagMap[tag]; return ["meta.tag.punctuation." + (start == "<" ? "" : "end-") + "tag-open.xml", "meta.tag" + (group ? "." + group : "") + ".tag-name.xml"]; }, regex: "(</?)([-_a-zA-Z0-9:.]+)", next: "tag_stuff" }], tag_stuff: [ { include: "attributes" }, { token: "meta.tag.punctuation.tag-close.xml", regex: "/?>", next: "start" } ] }); this.embedTagRules(CssHighlightRules, "css-", "style"); this.embedTagRules(new JavaScriptHighlightRules({ jsx: false }).getRules(), "js-", "script"); if (this.constructor === HtmlHighlightRules) this.normalizeRules(); }; oop.inherits(HtmlHighlightRules, XmlHighlightRules); exports.HtmlHighlightRules = HtmlHighlightRules; }); ace.define("ace/mode/csound_document_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/csound_orchestra_highlight_rules", "ace/mode/csound_score_highlight_rules", "ace/mode/html_highlight_rules", "ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var CsoundOrchestraHighlightRules = require("./csound_orchestra_highlight_rules").CsoundOrchestraHighlightRules; var CsoundScoreHighlightRules = require("./csound_score_highlight_rules").CsoundScoreHighlightRules; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var CsoundDocumentHighlightRules = function() { var orchestraHighlightRules = new CsoundOrchestraHighlightRules("csound-"); var scoreHighlightRules = new CsoundScoreHighlightRules("csound-score-"); this.$rules = { "start": [ { token: ["meta.tag.punctuation.tag-open.csound-document", "entity.name.tag.begin.csound-document", "meta.tag.punctuation.tag-close.csound-document"], regex: /(<)(CsoundSynthesi[sz]er)(>)/, next: "synthesizer" }, { defaultToken: "text.csound-document" } ], "synthesizer": [ { token: ["meta.tag.punctuation.end-tag-open.csound-document", "entity.name.tag.begin.csound-document", "meta.tag.punctuation.tag-close.csound-document"], regex: "(</)(CsoundSynthesi[sz]er)(>)", next: "start" }, { token: ["meta.tag.punctuation.tag-open.csound-document", "entity.name.tag.begin.csound-document", "meta.tag.punctuation.tag-close.csound-document"], regex: "(<)(CsInstruments)(>)", next: orchestraHighlightRules.embeddedRulePrefix + "start" }, { token: ["meta.tag.punctuation.tag-open.csound-document", "entity.name.tag.begin.csound-document", "meta.tag.punctuation.tag-close.csound-document"], regex: "(<)(CsScore)(>)", next: scoreHighlightRules.embeddedRulePrefix + "start" }, { token: ["meta.tag.punctuation.tag-open.csound-document", "entity.name.tag.begin.csound-document", "meta.tag.punctuation.tag-close.csound-document"], regex: "(<)([Hh][Tt][Mm][Ll])(>)", next: "html-start" } ] }; this.embedRules(orchestraHighlightRules.getRules(), orchestraHighlightRules.embeddedRulePrefix, [{ token: ["meta.tag.punctuation.end-tag-open.csound-document", "entity.name.tag.begin.csound-document", "meta.tag.punctuation.tag-close.csound-document"], regex: "(</)(CsInstruments)(>)", next: "synthesizer" }]); this.embedRules(scoreHighlightRules.getRules(), scoreHighlightRules.embeddedRulePrefix, [{ token: ["meta.tag.punctuation.end-tag-open.csound-document", "entity.name.tag.begin.csound-document", "meta.tag.punctuation.tag-close.csound-document"], regex: "(</)(CsScore)(>)", next: "synthesizer" }]); this.embedRules(HtmlHighlightRules, "html-", [{ token: ["meta.tag.punctuation.end-tag-open.csound-document", "entity.name.tag.begin.csound-document", "meta.tag.punctuation.tag-close.csound-document"], regex: "(</)([Hh][Tt][Mm][Ll])(>)", next: "synthesizer" }]); this.normalizeRules(); }; oop.inherits(CsoundDocumentHighlightRules, TextHighlightRules); exports.CsoundDocumentHighlightRules = CsoundDocumentHighlightRules; }); ace.define("ace/mode/csound_document", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text", "ace/mode/csound_document_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var CsoundDocumentHighlightRules = require("./csound_document_highlight_rules").CsoundDocumentHighlightRules; var Mode = function() { this.HighlightRules = CsoundDocumentHighlightRules; }; oop.inherits(Mode, TextMode); (function() { this.$id = "ace/mode/csound_document"; this.snippetFileId = "ace/snippets/csound_document"; }).call(Mode.prototype); exports.Mode = Mode; }); (function() { ace.require(["ace/mode/csound_document"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
var searchData= [ ['update_5fcycle_183',['UPDATE_CYCLE',['../_config_8h.html#accbf9ecab7aedeabb949d797657a04fb',1,'Config.h']]], ['updateinfo_184',['updateInfo',['../_balance_car_8ino.html#a62d08aadd1bcf30936f37705e85d85c7',1,'BalanceCar.ino']]] ];
const uc = window.uc; /** * 设置系统横竖屏 * @param {Number} orientaiton 屏幕模式; { 1: '竖屏', 2: '横屏' } * */ export default (orientaiton = 1) => { return new Promise((resolve, reject) => { uc.requestScreenOrientation({ orientaiton, // 1:竖屏模式 2:横屏模式,传感器模式的横屏,对应 android SCREEN_ORIENTATION_SENSOR_LANDSCAPE success: (data) => resolve(data), fail: (data) => reject(data), }); }) };
/* eslint-disable import/no-extraneous-dependencies */ import Vue from 'vue'; import { MglMap, MglGeojsonLayer, MglMarker, MglPopup } from 'vue-mapbox'; import Mapbox from 'mapbox-gl'; Vue.component('MglMap', MglMap); Vue.component('MglGeojsonLayer', MglGeojsonLayer); Vue.component('MglMarker', MglMarker); Vue.component('MglPopup', MglPopup); Vue.prototype.$mapbox = Mapbox;
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > FunctionDeclaration within a "do-while" Block in strict code is not allowed description: Declaring function within a "do-while" loop negative: SyntaxError bestPractice: "http://wiki.ecmascript.org/doku.php?id=conventions:no_non_standard_strict_decls" flags: [onlyStrict] ---*/ "use strict"; do { function __func(){}; } while(0);
function Grid(size, previousState) { this.size = size; this.cells = previousState ? this.fromState(previousState) : this.empty(); } // Build a grid of the specified size Grid.prototype.empty = function () { var cells = []; for (var x = 0; x < this.size; x++) { var row = (cells[x] = []); for (var y = 0; y < this.size; y++) { row.push(null); } } return cells; }; Grid.prototype.fromState = function (state) { var cells = []; for (var x = 0; x < this.size; x++) { var row = (cells[x] = []); for (var y = 0; y < this.size; y++) { var tile = state[x][y]; row.push(tile ? new Tile(tile.position, tile.value) : null); } } return cells; }; // Find the first available random position Grid.prototype.randomAvailableCell = function () { var cells = this.availableCells(); if (cells.length) { return cells[Math.floor(Math.random() * cells.length)]; } }; Grid.prototype.availableCells = function () { var cells = []; this.eachCell(function (x, y, tile) { if (!tile) { cells.push({ x: x, y: y }); } }); return cells; }; // Call callback for every cell Grid.prototype.eachCell = function (callback) { for (var x = 0; x < this.size; x++) { for (var y = 0; y < this.size; y++) { callback(x, y, this.cells[x][y]); } } }; // Check if there are any cells available Grid.prototype.cellsAvailable = function () { return !!this.availableCells().length; }; // Check if the specified cell is taken Grid.prototype.cellAvailable = function (cell) { return !this.cellOccupied(cell); }; Grid.prototype.cellOccupied = function (cell) { return !!this.cellContent(cell); }; Grid.prototype.cellContent = function (cell) { if (this.withinBounds(cell)) { return this.cells[cell.x][cell.y]; } else { return null; } }; // Inserts a tile at its position Grid.prototype.insertTile = function (tile) { this.cells[tile.x][tile.y] = tile; }; Grid.prototype.removeTile = function (tile) { this.cells[tile.x][tile.y] = null; }; Grid.prototype.withinBounds = function (position) { return ( position.x >= 0 && position.x < this.size && position.y >= 0 && position.y < this.size ); }; Grid.prototype.serialize = function () { var cellState = []; for (var x = 0; x < this.size; x++) { var row = (cellState[x] = []); for (var y = 0; y < this.size; y++) { row.push(this.cells[x][y] ? this.cells[x][y].serialize() : null); } } return { size: this.size, cells: cellState, }; };
import React, { Component } from 'react'; class ASList extends React.Component { constructor(props) { super(props); } //行头、表体Header table //排序、增删行 render() {} }
const appRoot = require('app-root-path'); const nock = require('nock'); const querystring = require('querystring'); const should = require('should'); const enketo_ = require(appRoot + '/lib/external/enketo'); const Problem = require(appRoot + '/lib/util/problem'); describe('external/enketo', () => { const enketoConfig = { url: 'http://enketoHost:1234/enketoPath', apiKey: 'enketoApiKey' }; const enketo = enketo_.init(enketoConfig); const enketoNock = nock('http://enketoHost:1234'); const openRosaUrl = 'http://openRosaHost:5678/somePath'; const xmlFormId = 'wellPumps'; describe('preview', () => { it('should send a properly constructed request to Enketo', () => { enketoNock .post('/enketoPath/api/v2/survey') .reply(201, function(uri, requestBody) { const base64Auth = Buffer.from('enketoApiKey:').toString('base64'); const expectedQueryString = querystring.stringify({ server_url: openRosaUrl, form_id: xmlFormId }); this.req.headers.authorization.should.equal(`Basic ${base64Auth}`); this.req.headers.cookie.should.equal('__Host-session=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'); requestBody.should.equal(expectedQueryString); return JSON.stringify({ url: 'http://enke.to/::stuvwxyz', code: 201 }); }); return enketo.create(openRosaUrl, xmlFormId, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'); }); it('should return the Enketo survey ID', () => { enketoNock .post('/enketoPath/api/v2/survey') .reply(201, { url: 'http://enke.to/::stuvwxyz', code: 201 }); return enketo.create(openRosaUrl, xmlFormId, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .then((result) => result.should.equal('::stuvwxyz')); }); it('should return an Enketo single-survey ID', () => { enketoNock .post('/enketoPath/api/v2/survey/single/once') .reply(201, { single_once_url: 'http://enke.to/single/::stuvwxyz', code: 201 }); return enketo.createOnceToken(openRosaUrl, xmlFormId, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .then((result) => result.should.equal('::stuvwxyz')); }); it('should throw a Problem if the Enketo response is not valid json', () => { enketoNock .post('/enketoPath/api/v2/survey') .reply(201, 'no json for you!'); return enketo.create(openRosaUrl, xmlFormId, null) .should.be.rejectedWith(Problem.internal.enketoUnexpectedResponse('invalid JSON')); }); it('should throw a Problem if the Enketo response url is unparseable', () => { enketoNock .post('/enketoPath/api/v2/survey') .reply(201, { url: 'http://enke.to/$$', code: 201 }); return enketo.create(openRosaUrl, xmlFormId, null) .should.be.rejectedWith(Problem.internal.enketoUnexpectedResponse('Could not parse token from enketo response url: http://enke.to/$$')); }); it('should throw a Problem if the Enketo response code is unexpected', () => { enketoNock .post('/enketoPath/api/v2/survey') .reply(204, {}); return enketo.create(openRosaUrl, xmlFormId, null) .should.be.rejectedWith(Problem.internal.enketoUnexpectedResponse('wrong status code')); }); }); describe('edit', () => { it('should send a properly formatted request to enketo', () => { let run = false; enketoNock .post('/enketoPath/api/v2/instance') .reply(201, function(uri, requestBody) { run = true; const base64Auth = Buffer.from('enketoApiKey:').toString('base64'); const expectedQueryString = querystring.stringify({ server_url: openRosaUrl, form_id: xmlFormId, instance: '<data/>', instance_id: 'instance', 'instance_attachments[fileone.txt]': 'http://openRosaHost:5678/v1/projects/1/forms/wellPumps/submissions/logical/versions/instance/attachments/fileone.txt', return_url: 'http://openRosaHost:5678/#/projects/1/forms/wellPumps/submissions/logical' }); this.req.headers.authorization.should.equal(`Basic ${base64Auth}`); this.req.headers.cookie.should.equal('__Host-session=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'); requestBody.should.equal(expectedQueryString); return JSON.stringify({ edit_url: 'http://enke.to/::editedit', code: 201 }); }); return enketo.edit( openRosaUrl, 'http://openRosaHost:5678', { projectId: 1, xmlFormId: 'wellPumps' }, 'logical', { xml: '<data/>', instanceId: 'instance' }, [{ blobId: 1, name: 'fileone.txt' }, { blobId: null, name: 'filetwo.jpg' }], 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' ).then(() => { run.should.equal(true); }); }); it('should return an enketo edit url with the domain replaced', () => { enketoNock .post('/enketoPath/api/v2/instance') .reply(201, { edit_url: 'http://enke.to/::editedit', code: 201 }); return enketo.edit( openRosaUrl, 'http://openRosaHost:5678', { projectId: 1, xmlFormId: 'wellPumps' }, 'logical', { xml: '<data/>', instanceId: 'instance' }, [], 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' ).then((url) => { url.should.equal('http://openrosahost:5678/::editedit'); }); }); it('should return an enketo edit url with the port and protocol replaced', () => { enketoNock .post('/enketoPath/api/v2/instance') .reply(201, { edit_url: 'http://enke.to/::editedit', code: 201 }); return enketo.edit( openRosaUrl, 'https://securehost', { projectId: 1, xmlFormId: 'wellPumps' }, 'logical', { xml: '<data/>', instanceId: 'instance' }, [], 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' ).then((url) => { url.should.equal('https://securehost/::editedit'); }); }); it('should return a custom message if Enketo says it is too soon', () => { enketoNock .post('/enketoPath/api/v2/instance') .reply(405, { code: 405, message: 'Not allowed. Record is already being edited' }); return enketo.edit( openRosaUrl, 'http://openRosaHost:5678', { projectId: 1, xmlFormId: 'wellPumps' }, 'logical', { xml: '<data/>', instanceId: 'instance' }, [], 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' ).should.be.rejected().then((err) => { err.problemCode.should.equal(409.13); /wait one minute/.test(err.message).should.equal(true); }); }); }); });
'use strict' const fs = require('fs'); const meta = require('./meta.json'); const schema = require('./schema.json'); const barometer = require('./barometer'); module.exports = function (app) { var plugin = { }; let persistTimer = null; plugin.id = 'signalk-barometer-trend'; plugin.name = 'Barometer Trend'; plugin.description = 'Calculate tendency, trend and weather predictions of barometric pressure'; var unsubscribes = []; plugin.start = function (options, restartPlugin) { app.debug('Plugin started'); barometer.setSampleRate(options.rate); app.debug('Sample rate set to ' + options.rate + " seconds"); barometer.setAltitudeCorrection(options.altitude); app.debug('Altitude offset set to ' + options.altitude + " metre(s)"); barometer.populate(read); let localSubscription = { context: '*', subscribe: barometer.SUBSCRIPTIONS }; app.subscriptionmanager.subscribe( localSubscription, unsubscribes, subscriptionError => { app.error('Error:' + subscriptionError); }, delta => sendDelta(barometer.onDeltasUpdate(delta)) ); persistTimer = setInterval(function () { barometer.persist(write); }, 1000 * 60 * 3); //every 3 minutes }; plugin.stop = function () { app.debug('Plugin stopping'); clearInterval(persistTimer) barometer.persist(write); unsubscribes.forEach(f => f()); unsubscribes = []; app.debug('Plugin stopped'); }; plugin.schema = schema[0]; function sendDelta(deltaValues) { if (deltaValues !== null && deltaValues.length > 0) { let signalk_delta = { context: "vessels." + app.selfId, updates: [ { timestamp: new Date().toISOString(), values: deltaValues, meta, } ] }; app.handleMessage(plugin.id, signalk_delta); } } function offlineFilePath() { return app.getDataDirPath() + "/offline.json"; } function write(json) { let content = JSON.stringify(json, null, 2); fs.writeFile(offlineFilePath(), content, 'utf8', (err) => { if (err) { app.debug(err.stack); app.error(err); } else { app.debug("Wrote plugin data to file " + offlineFilePath()); } }); } function read() { try { const content = fs.readFileSync(offlineFilePath(), 'utf-8'); try { return barometer.JSONParser(content); } catch (err) { app.error("Could not parse JSON : " + content); app.error(err.stack); return []; } } catch (e) { if (e.code && e.code === 'ENOENT') { return []; } } return []; } return plugin; };
import '../site_configs/hof_cug-63710/js/63710'; import '../site_configs/hof_cug-63710/styles/63710.scss';
/** * assert * * assert.throw(block, error, message) * assert.ifError(vaule) */ const assert = require("assert"); const fs = require("fs"); function readConfigFile(cb){ fs.readFile("config.cfg", (err, data)=>{ if(err && err.code == "ENOENT"){ // cb(err, { "database": "psql://localhost/test"}); cb(null, { "database": "psql://localhost/test"}); }else if(err){ cb(err); }else{ cb(null, data); } }); } readConfigFile((err, data)=>{ assert.ifError(err); });
import request from '@/utils/request' const defaultSettings = require('@/settings.js') export function login(data) { return request({ url: '/keyauth/v1/oauth2/tokens/', method: 'post', auth: { username: defaultSettings.client_id, password: defaultSettings.client_secret }, data }) } export function refreshAccessToken(data) { return request({ url: '/keyauth/v1/oauth2/tokens/', method: 'post', auth: { username: defaultSettings.client_id, password: defaultSettings.client_secret }, data }) } export function logout() { return request({ url: '/keyauth/v1/oauth2/tokens/', method: 'delete', auth: { username: defaultSettings.client_id, password: defaultSettings.client_secret } }) } export function sendVerifyCodeByPass(data) { return request({ url: '/keyauth/v1/verify_code/pass/', method: 'post', auth: { username: defaultSettings.client_id, password: defaultSettings.client_secret }, data }) } export function queryToken(query) { return request({ url: '/keyauth/v1/self/tokens/', method: 'get', params: query }) } export function deleteToken(data) { return request({ url: '/keyauth/v1/self/tokens/', method: 'delete', auth: { username: defaultSettings.client_id, password: defaultSettings.client_secret }, data }) }
import filter from 'lodash/filter'; import flatten from 'lodash/flatten'; import get from 'lodash/get'; import map from 'lodash/map'; import set from 'lodash/set'; import some from 'lodash/some'; import startsWith from 'lodash/startsWith'; angular.module('managerApp') .controller('TelecomTelephonyLineCallsSimultaneousLinesCtrl', function TelecomTelephonyLineCallsSimultaneousLinesCtrl( $filter, $q, $stateParams, $translate, currentLine, OvhApiOrderTelephony, OvhApiTelephony, OvhApiTelephonyService, tucTelephonyBulk, TucToast, ) { const self = this; const apiResources = { getSimultaneousLines: OvhApiOrderTelephony.v6().getSimultaneousLines, orderSimultaneousLines: OvhApiOrderTelephony.v6().orderSimultaneousLines, }; let unitPrices = null; self.bulkOrders = []; self.isTrunk = false; self.orderUrl = null; self.showBulkOrderSummary = false; self.needSave = function needSave() { return self.options.simultaneousLines !== self.saved.simultaneousLines; }; self.doOrder = function doOrder() { self.loading.doOrder = true; return apiResources.orderSimultaneousLines({ serviceName: $stateParams.serviceName, }, { quantity: self.options.simultaneousLines, }).$promise.then((order) => { self.orderUrl = order.url; self.prices = order.prices; return order; }).catch((err) => $translate('telephony_line_actions_line_calls_simultaneous_line_order_error').then((message) => { TucToast.error(message); return $q.reject(err); })).finally(() => { self.loading.order = false; self.loading.doOrder = false; }); }; function getOfferTasks() { return OvhApiTelephonyService.OfferTask().v6() .query({ billingAccount: $stateParams.billingAccount, serviceName: $stateParams.serviceName, action: 'removeSimltaneousLines', }).$promise .then((offerTasks) => $q.all(map( offerTasks, (taskId) => OvhApiTelephonyService.OfferTask().v6() .get({ billingAccount: $stateParams.billingAccount, serviceName: $stateParams.serviceName, taskId, }).$promise .then((taskDetail) => { set(taskDetail, 'formatedDate', $filter('date')(taskDetail.executionDate, 'fullDate')); return taskDetail; }).catch((err) => $translate('telephony_line_actions_line_calls_simultaneous_line_offer_task_error').then((message) => { TucToast.error(message); return $q.reject(err); })), ))) .then((offerTasksDetails) => { self.offerTasks = offerTasksDetails; return self.offerTasks; }); } self.doRemoveSimultaneousLines = function doRemoveSimultaneousLines() { self.loading.save = true; return OvhApiTelephony.Line().v6().removeSimultaneousLine({ billingAccount: $stateParams.billingAccount, serviceName: $stateParams.serviceName, }, { quantityRemove: self.saved.simultaneousLines - self.options.simultaneousLines, }).$promise.then(() => { self.loading.save = false; self.showDoRemoveButtons = false; self.saved.simultaneousLines = self.options.simultaneousLines; return getOfferTasks(); }).catch((err) => $translate('telephony_line_actions_line_calls_simultaneous_line_write_error').then((message) => { TucToast.error([message, get(err, 'data.message')].join(' ')); self.cancelRemove(); self.options.minimumAvailableSimultaneousLines = self.saved.simultaneousLines; return $q.reject(err); })).finally(() => { self.loading.save = false; }); }; self.cancelRemove = function cancelRemove() { self.showDoRemoveButtons = false; self.options.simultaneousLines = self.saved.simultaneousLines; }; self.save = function save() { self.prices = null; self.contractsAccepted = false; self.showDoRemoveButtons = false; if (self.needSave()) { if (self.saved.simultaneousLines < self.options.simultaneousLines) { self.showDoRemoveButtons = false; self.recalculatePrices(); } if (self.saved.simultaneousLines > self.options.simultaneousLines && self.options.simultaneousLines) { self.showDoRemoveButtons = true; } } else { self.showDoRemoveButtons = false; } }; self.recalculatePrices = function recalculatePrices() { const quantity = self.options.simultaneousLines - self.saved.simultaneousLines; self.prices = { tax: { text: $filter('currency')(unitPrices.tax.value * quantity) }, withTax: { text: $filter('currency')(unitPrices.withTax.value * quantity) }, withoutTax: { text: $filter('currency')(unitPrices.withoutTax.value * quantity) }, }; }; function getUnitPrices() { return apiResources.getSimultaneousLines({ serviceName: $stateParams.serviceName, quantity: currentLine.simultaneousLinesDetails.current + 1, }).$promise.then((order) => { self.contracts = order.contracts; unitPrices = order.prices; return order; }).catch((err) => $translate('telephony_line_actions_line_calls_simultaneous_line_write_error').then((message) => { TucToast.error([message, get(err, 'data.message')].join(' ')); return $q.reject(err); })); } function init() { if (!currentLine) { TucToast.error($translate.instant('telephony_line_actions_line_calls_simultaneous_line_load_error')); return $q.when(null); } self.loading = { init: true, order: false, orderUrl: null, doOrder: false, save: false, }; self.contractsAccepted = false; self.contracts = null; self.hundredLines = false; self.prices = null; self.saved = { }; self.offerTasks = []; self.options = { simultaneousLines: null, maximumAvailableSimultaneousLines: currentLine.simultaneousLinesDetails.maximum, minimumAvailableSimultaneousLines: 1, }; self.showBulkOrderSummary = false; self.options.simultaneousLines = currentLine.simultaneousLines; self.hundredLines = currentLine.simultaneousLines >= 100; self.isTrunk = some(currentLine.offers, (offer) => startsWith(offer, 'voip.main.offer.trunk')); if (self.isTrunk) { apiResources.getSimultaneousLines = OvhApiOrderTelephony.v6().getSimultaneousTrunkLines; apiResources.orderSimultaneousLines = OvhApiOrderTelephony.v6().orderSimultaneousTrunkLines; } self.options.details = currentLine.simultaneousLinesDetails; self.saved = angular.copy(self.options); return $q.all([ getOfferTasks(), getUnitPrices(), ]).finally(() => { self.loading.init = false; }).catch(() => $translate('telephony_line_actions_line_calls_simultaneous_line_load_error').then((message) => TucToast.error(message))); } init(); /* =========================== = BULK = ============================ */ self.bulkDatas = { billingAccount: $stateParams.billingAccount, serviceName: $stateParams.serviceName, infos: { name: 'simultaneousCalls', actions: [{ name: 'removeSimultaneousLines', route: '/telephony/{billingAccount}/line/{serviceName}/removeSimultaneousLines', method: 'POST', params: null, }, { name: 'updateSimultaneousChannels', route: '/order/telephony/lines/{serviceName}/updateSimultaneousChannels', method: 'POST', params: null, }], }, }; self.filterServices = function filterServices(services) { return filter(services, (service) => ['sip', 'mgcp'].indexOf(service.featureType) > -1 && service.hasValidPublicOffer() && !service.isSipTrunkRates()); }; self.getBulkParams = function getBulkParams() { return self.options.simultaneousLines; }; self.onBulkSuccess = function onBulkSuccess(bulkResult) { // display message of success or error tucTelephonyBulk.getTucToastInfos(bulkResult, { fullSuccess: $translate.instant('telephony_line_actions_line_calls_simultaneous_bulk_all_success'), partialSuccess: $translate.instant('telephony_line_actions_line_calls_simultaneous_bulk_some_success', { count: bulkResult.success.length, }), error: $translate.instant('telephony_line_actions_line_calls_simultaneous_bulk_error'), }).forEach((toastInfo) => { TucToast[toastInfo.type](toastInfo.message, { hideAfter: null, }); }); if (bulkResult.success.length > 0) { self.buildOrderSummary(bulkResult.success); } }; self.onBulkError = function onBulkError(error) { TucToast.error([$translate.instant('telephony_line_actions_line_calls_simultaneous_bulk_on_error'), get(error, 'msg.data')].join(' ')); }; self.buildOrderSummary = function buildOrderSummary(orders) { self.bulkOrders = map( filter( flatten( map( orders, 'values', ), ), { action: 'updateSimultaneousChannels' }, ), 'value', ); self.showBulkOrderSummary = self.bulkOrders.length > 0; }; /* ----- End of BULK ------ */ });
( function ( mw, $ ) { QUnit.module( 'mmv.bootstrap', QUnit.newMwEnvironment( { setup: function () { mw.config.set( 'wgMediaViewer', true ); mw.config.set( 'wgMediaViewerOnClick', true ); this.sandbox.stub( mw.user, 'isAnon' ).returns( false ); } } ) ); function createGallery( imageSrc, caption ) { var $div = $( '<div>' ).addClass( 'gallery' ).appendTo( '#qunit-fixture' ), $galleryBox = $( '<div>' ).addClass( 'gallerybox' ).appendTo( $div ), $thumbwrap = $( '<div>' ).addClass( 'thumb' ).appendTo( $galleryBox ), $link = $( '<a>' ).addClass( 'image' ).appendTo( $thumbwrap ); $( '<img>' ).attr( 'src', ( imageSrc || 'thumb.jpg' ) ).appendTo( $link ); $( '<div>' ).addClass( 'gallerytext' ).text( caption || 'Foobar' ).appendTo( $galleryBox ); return $div; } function createThumb( imageSrc, caption, alt ) { var $div = $( '<div>' ).addClass( 'thumb' ).appendTo( '#qunit-fixture' ), $link = $( '<a>' ).addClass( 'image' ).appendTo( $div ); $( '<div>' ).addClass( 'thumbcaption' ).appendTo( $div ).text( caption ); $( '<img>' ).attr( 'src', ( imageSrc || 'thumb.jpg' ) ).attr( 'alt', alt ).appendTo( $link ); return $div; } function createNormal( imageSrc, caption ) { var $link = $( '<a>' ).prop( 'title', caption ).addClass( 'image' ).appendTo( '#qunit-fixture' ); $( '<img>' ).prop( 'src', ( imageSrc || 'thumb.jpg' ) ).appendTo( $link ); return $link; } function createMultipleImage( images ) { var i, $div, $thumbimage, $link, $contain = $( '<div>' ).addClass( 'thumb' ), $thumbinner = $( '<div>' ).addClass( 'thumbinner' ).appendTo( $contain ); for ( i = 0; i < images.length; ++i ) { $div = $( '<div>' ).appendTo( $thumbinner ); $thumbimage = $( '<div>' ).addClass( 'thumbimage' ).appendTo( $div ); $link = $( '<a>' ).addClass( 'image' ).appendTo( $thumbimage ); $( '<img>' ).prop( 'src', images[ i ][ 0 ] ).appendTo( $link ); $( '<div>' ).addClass( 'thumbcaption' ).text( images[ i ][ 1 ] ).appendTo( $div ); } return $contain; } function createBootstrap( viewer ) { var bootstrap = new mw.mmv.MultimediaViewerBootstrap(); bootstrap.processThumbs( $( '#qunit-fixture' ) ); // MultimediaViewerBootstrap.ensureEventHandlersAreSetUp() is a weird workaround for gadget bugs. // MediaViewer should work without it, and so should the tests. bootstrap.ensureEventHandlersAreSetUp = $.noop; bootstrap.getViewer = function () { return viewer || { initWithThumbs: $.noop, hash: $.noop }; }; return bootstrap; } function hashTest( prefix, bootstrap, assert ) { var hash = prefix + '/foo', callCount = 0; bootstrap.loadViewer = function () { callCount++; return $.Deferred().reject(); }; // Hijack loadViewer, which will return a promise that we'll have to // wait for if we want to see these tests through mw.mmv.testHelpers.asyncMethod( bootstrap, 'loadViewer' ); bootstrap.setupEventHandlers(); // invalid hash, should not trigger MMV load window.location.hash = 'Foo'; // actual hash we want to test for, should trigger MMV load // use setTimeout to add new hash change to end of the call stack, // ensuring that event handlers for our previous change can execute // without us interfering with another immediate change setTimeout( function () { window.location.hash = hash; } ); return mw.mmv.testHelpers.waitForAsync().then( function () { assert.ok( callCount === 1, 'Viewer should be loaded once' ); bootstrap.cleanupEventHandlers(); window.location.hash = ''; } ); } QUnit.test( 'Promise does not hang on ResourceLoader errors', function ( assert ) { var bootstrap, errorMessage = 'loading failed', done = assert.async(); this.sandbox.stub( mw.loader, 'using' ) .callsArgWith( 2, new Error( errorMessage, [ 'mmv' ] ) ) .withArgs( 'mediawiki.notification' ).returns( $.Deferred().reject() ); // needed for mw.notify bootstrap = createBootstrap(); this.sandbox.stub( bootstrap, 'setupOverlay' ); this.sandbox.stub( bootstrap, 'cleanupOverlay' ); bootstrap.loadViewer( true ).fail( function ( message ) { assert.ok( bootstrap.setupOverlay.called, 'Overlay was set up' ); assert.ok( bootstrap.cleanupOverlay.called, 'Overlay was cleaned up' ); assert.strictEqual( message, errorMessage, 'promise is rejected with the error message when loading fails' ); done(); } ); } ); QUnit.test( 'Clicks are not captured once the loading fails', function ( assert ) { var event, returnValue, bootstrap = new mw.mmv.MultimediaViewerBootstrap(), clock = this.sandbox.useFakeTimers(); this.sandbox.stub( mw.loader, 'using' ) .callsArgWith( 2, new Error( 'loading failed', [ 'mmv' ] ) ) .withArgs( 'mediawiki.notification' ).returns( $.Deferred().reject() ); // needed for mw.notify bootstrap.ensureEventHandlersAreSetUp = $.noop; // trigger first click, which will cause MMV to be loaded (which we've // set up to fail) event = new $.Event( 'click', { button: 0, which: 1 } ); returnValue = bootstrap.click( {}, event, 'foo' ); clock.tick( 10 ); assert.ok( event.isDefaultPrevented(), 'First click is caught' ); assert.strictEqual( returnValue, false, 'First click is caught' ); // wait until MMW is loaded (or failed to load, in this case) before we // trigger another click - which should then not be caught event = new $.Event( 'click', { button: 0, which: 1 } ); returnValue = bootstrap.click( {}, event, 'foo' ); clock.tick( 10 ); assert.ok( !event.isDefaultPrevented(), 'Click after loading failure is not caught' ); assert.notStrictEqual( returnValue, false, 'Click after loading failure is not caught' ); clock.restore(); } ); /* FIXME: Tests suspended as they do not pass in QUnit 2.x+ – T192932 QUnit.test( 'Check viewer invoked when clicking on valid image links', function ( assert ) { // TODO: Is <div class="gallery"><span class="image"><img/></span></div> valid ??? var div, link, link2, link3, link4, link5, bootstrap, viewer = { initWithThumbs: $.noop, loadImageByTitle: this.sandbox.stub() }, clock = this.sandbox.useFakeTimers(); // Create gallery with valid link image div = createGallery(); link = div.find( 'a.image' ); // Valid isolated thumbnail link2 = $( '<a>' ).addClass( 'image' ).appendTo( '#qunit-fixture' ); $( '<img>' ).attr( 'src', 'thumb2.jpg' ).appendTo( link2 ); // Non-valid fragment link3 = $( '<a>' ).addClass( 'noImage' ).appendTo( div ); $( '<img>' ).attr( 'src', 'thumb3.jpg' ).appendTo( link3 ); mw.config.set( 'wgTitle', 'Thumb4.jpg' ); mw.config.set( 'wgNamespaceNumber', 6 ); $( '<div>' ).addClass( 'fullMedia' ).appendTo( div ); $( '<img>' ).attr( 'src', 'thumb4.jpg' ).appendTo( $( '<a>' ) .appendTo( $( '<div>' ) .attr( 'id', 'file' ) .appendTo( '#qunit-fixture' ) ) ); // Create a new bootstrap object to trigger the DOM scan, etc. bootstrap = createBootstrap( viewer ); this.sandbox.stub( bootstrap, 'setupOverlay' ); link4 = $( '.fullMedia .mw-mmv-view-expanded' ); assert.ok( link4.length, 'Link for viewing expanded file was set up.' ); link5 = $( '.fullMedia .mw-mmv-view-config' ); assert.ok( link5.length, 'Link for opening enable/disable configuration was set up.' ); // Click on valid link link.trigger( { type: 'click', which: 1 } ); clock.tick( 10 ); // FIXME: Actual bootstrap.setupOverlay.callCount: 2 assert.equal( bootstrap.setupOverlay.callCount, 1, 'setupOverlay called (1st click)' ); assert.equal( viewer.loadImageByTitle.callCount, 1, 'loadImageByTitle called (1st click)' ); this.sandbox.reset(); // Click on valid link link2.trigger( { type: 'click', which: 1 } ); clock.tick( 10 ); assert.equal( bootstrap.setupOverlay.callCount, 1, 'setupOverlay called (2nd click)' ); assert.equal( viewer.loadImageByTitle.callCount, 1, 'loadImageByTitle called (2nd click)' ); this.sandbox.reset(); // Click on valid link link4.trigger( { type: 'click', which: 1 } ); clock.tick( 10 ); assert.equal( bootstrap.setupOverlay.callCount, 1, 'setupOverlay called (3rd click)' ); assert.equal( viewer.loadImageByTitle.callCount, 1, 'loadImageByTitle called (3rd click)' ); this.sandbox.reset(); // Click on valid link even when preference says not to mw.config.set( 'wgMediaViewerOnClick', false ); link4.trigger( { type: 'click', which: 1 } ); clock.tick( 10 ); mw.config.set( 'wgMediaViewerOnClick', true ); assert.equal( bootstrap.setupOverlay.callCount, 1, 'setupOverlay called on-click with pref off' ); assert.equal( viewer.loadImageByTitle.callCount, 1, 'loadImageByTitle called on-click with pref off' ); this.sandbox.reset(); // @todo comment that above clicks should result in call, below clicks should not // Click on non-valid link link3.trigger( { type: 'click', which: 1 } ); clock.tick( 10 ); assert.equal( bootstrap.setupOverlay.callCount, 0, 'setupOverlay not called on non-valid link click' ); assert.equal( viewer.loadImageByTitle.callCount, 0, 'loadImageByTitle not called on non-valid link click' ); this.sandbox.reset(); // Click on valid links with preference off mw.config.set( 'wgMediaViewerOnClick', false ); link.trigger( { type: 'click', which: 1 } ); link2.trigger( { type: 'click', which: 1 } ); clock.tick( 10 ); assert.equal( bootstrap.setupOverlay.callCount, 0, 'setupOverlay not called on non-valid link click with pref off' ); assert.equal( viewer.loadImageByTitle.callCount, 0, 'loadImageByTitle not called on non-valid link click with pref off' ); clock.restore(); } ); */ QUnit.test( 'Skip images with invalid extensions', function ( assert ) { var div, link, viewer = { initWithThumbs: $.noop, loadImageByTitle: this.sandbox.stub() }, clock = this.sandbox.useFakeTimers(); // Create gallery with image that has invalid name extension div = createGallery( 'thumb.badext' ); link = div.find( 'a.image' ); // Create a new bootstrap object to trigger the DOM scan, etc. createBootstrap( viewer ); // Click on valid link with wrong image extension link.trigger( { type: 'click', which: 1 } ); clock.tick( 10 ); assert.ok( !viewer.loadImageByTitle.called, 'Image should not be loaded' ); clock.restore(); } ); /* FIXME: Tests suspended as they do not pass in QUnit 2.x+ – T192932 QUnit.test( 'Accept only left clicks without modifier keys, skip the rest', function ( assert ) { var $div, $link, bootstrap, viewer = { initWithThumbs: $.noop, loadImageByTitle: this.sandbox.stub() }, clock = this.sandbox.useFakeTimers(); // Create gallery with image that has valid name extension $div = createGallery(); // Create a new bootstrap object to trigger the DOM scan, etc. bootstrap = createBootstrap( viewer ); this.sandbox.stub( bootstrap, 'setupOverlay' ); $link = $div.find( 'a.image' ); // Handle valid left click, it should try to load the image $link.trigger( { type: 'click', which: 1 } ); clock.tick( 10 ); // FIXME: Actual bootstrap.setupOverlay.callCount: 2 assert.equal( bootstrap.setupOverlay.callCount, 1, 'Left-click: Set up overlay' ); assert.equal( viewer.loadImageByTitle.callCount, 1, 'Left-click: Load image' ); this.sandbox.reset(); // Skip Ctrl-left-click, no image is loaded $link.trigger( { type: 'click', which: 1, ctrlKey: true } ); clock.tick( 10 ); assert.equal( bootstrap.setupOverlay.callCount, 0, 'Ctrl-left-click: No overlay' ); assert.equal( viewer.loadImageByTitle.callCount, 0, 'Ctrl-left-click: No image load' ); this.sandbox.reset(); // Skip invalid right click, no image is loaded $link.trigger( { type: 'click', which: 2 } ); clock.tick( 10 ); assert.equal( bootstrap.setupOverlay.callCount, 0, 'Right-click: No overlay' ); assert.equal( viewer.loadImageByTitle.callCount, 0, 'Right-click: Image was not loaded' ); clock.restore(); } ); */ QUnit.test( 'Ensure that the correct title is loaded when clicking', function ( assert ) { var bootstrap, viewer = { initWithThumbs: $.noop, loadImageByTitle: this.sandbox.stub() }, $div = createGallery( 'foo.jpg' ), $link = $div.find( 'a.image' ), clock = this.sandbox.useFakeTimers(); // Create a new bootstrap object to trigger the DOM scan, etc. bootstrap = createBootstrap( viewer ); this.sandbox.stub( bootstrap, 'setupOverlay' ); $link.trigger( { type: 'click', which: 1 } ); clock.tick( 10 ); assert.ok( bootstrap.setupOverlay.called, 'Overlay was set up' ); assert.strictEqual( viewer.loadImageByTitle.firstCall.args[ 0 ].getPrefixedDb(), 'File:Foo.jpg', 'Titles are identical' ); clock.restore(); } ); /* FIXME: Tests suspended as they do not pass in QUnit 2.x+ – T192932 QUnit.test( 'Validate new LightboxImage object has sane constructor parameters', function ( assert ) { var bootstrap, $div, $link, viewer = mw.mmv.testHelpers.getMultimediaViewer(), fname = 'valid', imgSrc = '/' + fname + '.jpg/300px-' + fname + '.jpg', imgRegex = new RegExp( imgSrc + '$' ), clock = this.sandbox.useFakeTimers(); $div = createThumb( imgSrc, 'Blah blah', 'meow' ); $link = $div.find( 'a.image' ); // Create a new bootstrap object to trigger the DOM scan, etc. bootstrap = createBootstrap( viewer ); this.sandbox.stub( bootstrap, 'setupOverlay' ); this.sandbox.stub( viewer, 'createNewImage' ); viewer.loadImage = $.noop; viewer.createNewImage = function ( fileLink, filePageLink, fileTitle, index, thumb, caption, alt ) { var html = thumb.outerHTML; // FIXME: fileLink doesn't match imgRegex (null) assert.ok( fileLink.match( imgRegex ), 'Thumbnail URL used in creating new image object' ); assert.strictEqual( filePageLink, '', 'File page link is sane when creating new image object' ); assert.strictEqual( fileTitle.title, fname, 'Filename is correct when passed into new image constructor' ); assert.strictEqual( index, 0, 'The only image we created in the gallery is set at index 0 in the images array' ); assert.ok( html.indexOf( ' src="' + imgSrc + '"' ) > 0, 'The image element passed in contains the src=... we want.' ); assert.ok( html.indexOf( ' alt="meow"' ) > 0, 'The image element passed in contains the alt=... we want.' ); assert.strictEqual( caption, 'Blah blah', 'The caption passed in is correct' ); assert.strictEqual( alt, 'meow', 'The alt text passed in is correct' ); }; $link.trigger( { type: 'click', which: 1 } ); clock.tick( 10 ); assert.equal( bootstrap.setupOverlay.callCount, 1, 'Overlay was set up' ); clock.reset(); } ); */ QUnit.test( 'Only load the viewer on a valid hash (modern browsers)', function ( assert ) { var bootstrap; window.location.hash = ''; bootstrap = createBootstrap(); return hashTest( '/media', bootstrap, assert ); } ); QUnit.test( 'Only load the viewer on a valid hash (old browsers)', function ( assert ) { var bootstrap; window.location.hash = ''; bootstrap = createBootstrap(); bootstrap.browserHistory = undefined; return hashTest( '/media', bootstrap, assert ); } ); QUnit.test( 'Load the viewer on a legacy hash (modern browsers)', function ( assert ) { var bootstrap; window.location.hash = ''; bootstrap = createBootstrap(); return hashTest( 'mediaviewer', bootstrap, assert ); } ); QUnit.test( 'Load the viewer on a legacy hash (old browsers)', function ( assert ) { var bootstrap; window.location.hash = ''; bootstrap = createBootstrap(); bootstrap.browserHistory = undefined; return hashTest( 'mediaviewer', bootstrap, assert ); } ); QUnit.test( 'Overlay is set up on hash change', function ( assert ) { var bootstrap; window.location.hash = '#/media/foo'; bootstrap = createBootstrap(); this.sandbox.stub( bootstrap, 'setupOverlay' ); bootstrap.hash(); assert.ok( bootstrap.setupOverlay.called, 'Overlay is set up' ); } ); QUnit.test( 'Overlay is not set up on an irrelevant hash change', function ( assert ) { var bootstrap; window.location.hash = '#foo'; bootstrap = createBootstrap(); this.sandbox.stub( bootstrap, 'setupOverlay' ); bootstrap.loadViewer(); bootstrap.setupOverlay.reset(); bootstrap.hash(); assert.ok( !bootstrap.setupOverlay.called, 'Overlay is not set up' ); } ); QUnit.test( 'internalHashChange', function ( assert ) { var bootstrap = createBootstrap(), hash = '#/media/foo', callCount = 0, clock = this.sandbox.useFakeTimers(); window.location.hash = ''; bootstrap.loadViewer = function () { callCount++; return $.Deferred().reject(); }; bootstrap.setupEventHandlers(); bootstrap.internalHashChange( { hash: hash } ); clock.tick( 10 ); assert.ok( callCount === 0, 'Viewer should not be loaded' ); assert.strictEqual( window.location.hash, hash, 'Window\'s hash has been updated correctly' ); bootstrap.cleanupEventHandlers(); window.location.hash = ''; clock.restore(); } ); QUnit.test( 'internalHashChange (legacy)', function ( assert ) { var bootstrap = createBootstrap(), hash = '#mediaviewer/foo', callCount = 0, clock = this.sandbox.useFakeTimers(); window.location.hash = ''; bootstrap.loadViewer = function () { callCount++; return $.Deferred().reject(); }; bootstrap.setupEventHandlers(); bootstrap.internalHashChange( { hash: hash } ); clock.tick( 10 ); assert.ok( callCount === 0, 'Viewer should not be loaded' ); assert.strictEqual( window.location.hash, hash, 'Window\'s hash has been updated correctly' ); bootstrap.cleanupEventHandlers(); window.location.hash = ''; clock.restore(); } ); QUnit.test( 'Restoring article scroll position', function ( assert ) { var stubbedScrollTop, bootstrap = createBootstrap(), $window = $( window ), done = assert.async(); this.sandbox.stub( $.fn, 'scrollTop', function ( scrollTop ) { if ( scrollTop !== undefined ) { stubbedScrollTop = scrollTop; return this; } else { return stubbedScrollTop; } } ); $window.scrollTop( 50 ); bootstrap.setupOverlay(); // Calling this a second time because it can happen in history navigation context bootstrap.setupOverlay(); // Clear scrollTop to check it is restored $window.scrollTop( 0 ); bootstrap.cleanupOverlay(); // Scroll restoration is on a setTimeout setTimeout( function () { assert.strictEqual( $( window ).scrollTop(), 50, 'Scroll is correctly reset to original top position' ); done(); } ); } ); QUnit.test( 'Preload JS/CSS dependencies on thumb hover', function ( assert ) { var $div, bootstrap, clock = this.sandbox.useFakeTimers(), viewer = { initWithThumbs: $.noop }; // Create gallery with image that has valid name extension $div = createThumb(); // Create a new bootstrap object to trigger the DOM scan, etc. bootstrap = createBootstrap( viewer ); this.sandbox.stub( mw.loader, 'load' ); $div.mouseenter(); clock.tick( bootstrap.hoverWaitDuration - 50 ); $div.mouseleave(); assert.ok( !mw.loader.load.called, 'Dependencies should not be preloaded if the thumb is not hovered long enough' ); $div.mouseenter(); clock.tick( bootstrap.hoverWaitDuration + 50 ); $div.mouseleave(); assert.ok( mw.loader.load.called, 'Dependencies should be preloaded if the thumb is hovered long enough' ); clock.restore(); } ); QUnit.test( 'isAllowedThumb', function ( assert ) { var $container = $( '<div>' ), $thumb = $( '<img>' ).appendTo( $container ), bootstrap = createBootstrap(); assert.ok( bootstrap.isAllowedThumb( $thumb ), 'Normal image in a div is allowed.' ); $container.addClass( 'metadata' ); assert.strictEqual( bootstrap.isAllowedThumb( $thumb ), false, 'Image in a metadata container is disallowed.' ); $container.prop( 'class', '' ); $container.addClass( 'noviewer' ); assert.strictEqual( bootstrap.isAllowedThumb( $thumb ), false, 'Image in a noviewer container is disallowed.' ); $container.prop( 'class', '' ); $container.addClass( 'noarticletext' ); assert.strictEqual( bootstrap.isAllowedThumb( $thumb ), false, 'Image in an empty article is disallowed.' ); $container.prop( 'class', '' ); $thumb.addClass( 'noviewer' ); assert.strictEqual( bootstrap.isAllowedThumb( $thumb ), false, 'Image with a noviewer class is disallowed.' ); } ); QUnit.test( 'findCaption', function ( assert ) { var gallery = createGallery( 'foo.jpg', 'Baz' ), thumb = createThumb( 'foo.jpg', 'Quuuuux' ), link = createNormal( 'foo.jpg', 'Foobar' ), multiple = createMultipleImage( [ [ 'foo.jpg', 'Image #1' ], [ 'bar.jpg', 'Image #2' ], [ 'foobar.jpg', 'Image #3' ] ] ), bootstrap = createBootstrap(); assert.strictEqual( bootstrap.findCaption( gallery.find( '.thumb' ), gallery.find( 'a.image' ) ), 'Baz', 'A gallery caption is found.' ); assert.strictEqual( bootstrap.findCaption( thumb, thumb.find( 'a.image' ) ), 'Quuuuux', 'A thumbnail caption is found.' ); assert.strictEqual( bootstrap.findCaption( $(), link ), 'Foobar', 'The caption is found even if the image is not a thumbnail.' ); assert.strictEqual( bootstrap.findCaption( multiple, multiple.find( 'img[src="bar.jpg"]' ).closest( 'a' ) ), 'Image #2', 'The caption is found in {{Multiple image}}.' ); } ); }( mediaWiki, jQuery ) );
const { NotImplementedError } = require('../extensions/index.js'); /** * Calculate turns number and time (in seconds) required * to solve puzzle * * @param {Number} disks number of disks * @param {Number} turnsSpeed speed (in turns/hour) * @return {Object} object with props turns (number of turns) * and seconds (time in seconds) * * @example * * calculateHanoi(9, 4308) => { turns: 511, seconds: 427 } * */ const calculateHanoi = (disksNumber, turnsSpeed) => { const turns = (2 ** disksNumber) - 1; const seconds = Math.floor(turns / (turnsSpeed / 3600)); return {turns: turns, seconds: seconds}; }; module.exports = { calculateHanoi };
import fs from 'fs'; import glob from 'glob'; import dot from 'dot-object'; import { readVueFiles, readLangFiles, extractI18nItemsFromVueFiles, extractI18nItemsFromLanguageFiles, logMissingKeys, logUnusedKeys, } from './library/index'; export var VueI18NExtractReportTypes; (function (VueI18NExtractReportTypes) { VueI18NExtractReportTypes[VueI18NExtractReportTypes["None"] = 0] = "None"; VueI18NExtractReportTypes[VueI18NExtractReportTypes["Missing"] = 1] = "Missing"; VueI18NExtractReportTypes[VueI18NExtractReportTypes["Unused"] = 2] = "Unused"; VueI18NExtractReportTypes[VueI18NExtractReportTypes["All"] = 3] = "All"; })(VueI18NExtractReportTypes || (VueI18NExtractReportTypes = {})); ; export default class VueI18NExtract { parseVueFiles(vueFilesPath) { const filesList = readVueFiles(vueFilesPath); return extractI18nItemsFromVueFiles(filesList); } parseLanguageFiles(languageFilesPath) { const filesList = readLangFiles(languageFilesPath); return extractI18nItemsFromLanguageFiles(filesList); } createI18NReport(vueFiles, languageFiles, reportType = VueI18NExtractReportTypes.All) { const parsedVueFiles = this.parseVueFiles(vueFiles); const parsedLanguageFiles = this.parseLanguageFiles(languageFiles); return this.extractI18NReport(parsedVueFiles, parsedLanguageFiles, reportType); } extractI18NReport(parsedVueFiles, parsedLanguageFiles, reportType = VueI18NExtractReportTypes.All) { const missingKeys = []; const unusedKeys = []; Object.keys(parsedLanguageFiles).forEach((language) => { let languageItems = parsedLanguageFiles[language]; parsedVueFiles.forEach((vueItem) => { const usedByVueItem = ({ path }) => path === vueItem.path || path.startsWith(vueItem.path + '.'); if (!parsedLanguageFiles[language].some(usedByVueItem)) { missingKeys.push(({ ...vueItem, language })); } languageItems = languageItems.filter((i) => !usedByVueItem(i)); }); unusedKeys.push(...languageItems.map((item) => ({ ...item, language }))); }); let extracts = {}; if (reportType & VueI18NExtractReportTypes.Missing) { extracts = Object.assign(extracts, { missingKeys }); } if (reportType & VueI18NExtractReportTypes.Unused) { extracts = Object.assign(extracts, { unusedKeys }); } return extracts; } logI18NReport(report) { Object.keys(report).forEach(key => { if (key === 'missingKeys') { logMissingKeys(report.missingKeys); } else if (key === 'unusedKeys') { logUnusedKeys(report.unusedKeys); } }); } writeMissingToLanguage(resolvedLanguageFiles, i18nReport) { var globArray = glob.sync(resolvedLanguageFiles); var parsedContent = globArray .map(f => fs.readFileSync(f, 'utf8')) .map(i => JSON.parse(i)); i18nReport.missingKeys.forEach(item => { parsedContent.forEach(i => dot.str(item.path, '', i)); }); let stringifyiedContent = parsedContent .map(i => JSON.stringify(i, null, 2)); stringifyiedContent .forEach((i, index) => fs.writeFileSync(globArray[index], i)); } async writeReportToFile(report, writePath) { const reportString = JSON.stringify(report); return new Promise((resolve, reject) => { fs.writeFile(writePath, reportString, (err) => { if (err) { reject(err); return; } resolve(); }); }); } }
const fz = {...require('../converters/fromZigbee'), legacy: require('../lib/legacy').fromZigbee}; const reporting = require('../lib/reporting'); const extend = require('../lib/extend'); module.exports = [ { zigbeeModel: ['43076'], model: '43076', vendor: 'Enbrighten', description: 'Zigbee in-wall smart switch', extend: extend.switch(), meta: {configureKey: 1}, configure: async (device, coordinatorEndpoint, logger) => { const endpoint = device.getEndpoint(1); await reporting.bind(endpoint, coordinatorEndpoint, ['genOnOff']); await reporting.onOff(endpoint); }, }, { zigbeeModel: ['43080'], model: '43080', vendor: 'Enbrighten', description: 'Zigbee in-wall smart dimmer', extend: extend.light_onoff_brightness(), meta: {configureKey: 1}, configure: async (device, coordinatorEndpoint, logger) => { const endpoint = device.getEndpoint(1); await reporting.bind(endpoint, coordinatorEndpoint, ['genOnOff', 'genLevelCtrl']); await reporting.onOff(endpoint); }, }, { zigbeeModel: ['43102'], model: '43102', vendor: 'Enbrighten', description: 'Zigbee in-wall outlet', extend: extend.switch(), }, { zigbeeModel: ['43100'], model: '43100', vendor: 'Enbrighten', description: 'Plug-in Zigbee outdoor smart switch', extend: extend.switch(), fromZigbee: [fz.command_on_state, fz.command_off_state], meta: {configureKey: 1}, configure: async (device, coordinatorEndpoint, logger) => { const endpoint1 = device.getEndpoint(1); const endpoint2 = device.getEndpoint(2); await reporting.bind(endpoint2, coordinatorEndpoint, ['genOnOff']); await reporting.bind(endpoint1, coordinatorEndpoint, ['genOnOff']); await reporting.onOff(endpoint1); }, }, { zigbeeModel: ['43082'], model: '43082', vendor: 'Enbrighten', description: 'Zigbee in-wall smart dimmer', extend: extend.light_onoff_brightness({disableEffect: true}), meta: {configureKey: 1}, configure: async (device, coordinatorEndpoint, logger) => { const endpoint = device.getEndpoint(1); await reporting.bind(endpoint, coordinatorEndpoint, ['genOnOff', 'genLevelCtrl']); await reporting.onOff(endpoint); }, }, { zigbeeModel: ['43084'], model: '43084', vendor: 'Enbrighten', description: 'Zigbee in-wall smart switch', extend: extend.switch(), meta: {configureKey: 1}, configure: async (device, coordinatorEndpoint, logger) => { const endpoint = device.getEndpoint(1); await reporting.bind(endpoint, coordinatorEndpoint, ['genOnOff']); await reporting.onOff(endpoint); }, }, { zigbeeModel: ['43090'], model: '43090', vendor: 'Enbrighten', description: 'Zigbee in-wall smart dimmer', extend: extend.light_onoff_brightness(), meta: {configureKey: 1}, configure: async (device, coordinatorEndpoint, logger) => { const endpoint = device.getEndpoint(1); await reporting.bind(endpoint, coordinatorEndpoint, ['genOnOff', 'genLevelCtrl']); await reporting.onOff(endpoint); }, }, ];
/* Field Color (color) */ /*global jQuery, document, redux_change, redux*/ (function( $ ) { 'use strict'; redux.field_objects = redux.field_objects || {}; redux.field_objects.color = redux.field_objects.color || {}; $( document ).ready( function() { } ); redux.field_objects.color.init = function( selector ) { if ( !selector ) { selector = $( document ).find( ".redux-group-tab:visible" ).find( '.redux-container-color:visible' ); } $( selector ).each( function() { var el = $( this ); var parent = el; if ( !el.hasClass( 'redux-field-container' ) ) { parent = el.parents( '.redux-field-container:first' ); } if ( parent.is( ":hidden" ) ) { // Skip hidden fields return; } if ( parent.hasClass( 'redux-field-init' ) ) { parent.removeClass( 'redux-field-init' ); } else { return; } el.find( '.redux-color-init' ).wpColorPicker( { change: function( e, ui ) { $( this ).val( ui.color.toString() ); redux_change( $( this ) ); el.find( '#' + e.target.getAttribute( 'data-id' ) + '-transparency' ).removeAttr( 'checked' ); }, clear: function( e, ui ) { $( this ).val( ui.color.toString() ); redux_change( $( this ).parent().find( '.redux-color-init' ) ); } } ); el.find( '.redux-color' ).on( 'focus', function() { $( this ).data( 'oldcolor', $( this ).val() ); } ); el.find( '.redux-color' ).on( 'keyup', function() { var value = $( this ).val(); var color = colorValidate( this ); var id = '#' + $( this ).attr( 'id' ); if ( value === "transparent" ) { $( this ).parent().parent().find( '.wp-color-result' ).css( 'background-color', 'transparent' ); el.find( id + '-transparency' ).attr( 'checked', 'checked' ); } else { el.find( id + '-transparency' ).removeAttr( 'checked' ); if ( color && color !== $( this ).val() ) { $( this ).val( color ); } } } ); // Replace and validate field on blur el.find( '.redux-color' ).on( 'blur', function() { var value = $( this ).val(); var id = '#' + $( this ).attr( 'id' ); if ( value === "transparent" ) { $( this ).parent().parent().find( '.wp-color-result' ).css( 'background-color', 'transparent' ); el.find( id + '-transparency' ).attr( 'checked', 'checked' ); } else { if ( colorValidate( this ) === value ) { if ( value.indexOf( "#" ) !== 0 ) { $( this ).val( $( this ).data( 'oldcolor' ) ); } } el.find( id + '-transparency' ).removeAttr( 'checked' ); } } ); // Store the old valid color on keydown el.find( '.redux-color' ).on( 'keydown', function() { $( this ).data( 'oldkeypress', $( this ).val() ); } ); // When transparency checkbox is clicked el.find( '.color-transparency' ).on( 'click', function() { if ( $( this ).is( ":checked" ) ) { el.find( '.redux-saved-color' ).val( $( '#' + $( this ).data( 'id' ) ).val() ); el.find( '#' + $( this ).data( 'id' ) ).val( 'transparent' ); el.find( '#' + $( this ).data( 'id' ) ).parent().parent().find( '.wp-color-result' ).css( 'background-color', 'transparent' ); } else { if ( el.find( '#' + $( this ).data( 'id' ) ).val() === 'transparent' ) { var prevColor = $( '.redux-saved-color' ).val(); if ( prevColor === '' ) { prevColor = $( '#' + $( this ).data( 'id' ) ).data( 'default-color' ); } el.find( '#' + $( this ).data( 'id' ) ).parent().parent().find( '.wp-color-result' ).css( 'background-color', prevColor ); el.find( '#' + $( this ).data( 'id' ) ).val( prevColor ); } } } ); } ); }; })( jQuery );
// Copyright & License details are available under JXCORE_LICENSE file /* This code tests if some of the evaluated values in a subthread are the same as in the mainthread. Code spawns itself in mt-keep mode and gets results from files, since we cannot rely on stdout. */ if (process.isPackaged) return; var path = require("path"); var fs = require("fs"); var cp = require("child_process"); var assert = require('assert'); var clog = jxcore.utils.console.log; var mted = process.argv[1].substr(0, 2) === "mt"; var mtparam = "mt-keep:2"; var finished = false; var output = JSON.stringify(process.execArgv); var propName = "process.execArgv"; process.on("exit", function (code) { assert.ok(finished, "Test did not finish!"); }); // in order to compare process.argv, we remove argv[0] and argv[1] (mt/mt-keep) if (propName === "process.argv") { var copy = process.argv.slice(0); if (mted) { // removing "mt" or "mt:keep" from process.argv[1] copy.splice(0, 2); } else { // also removing from test argv[0], since from mt it contains full path // and in ST it can be just 'jx' copy.splice(0, 1); } output = JSON.stringify(copy); } var outFileName = process.cwd() + path.sep + "test-mt-values-tmp-0.txt"; if (mted) { // this block runs with jx mt // saves evaluation results into the file finished = true; if (process.threadId == 0) { fs.writeFileSync(outFileName, output); // forcing faster exit than naturally setTimeout(process.exit, 10); } return; } // the rest of the test runs in main thread // now evaluating inside mt-keep and comparing with ST evaluations // we pass all process.argv except [0] var cmd = '"' + process.execPath + '" ' + mtparam + ' ' + process.argv.slice(1).join(" "); if (fs.existsSync(outFileName)) fs.unlinkSync(outFileName); var child = cp.exec(cmd, {timeout: 10000}, function (error, stdout, stderr) { var exists = fs.existsSync(outFileName); assert.ok(exists, "Could not find output written to file " + outFileName); // checking results of mt var ret = fs.readFileSync(outFileName).toString(); fs.unlinkSync(outFileName); clog("main thread:", "green"); clog("\t", output); clog("MT-KEEP:", "magenta"); clog("\t", ret); assert.strictEqual(output, ret, "Values are not equal: process.execArgv"); finished = true; // forcing faster exit than naturally setTimeout(process.exit, 10); });
import nodemailer from 'nodemailer'; import exphbs from 'express-handlebars'; import nodemailerhbs from 'nodemailer-express-handlebars'; import {resolve} from 'path'; import mailConfig from '../config/mail'; class Mail{ constructor(){ const {host, port, secure, auth} = mailConfig; this.transporter = nodemailer.createTransport({ host, port, secure, auth: auth.user ? auth: null, }); this.configureTemplates(); } sendMail(message){ return this.transporter.sendMail({ ...mailConfig.default, ...message, }); } configureTemplates(){ const viewPath = resolve(__dirname, '..', 'app', 'views', 'emails'); this.transporter.use('compile', nodemailerhbs({ viewEngine: exphbs.create({ layoutsDir: resolve(viewPath, 'layouts'), partialsDir: resolve(viewPath, 'partials'), defaultLayout: 'default', extname: '.hbs', }), viewPath, extName: '.hbs', })) } } export default new Mail();
/*! * Knockout ES5 plugin - https://github.com/SteveSanderson/knockout-es5 * Copyright (c) Steve Sanderson * MIT license */ (function(global, undefined) { 'use strict'; // Model tracking // -------------- // // This is the central feature of Knockout-ES5. We augment model objects by converting properties // into ES5 getter/setter pairs that read/write an underlying Knockout observable. This means you can // use plain JavaScript syntax to read/write the property while still getting the full benefits of // Knockout's automatic dependency detection and notification triggering. // // For comparison, here's Knockout ES3-compatible syntax: // // var firstNameLength = myModel.user().firstName().length; // Read // myModel.user().firstName('Bert'); // Write // // ... versus Knockout-ES5 syntax: // // var firstNameLength = myModel.user.firstName.length; // Read // myModel.user.firstName = 'Bert'; // Write // `ko.track(model)` converts each property on the given model object into a getter/setter pair that // wraps a Knockout observable. Optionally specify an array of property names to wrap; otherwise we // wrap all properties. If any of the properties are already observables, we replace them with // ES5 getter/setter pairs that wrap your original observable instances. In the case of readonly // ko.computed properties, we simply do not define a setter (so attempted writes will be ignored, // which is how ES5 readonly properties normally behave). // // By design, this does *not* recursively walk child object properties, because making literally // everything everywhere independently observable is usually unhelpful. When you do want to track // child object properties independently, define your own class for those child objects and put // a separate ko.track call into its constructor --- this gives you far more control. function track(obj, propertyNames) { if (!obj || typeof obj !== 'object') { throw new Error('When calling ko.track, you must pass an object as the first parameter.'); } var ko = this, allObservablesForObject = getAllObservablesForObject(obj, true); propertyNames = propertyNames || Object.getOwnPropertyNames(obj); propertyNames.forEach(function(propertyName) { // Skip properties that are already tracked if (propertyName in allObservablesForObject) { return; } // Skip properties where descriptor can't be redefined if ( false === Object.getOwnPropertyDescriptor(obj, propertyName).configurable ){ return; } var origValue = obj[propertyName], isArray = origValue instanceof Array, observable = ko.isObservable(origValue) ? origValue : isArray ? ko.observableArray(origValue) : ko.observable(origValue); Object.defineProperty(obj, propertyName, { configurable: true, enumerable: true, get: observable, set: ko.isWriteableObservable(observable) ? observable : undefined }); allObservablesForObject[propertyName] = observable; if (isArray) { notifyWhenPresentOrFutureArrayValuesMutate(ko, observable); } }); return obj; } // Lazily created by `getAllObservablesForObject` below. Has to be created lazily because the // WeakMap factory isn't available until the module has finished loading (may be async). var objectToObservableMap; // Gets or creates the hidden internal key-value collection of observables corresponding to // properties on the model object. function getAllObservablesForObject(obj, createIfNotDefined) { if (!objectToObservableMap) { objectToObservableMap = weakMapFactory(); } var result = objectToObservableMap.get(obj); if (!result && createIfNotDefined) { result = {}; objectToObservableMap.set(obj, result); } return result; } // Computed properties // ------------------- // // The preceding code is already sufficient to upgrade ko.computed model properties to ES5 // getter/setter pairs (or in the case of readonly ko.computed properties, just a getter). // These then behave like a regular property with a getter function, except they are smarter: // your evaluator is only invoked when one of its dependencies changes. The result is cached // and used for all evaluations until the next time a dependency changes). // // However, instead of forcing developers to declare a ko.computed property explicitly, it's // nice to offer a utility function that declares a computed getter directly. // Implements `ko.defineProperty` function defineComputedProperty(obj, propertyName, evaluatorOrOptions) { var ko = this, computedOptions = { owner: obj, deferEvaluation: true }; if (typeof evaluatorOrOptions === 'function') { computedOptions.read = evaluatorOrOptions; } else { if ('value' in evaluatorOrOptions) { throw new Error('For ko.defineProperty, you must not specify a "value" for the property. You must provide a "get" function.'); } if (typeof evaluatorOrOptions.get !== 'function') { throw new Error('For ko.defineProperty, the third parameter must be either an evaluator function, or an options object containing a function called "get".'); } computedOptions.read = evaluatorOrOptions.get; computedOptions.write = evaluatorOrOptions.set; } obj[propertyName] = ko.computed(computedOptions); track.call(ko, obj, [propertyName]); return obj; } // Array handling // -------------- // // Arrays are special, because unlike other property types, they have standard mutator functions // (`push`/`pop`/`splice`/etc.) and it's desirable to trigger a change notification whenever one of // those mutator functions is invoked. // // Traditionally, Knockout handles this by putting special versions of `push`/`pop`/etc. on observable // arrays that mutate the underlying array and then trigger a notification. That approach doesn't // work for Knockout-ES5 because properties now return the underlying arrays, so the mutator runs // in the context of the underlying array, not any particular observable: // // // Operates on the underlying array value // myModel.someCollection.push('New value'); // // To solve this, Knockout-ES5 detects array values, and modifies them as follows: // 1. Associates a hidden subscribable with each array instance that it encounters // 2. Intercepts standard mutators (`push`/`pop`/etc.) and makes them trigger the subscribable // Then, for model properties whose values are arrays, the property's underlying observable // subscribes to the array subscribable, so it can trigger a change notification after mutation. // Given an observable that underlies a model property, watch for any array value that might // be assigned as the property value, and hook into its change events function notifyWhenPresentOrFutureArrayValuesMutate(ko, observable) { var watchingArraySubscription = null; ko.computed(function () { // Unsubscribe to any earlier array instance if (watchingArraySubscription) { watchingArraySubscription.dispose(); watchingArraySubscription = null; } // Subscribe to the new array instance var newArrayInstance = observable(); if (newArrayInstance instanceof Array) { watchingArraySubscription = startWatchingArrayInstance(ko, observable, newArrayInstance); } }); } // Listens for array mutations, and when they happen, cause the observable to fire notifications. // This is used to make model properties of type array fire notifications when the array changes. // Returns a subscribable that can later be disposed. function startWatchingArrayInstance(ko, observable, arrayInstance) { var subscribable = getSubscribableForArray(ko, arrayInstance); return subscribable.subscribe(observable); } // Lazily created by `getSubscribableForArray` below. Has to be created lazily because the // WeakMap factory isn't available until the module has finished loading (may be async). var arraySubscribablesMap; // Gets or creates a subscribable that fires after each array mutation function getSubscribableForArray(ko, arrayInstance) { if (!arraySubscribablesMap) { arraySubscribablesMap = weakMapFactory(); } var subscribable = arraySubscribablesMap.get(arrayInstance); if (!subscribable) { subscribable = new ko.subscribable(); arraySubscribablesMap.set(arrayInstance, subscribable); var notificationPauseSignal = {}; wrapStandardArrayMutators(arrayInstance, subscribable, notificationPauseSignal); addKnockoutArrayMutators(ko, arrayInstance, subscribable, notificationPauseSignal); } return subscribable; } // After each array mutation, fires a notification on the given subscribable function wrapStandardArrayMutators(arrayInstance, subscribable, notificationPauseSignal) { ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'].forEach(function(fnName) { var origMutator = arrayInstance[fnName]; arrayInstance[fnName] = function() { var result = origMutator.apply(this, arguments); if (notificationPauseSignal.pause !== true) { subscribable.notifySubscribers(this); } return result; }; }); } // Adds Knockout's additional array mutation functions to the array function addKnockoutArrayMutators(ko, arrayInstance, subscribable, notificationPauseSignal) { ['remove', 'removeAll', 'destroy', 'destroyAll', 'replace'].forEach(function(fnName) { // Make it a non-enumerable property for consistency with standard Array functions Object.defineProperty(arrayInstance, fnName, { enumerable: false, value: function() { var result; // These additional array mutators are built using the underlying push/pop/etc. // mutators, which are wrapped to trigger notifications. But we don't want to // trigger multiple notifications, so pause the push/pop/etc. wrappers and // delivery only one notification at the end of the process. notificationPauseSignal.pause = true; try { // Creates a temporary observableArray that can perform the operation. result = ko.observableArray.fn[fnName].apply(ko.observableArray(arrayInstance), arguments); } finally { notificationPauseSignal.pause = false; } subscribable.notifySubscribers(arrayInstance); return result; } }); }); } // Static utility functions // ------------------------ // // Since Knockout-ES5 sets up properties that return values, not observables, you can't // trivially subscribe to the underlying observables (e.g., `someProperty.subscribe(...)`), // or tell them that object values have mutated, etc. To handle this, we set up some // extra utility functions that can return or work with the underlying observables. // Returns the underlying observable associated with a model property (or `null` if the // model or property doesn't exist, or isn't associated with an observable). This means // you can subscribe to the property, e.g.: // // ko.getObservable(model, 'propertyName') // .subscribe(function(newValue) { ... }); function getObservable(obj, propertyName) { if (!obj || typeof obj !== 'object') { return null; } var allObservablesForObject = getAllObservablesForObject(obj, false); return (allObservablesForObject && allObservablesForObject[propertyName]) || null; } // Causes a property's associated observable to fire a change notification. Useful when // the property value is a complex object and you've modified a child property. function valueHasMutated(obj, propertyName) { var observable = getObservable(obj, propertyName); if (observable) { observable.valueHasMutated(); } } // Module initialisation // --------------------- // // When this script is first evaluated, it works out what kind of module loading scenario // it is in (Node.js or a browser `<script>` tag), stashes a reference to its dependencies // (currently that's just the WeakMap shim), and then finally attaches itself to whichever // instance of Knockout.js it can find. // A function that returns a new ES6-compatible WeakMap instance (using ES5 shim if needed). // Instantiated by prepareExports, accounting for which module loader is being used. var weakMapFactory; // Extends a Knockout instance with Knockout-ES5 functionality function attachToKo(ko) { ko.track = track; ko.getObservable = getObservable; ko.valueHasMutated = valueHasMutated; ko.defineProperty = defineComputedProperty; } // Determines which module loading scenario we're in, grabs dependencies, and attaches to KO function prepareExports() { if (typeof module !== 'undefined') { // Node.js case - load KO and WeakMap modules synchronously var ko = require('knockout'), WM = require('weakmap'); attachToKo(ko); weakMapFactory = function() { return new WM(); }; module.exports = ko; } else if ('ko' in global) { // Non-module case - attach to the global instance, and assume a global WeakMap constructor attachToKo(global.ko); weakMapFactory = function() { return new global.WeakMap(); }; } } prepareExports(); })(this); /*! WeakMap shim * (The MIT License) * * Copyright (c) 2012 Brandon Benvie <http://bbenvie.com> * * 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 with 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. */ // Original WeakMap implementation by Gozala @ https://gist.github.com/1269991 // Updated and bugfixed by Raynos @ https://gist.github.com/1638059 // Expanded by Benvie @ https://github.com/Benvie/harmony-collections // This is the version used by knockout-es5. Modified by Steve Sanderson as follows: // [1] Deleted weakmap.min.js (it's not useful as it would be out of sync with weakmap.js now I'm editing it) // [2] Since UglifyJS strips inline function names (and you can't disable that without disabling name mangling // entirely), insert code that re-adds function names void function(global, undefined_, undefined){ var getProps = Object.getOwnPropertyNames, defProp = Object.defineProperty, toSource = Function.prototype.toString, create = Object.create, hasOwn = Object.prototype.hasOwnProperty, funcName = /^\n?function\s?(\w*)?_?\(/; function define(object, key, value){ if (typeof key === 'function') { value = key; key = nameOf(value).replace(/_$/, ''); } return defProp(object, key, { configurable: true, writable: true, value: value }); } function nameOf(func){ return typeof func !== 'function' ? '' : '_name' in func ? func._name : 'name' in func ? func.name : toSource.call(func).match(funcName)[1]; } function namedFunction(name, func) { // Undo the name-stripping that UglifyJS does func._name = name; return func; } // ############ // ### Data ### // ############ var Data = (function(){ var dataDesc = { value: { writable: true, value: undefined } }, datalock = 'return function(k){if(k===s)return l}', uids = create(null), createUID = function(){ var key = Math.random().toString(36).slice(2); return key in uids ? createUID() : uids[key] = key; }, globalID = createUID(), storage = function(obj){ if (hasOwn.call(obj, globalID)) return obj[globalID]; if (!Object.isExtensible(obj)) throw new TypeError("Object must be extensible"); var store = create(null); defProp(obj, globalID, { value: store }); return store; }; // common per-object storage area made visible by patching getOwnPropertyNames' define(Object, namedFunction('getOwnPropertyNames', function getOwnPropertyNames(obj){ var props = getProps(obj); if (hasOwn.call(obj, globalID)) props.splice(props.indexOf(globalID), 1); return props; })); function Data(){ var puid = createUID(), secret = {}; this.unlock = function(obj){ var store = storage(obj); if (hasOwn.call(store, puid)) return store[puid](secret); var data = create(null, dataDesc); defProp(store, puid, { value: new Function('s', 'l', datalock)(secret, data) }); return data; } } define(Data.prototype, namedFunction('get', function get(o){ return this.unlock(o).value })); define(Data.prototype, namedFunction('set', function set(o, v){ this.unlock(o).value = v })); return Data; }()); var WM = (function(data){ var validate = function(key){ if (key == null || typeof key !== 'object' && typeof key !== 'function') throw new TypeError("Invalid WeakMap key"); } var wrap = function(collection, value){ var store = data.unlock(collection); if (store.value) throw new TypeError("Object is already a WeakMap"); store.value = value; } var unwrap = function(collection){ var storage = data.unlock(collection).value; if (!storage) throw new TypeError("WeakMap is not generic"); return storage; } var initialize = function(weakmap, iterable){ if (iterable !== null && typeof iterable === 'object' && typeof iterable.forEach === 'function') { iterable.forEach(function(item, i){ if (item instanceof Array && item.length === 2) set.call(weakmap, iterable[i][0], iterable[i][1]); }); } } function WeakMap(iterable){ if (this === global || this == null || this === WeakMap.prototype) return new WeakMap(iterable); wrap(this, new Data); initialize(this, iterable); } function get(key){ validate(key); var value = unwrap(this).get(key); return value === undefined_ ? undefined : value; } function set(key, value){ validate(key); // store a token for explicit undefined so that "has" works correctly unwrap(this).set(key, value === undefined ? undefined_ : value); } function has(key){ validate(key); return unwrap(this).get(key) !== undefined; } function delete_(key){ validate(key); var data = unwrap(this), had = data.get(key) !== undefined; data.set(key, undefined); return had; } function toString(){ unwrap(this); return '[object WeakMap]'; } // Undo the function-name stripping that UglifyJS does get._name = 'get'; set._name = 'set'; has._name = 'has'; toString._name = 'toString'; try { var src = ('return '+delete_).replace('e_', '\\u0065'), del = new Function('unwrap', 'validate', src)(unwrap, validate); } catch (e) { var del = delete_; } var src = (''+Object).split('Object'); var stringifier = namedFunction('toString', function toString(){ return src[0] + nameOf(this) + src[1]; }); define(stringifier, stringifier); var prep = { __proto__: [] } instanceof Array ? function(f){ f.__proto__ = stringifier } : function(f){ define(f, stringifier) }; prep(WeakMap); [toString, get, set, has, del].forEach(function(method){ define(WeakMap.prototype, method); prep(method); }); return WeakMap; }(new Data)); var defaultCreator = Object.create ? function(){ return Object.create(null) } : function(){ return {} }; function createStorage(creator){ var weakmap = new WM; creator || (creator = defaultCreator); function storage(object, value){ if (value || arguments.length === 2) { weakmap.set(object, value); } else { value = weakmap.get(object); if (value === undefined) { value = creator(object); weakmap.set(object, value); } } return value; } return storage; } if (typeof module !== 'undefined') { module.exports = WM; } else if (typeof exports !== 'undefined') { exports.WeakMap = WM; } else if (!('WeakMap' in global)) { global.WeakMap = WM; } WM.createStorage = createStorage; if (global.WeakMap) global.WeakMap.createStorage = createStorage; }((0, eval)('this'));
module.exports = { selector: '#lift li', parse: { name: 1, status: { child: 0, attribute: 'class', regex: /-([a-z]+)$/ } } };
/** * @license Angular v5.2.6 * (c) 2010-2018 Google, Inc. https://angular.io/ * License: MIT */ import { EventEmitter, Injectable } from '@angular/core'; import { __extends } from 'tslib'; import { LocationStrategy } from '@angular/common'; /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A spy for {\@link Location} that allows tests to fire simulated location events. * * \@experimental */ var SpyLocation = /** @class */ (function () { function SpyLocation() { this.urlChanges = []; this._history = [new LocationState('', '')]; this._historyIndex = 0; /** * \@internal */ this._subject = new EventEmitter(); /** * \@internal */ this._baseHref = ''; /** * \@internal */ this._platformStrategy = /** @type {?} */ ((null)); } /** * @param {?} url * @return {?} */ SpyLocation.prototype.setInitialPath = /** * @param {?} url * @return {?} */ function (url) { this._history[this._historyIndex].path = url; }; /** * @param {?} url * @return {?} */ SpyLocation.prototype.setBaseHref = /** * @param {?} url * @return {?} */ function (url) { this._baseHref = url; }; /** * @return {?} */ SpyLocation.prototype.path = /** * @return {?} */ function () { return this._history[this._historyIndex].path; }; /** * @param {?} path * @param {?=} query * @return {?} */ SpyLocation.prototype.isCurrentPathEqualTo = /** * @param {?} path * @param {?=} query * @return {?} */ function (path, query) { if (query === void 0) { query = ''; } var /** @type {?} */ givenPath = path.endsWith('/') ? path.substring(0, path.length - 1) : path; var /** @type {?} */ currPath = this.path().endsWith('/') ? this.path().substring(0, this.path().length - 1) : this.path(); return currPath == givenPath + (query.length > 0 ? ('?' + query) : ''); }; /** * @param {?} pathname * @return {?} */ SpyLocation.prototype.simulateUrlPop = /** * @param {?} pathname * @return {?} */ function (pathname) { this._subject.emit({ 'url': pathname, 'pop': true, 'type': 'popstate' }); }; /** * @param {?} pathname * @return {?} */ SpyLocation.prototype.simulateHashChange = /** * @param {?} pathname * @return {?} */ function (pathname) { // Because we don't prevent the native event, the browser will independently update the path this.setInitialPath(pathname); this.urlChanges.push('hash: ' + pathname); this._subject.emit({ 'url': pathname, 'pop': true, 'type': 'hashchange' }); }; /** * @param {?} url * @return {?} */ SpyLocation.prototype.prepareExternalUrl = /** * @param {?} url * @return {?} */ function (url) { if (url.length > 0 && !url.startsWith('/')) { url = '/' + url; } return this._baseHref + url; }; /** * @param {?} path * @param {?=} query * @return {?} */ SpyLocation.prototype.go = /** * @param {?} path * @param {?=} query * @return {?} */ function (path, query) { if (query === void 0) { query = ''; } path = this.prepareExternalUrl(path); if (this._historyIndex > 0) { this._history.splice(this._historyIndex + 1); } this._history.push(new LocationState(path, query)); this._historyIndex = this._history.length - 1; var /** @type {?} */ locationState = this._history[this._historyIndex - 1]; if (locationState.path == path && locationState.query == query) { return; } var /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : ''); this.urlChanges.push(url); this._subject.emit({ 'url': url, 'pop': false }); }; /** * @param {?} path * @param {?=} query * @return {?} */ SpyLocation.prototype.replaceState = /** * @param {?} path * @param {?=} query * @return {?} */ function (path, query) { if (query === void 0) { query = ''; } path = this.prepareExternalUrl(path); var /** @type {?} */ history = this._history[this._historyIndex]; if (history.path == path && history.query == query) { return; } history.path = path; history.query = query; var /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : ''); this.urlChanges.push('replace: ' + url); }; /** * @return {?} */ SpyLocation.prototype.forward = /** * @return {?} */ function () { if (this._historyIndex < (this._history.length - 1)) { this._historyIndex++; this._subject.emit({ 'url': this.path(), 'pop': true }); } }; /** * @return {?} */ SpyLocation.prototype.back = /** * @return {?} */ function () { if (this._historyIndex > 0) { this._historyIndex--; this._subject.emit({ 'url': this.path(), 'pop': true }); } }; /** * @param {?} onNext * @param {?=} onThrow * @param {?=} onReturn * @return {?} */ SpyLocation.prototype.subscribe = /** * @param {?} onNext * @param {?=} onThrow * @param {?=} onReturn * @return {?} */ function (onNext, onThrow, onReturn) { return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn }); }; /** * @param {?} url * @return {?} */ SpyLocation.prototype.normalize = /** * @param {?} url * @return {?} */ function (url) { return /** @type {?} */ ((null)); }; SpyLocation.decorators = [ { type: Injectable }, ]; /** @nocollapse */ SpyLocation.ctorParameters = function () { return []; }; return SpyLocation; }()); var LocationState = /** @class */ (function () { function LocationState(path, query) { this.path = path; this.query = query; } return LocationState; }()); /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A mock implementation of {\@link LocationStrategy} that allows tests to fire simulated * location events. * * \@stable */ var MockLocationStrategy = /** @class */ (function (_super) { __extends(MockLocationStrategy, _super); function MockLocationStrategy() { var _this = _super.call(this) || this; _this.internalBaseHref = '/'; _this.internalPath = '/'; _this.internalTitle = ''; _this.urlChanges = []; /** * \@internal */ _this._subject = new EventEmitter(); return _this; } /** * @param {?} url * @return {?} */ MockLocationStrategy.prototype.simulatePopState = /** * @param {?} url * @return {?} */ function (url) { this.internalPath = url; this._subject.emit(new _MockPopStateEvent(this.path())); }; /** * @param {?=} includeHash * @return {?} */ MockLocationStrategy.prototype.path = /** * @param {?=} includeHash * @return {?} */ function (includeHash) { if (includeHash === void 0) { includeHash = false; } return this.internalPath; }; /** * @param {?} internal * @return {?} */ MockLocationStrategy.prototype.prepareExternalUrl = /** * @param {?} internal * @return {?} */ function (internal) { if (internal.startsWith('/') && this.internalBaseHref.endsWith('/')) { return this.internalBaseHref + internal.substring(1); } return this.internalBaseHref + internal; }; /** * @param {?} ctx * @param {?} title * @param {?} path * @param {?} query * @return {?} */ MockLocationStrategy.prototype.pushState = /** * @param {?} ctx * @param {?} title * @param {?} path * @param {?} query * @return {?} */ function (ctx, title, path, query) { this.internalTitle = title; var /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : ''); this.internalPath = url; var /** @type {?} */ externalUrl = this.prepareExternalUrl(url); this.urlChanges.push(externalUrl); }; /** * @param {?} ctx * @param {?} title * @param {?} path * @param {?} query * @return {?} */ MockLocationStrategy.prototype.replaceState = /** * @param {?} ctx * @param {?} title * @param {?} path * @param {?} query * @return {?} */ function (ctx, title, path, query) { this.internalTitle = title; var /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : ''); this.internalPath = url; var /** @type {?} */ externalUrl = this.prepareExternalUrl(url); this.urlChanges.push('replace: ' + externalUrl); }; /** * @param {?} fn * @return {?} */ MockLocationStrategy.prototype.onPopState = /** * @param {?} fn * @return {?} */ function (fn) { this._subject.subscribe({ next: fn }); }; /** * @return {?} */ MockLocationStrategy.prototype.getBaseHref = /** * @return {?} */ function () { return this.internalBaseHref; }; /** * @return {?} */ MockLocationStrategy.prototype.back = /** * @return {?} */ function () { if (this.urlChanges.length > 0) { this.urlChanges.pop(); var /** @type {?} */ nextUrl = this.urlChanges.length > 0 ? this.urlChanges[this.urlChanges.length - 1] : ''; this.simulatePopState(nextUrl); } }; /** * @return {?} */ MockLocationStrategy.prototype.forward = /** * @return {?} */ function () { throw 'not implemented'; }; MockLocationStrategy.decorators = [ { type: Injectable }, ]; /** @nocollapse */ MockLocationStrategy.ctorParameters = function () { return []; }; return MockLocationStrategy; }(LocationStrategy)); var _MockPopStateEvent = /** @class */ (function () { function _MockPopStateEvent(newUrl) { this.newUrl = newUrl; this.pop = true; this.type = 'popstate'; } return _MockPopStateEvent; }()); /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * Entry point for all public APIs of this package. */ // This file only reexports content of the `src` folder. Keep it that way. /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * Generated bundle index. Do not edit. */ export { SpyLocation, MockLocationStrategy }; //# sourceMappingURL=testing.js.map
function User(email, name) { this.email = email; this.name = name; this.online = false; } User.prototype.login = function () { this.online = true; console.log(this.email, 'has logged in'); } User.prototype.logout = function () { this.online = false; console.log(this.email, 'has logged out'); } function Admin(...args) { User.apply(this, args); this.role = 'super admin'; } /* same code * function Admin(email, name) { * User.apply(this, [email, name]); *} */ Admin.prototype = Object.create(User.prototype); //User의 프로토타입을 Admin __proto__에 연결 Admin.prototype.deleteUser = function (u) { users = users.filter(user => { return user.email != u.email; }) } var userOne = new User('ryu@naver.com', 'Ryu'); var userTwo = new User('yoshi@mariiokorp.com', 'Yoshi'); var admin = new Admin('kim@naver.com', 'kim'); var users = [userOne, userTwo, admin]; console.log(userOne); userTwo.login();
var penyedia = new DaftarObj2({ prefix : 'penyedia', url : 'pages.php?Pg=ref_penyedia', formName : 'penyediaForm', penyedia_form : '0', loading: function(){ //alert('loading'); this.topBarRender(); this.filterRender(); this.daftarRender(); this.sumHalRender(); }, detail: function(){ //alert('detail'); var me = this; errmsg = this.CekCheckbox(); if(errmsg ==''){ var box = this.GetCbxChecked(); //UserAktivitasDet.genDetail(); }else{ alert(errmsg); } }, BidangAfter2: function(){ penyedia.refreshList(true); }, BidangAfterform: function(){ var me = this; //this.formName = 'adminForm'; $.ajax({ url: this.url+'&tipe=BidangAfterForm', type : 'POST', data:{fmSKPDBidang: $("#cmbBidangForm").val(), fmSKPDUrusan: $("#cmbUrusanForm").val() }, success: function(data) { var resp = eval('(' + data + ')'); //console.info(me); //console.info('id='+me.prefix+'CbxBagian'); document.getElementById('cmbBidangForm').innerHTML=resp.content.bidang; document.getElementById('cmbSKPDForm').innerHTML=resp.content.skpd; } }); }, pilihBidang: function(){ penyedia.refreshList(true); }, comboSKPDChanged: function(){ penyedia.refreshList(true); }, daftarRender:function(){ var me =this; //render daftar addCoverPage2( 'daftar_cover', 1, true, true, {renderTo: this.prefix+'_cont_daftar', imgsrc: 'images/wait.gif', style: {position:'absolute', top:'5', left:'5'} } ); $.ajax({ url: this.url+'&tipe=daftar', type:'POST', data:$('#'+this.formName).serialize(), success: function(data) { var resp = eval('(' + data + ')'); document.getElementById(me.prefix+'_cont_daftar').innerHTML = resp.content; me.sumHalRender(); } }); }, Baru: function(){ var me = this; var err=''; if (err =='' ){ var cover = this.prefix+'_formcover'; document.body.style.overflow='hidden'; if(me.penyedia_form==0){//baru dari penyedia addCoverPage2(cover,1,true,false); }else{//baru dari barang addCoverPage2(cover,999,true,false); } $.ajax({ type:'POST', data:$('#'+this.formName).serialize(), url: this.url+'&tipe=formBaru', success: function(data) { var resp = eval('(' + data + ')'); document.getElementById(cover).innerHTML = resp.content; me.AfterFormBaru(); } }); }else{ alert(err); } }, Edit:function(){ var me = this; errmsg = this.CekCheckbox(); if(errmsg ==''){ var box = this.GetCbxChecked(); //this.Show ('formedit',{idplh:box.value}, false, true); var cover = this.prefix+'_formcover'; addCoverPage2(cover,999,true,false); document.body.style.overflow='hidden'; $.ajax({ type:'POST', data:$('#'+this.formName).serialize(), url: this.url+'&tipe=formEdit', success: function(data) { var resp = eval('(' + data + ')'); if (resp.err ==''){ document.getElementById(cover).innerHTML = resp.content; me.AfterFormEdit(resp); }else{ alert(resp.err); delElem(cover); document.body.style.overflow='auto'; } } }); }else{ alert(errmsg); } }, Simpan: function(){ var me= this; this.OnErrorClose = false document.body.style.overflow='hidden'; var cover = this.prefix+'_formsimpan'; addCoverPage2(cover,1,true,false); /*this.sendReq( this.url, { idprs: 0, daftarProses: new Array('simpan')}, this.formDialog);*/ $.ajax({ type:'POST', data:$('#'+this.prefix+'_form').serialize(), url: this.url+'&tipe=simpan', success: function(data) { var resp = eval('(' + data + ')'); delElem(cover); //document.getElementById(cover).innerHTML = resp.content; if(resp.err==''){ if(me.penyedia_form==0){ me.Close(); me.AfterSimpan(); }else{ me.Close(); barang.refreshCombopenyedia(); } }else{ alert(resp.err); } } }); } });
// import Vue from "../node_modules/vue/dist/vue.js"; import Vue from 'vue' // 导入 css文件 import 'normalize.css/normalize.css' // A modern alternative to CSS resets // 引入第三方插件 import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import ECharts from 'vue-echarts/components/ECharts.vue' import '@/styles/index.scss' // global css // 引入工具类/组件 // import App from './App.vue'; import App from './App' // App.Vue import store from './store' // 会默认识别router里面的index.js文件(不能是其他名字) import router from './router' // Internationalization import i18n from './lang' // @ 以根目录的方式定义相对路径 import '@/icons' // icon import '@/permission' // permission control /** * If you don't want to use mock-server * you want to use MockJs for mock api * you can execute: mockXHR() * * Currently MockJs will be used in the production environment, * please remove it before going online! ! ! */ // set ElementUI lang to EN // 使用组件,需要 Vue.use() 的组件,也就是有 install 的组件 Vue.use(ElementUI, { i18n: (key, value) => i18n.t(key, value) }) // register global component, // 全局注册的行为必须在根 Vue 实例 (通过 new Vue) 创建之前发生 Vue.component('v-chart', ECharts) // Vue.config 是一个对象,包含 Vue 的全局配置。可以在启动应用之前修改下列 property: // 阻止你显示显示生产模式的消息阻止你显示显示生产模式的消息 Vue.config.productionTip = false new Vue({ el: '#app', router, // (缩写) 相当于 routes: routes store, i18n, // render: h => h(App) // createElement 函数是用来生成 HTML DOM 元素的 // https://www.jianshu.com/p/b68184695e1f render: function(createElement) { return createElement(App) } })
var Volume = { isDragging: false, init: function() { $('#bottom .volume').mousedown(function(event) { Volume.setVolume(event); }); $('#bottom .volume .slider .knob').mousedown(function(event) { Volume.startDrag(event); }); $(window).mouseup(function(event) { Volume.stopDrag(event); }); $(window).mousemove(function(event) { Volume.onDrag(event); }); }, startDrag: function(event) { Volume.isDragging = true; }, stopDrag: function(event) { Volume.isDragging = false; }, onDrag: function(event) { if (!Volume.isDragging) { return; } Volume.setVolume(event); }, setVolume: function(event) { var maxW = $('#bottom .volume').width(); var mX = event.pageX - $('#bottom .volume .slider').offset().left; if (mX < 0) { mX = 0; } if (mX > maxW) { mX = maxW; } player.setVolume(mX/maxW*100.0); $('#bottom .volume .slider').css({'width': mX}); }, updateUI: function(volume) { var maxW = $('#bottom .volume').width(), mX = maxW * volume / 100.0; $('#bottom .volume .slider').css({'width': mX}); } };
import React from "react" import Layout from "../components/layout" import Metadata from "../components/metadata" const Index = () => { return ( <Layout> <Metadata title="Home" description="This is my home page" /> <h1>Home page</h1> <h2>I help organisation thrive with Analytics, Insight and A/B Testing</h2> </Layout> ) } export default Index
/* global angular:false */ (function (angular, $) { 'use strict'; angular.module('mvcDemo') .controller('TasksCtrl', ['$scope', function ($scope, guaService) { $scope.tasks = [ {id: 111, name: 11111, description: 11111}, {id: 222, name: 22222, description: 11111}, {id: 333, name: 33333, description: 11111} ]; $scope.openAddTaskModal = function () { $('#add-task-content').openModal(); }; }]); })(angular, $);
define(["../../../vaadin-material-styles/color.js", "../../../vaadin-material-styles/typography.js", "../../../vaadin-material-styles/mixins/required-field.js", "../../../vaadin-material-styles/font-icons.js", "../../../vaadin-material-styles/mixins/field-button.js", "../../../../@polymer/polymer/lib/utils/html-tag.js"], function (_color, _typography, _requiredField, _fontIcons, _fieldButton, _htmlTag) { "use strict"; var _templateObject_15e89bb0feba11eb8439e3eec9305af7; var $_documentContainer = (0, _htmlTag.html)(_templateObject_15e89bb0feba11eb8439e3eec9305af7 || (_templateObject_15e89bb0feba11eb8439e3eec9305af7 = babelHelpers.taggedTemplateLiteral(["<dom-module id=\"material-text-field\" theme-for=\"vaadin-text-field\">\n <template>\n <style include=\"material-required-field material-field-button\">\n :host {\n display: inline-flex;\n position: relative;\n padding-top: 8px;\n margin-bottom: 8px;\n outline: none;\n color: var(--material-body-text-color);\n font-size: var(--material-body-font-size);\n line-height: 24px;\n font-family: var(--material-font-family);\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n }\n\n :host::before {\n line-height: 32px;\n }\n\n /* Strange gymnastics to make fields vertically align nicely in most cases\n (no label, with label, without prefix, with prefix, etc.) */\n\n :host([has-label]) {\n padding-top: 24px;\n }\n\n [part=\"label\"]:empty {\n display: none;\n }\n\n [part=\"label\"]:empty::before {\n content: \"\xA0\";\n position: absolute;\n }\n\n [part=\"input-field\"] {\n position: relative;\n top: -0.2px; /* NOTE(platosha): Adjusts for wrong flex baseline in Chrome & Safari */\n height: 32px;\n padding-left: 0;\n padding-right: 0;\n background-color: transparent;\n margin: 0;\n }\n\n [part=\"input-field\"]::before,\n [part=\"input-field\"]::after {\n content: \"\";\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n height: 1px;\n transform-origin: 50% 0%;\n background-color: var(--_material-text-field-input-line-background-color, #000);\n opacity: var(--_material-text-field-input-line-opacity, 0.42);\n }\n\n [part=\"input-field\"]::after {\n background-color: var(--material-primary-color);\n opacity: 0;\n height: 2px;\n bottom: 0;\n transform: scaleX(0);\n transition: opacity 0.175s;\n }\n\n :host([disabled]) [part=\"label\"],\n :host([disabled]) [part=\"value\"],\n :host([disabled]) [part=\"input-field\"] ::slotted(input),\n :host([disabled]) [part=\"input-field\"] ::slotted(textarea),\n :host([disabled]) [part=\"input-field\"] ::slotted([part=\"value\"]) {\n color: var(--material-disabled-text-color);\n -webkit-text-fill-color: var(--material-disabled-text-color);\n }\n\n [part=\"value\"],\n :host([disabled]) [part=\"input-field\"] ::slotted(input),\n :host([disabled]) [part=\"input-field\"] ::slotted(textarea),\n /* Slotted by vaadin-select-text-field */\n [part=\"input-field\"] ::slotted([part=\"value\"]) {\n outline: none;\n margin: 0;\n border: 0;\n border-radius: 0;\n padding: 8px 0;\n width: 100%;\n height: 100%;\n font-family: inherit;\n font-size: 1em;\n line-height: inherit;\n color: inherit;\n background-color: transparent;\n /* Disable default invalid style in Firefox */\n box-shadow: none;\n }\n\n /* TODO: the text opacity should be 42%, but the disabled style is 38%.\n Would need to introduce another property for it if we want to be 100% accurate. */\n [part=\"value\"]::-webkit-input-placeholder {\n color: var(--material-disabled-text-color);\n transition: opacity 0.175s 0.05s;\n opacity: 1;\n }\n\n [part=\"value\"]:-ms-input-placeholder {\n color: var(--material-disabled-text-color);\n }\n\n [part=\"value\"]::-moz-placeholder {\n color: var(--material-disabled-text-color);\n transition: opacity 0.175s 0.05s;\n opacity: 1;\n }\n\n [part=\"value\"]::placeholder {\n color: var(--material-disabled-text-color);\n transition: opacity 0.175s 0.1s;\n opacity: 1;\n }\n\n :host([has-label]:not([focused]):not([invalid]):not([theme=\"always-float-label\"])) [part=\"value\"]::-webkit-input-placeholder {\n opacity: 0;\n transition-delay: 0;\n }\n\n :host([has-label]:not([focused]):not([invalid]):not([theme=\"always-float-label\"])) [part=\"value\"]::-moz-placeholder {\n opacity: 0;\n transition-delay: 0;\n }\n\n :host([has-label]:not([focused]):not([invalid]):not([theme=\"always-float-label\"])) [part=\"value\"]::placeholder {\n opacity: 0;\n transition-delay: 0;\n }\n\n /* IE11 doesn\u2019t show the placeholder when the input is focused, so it\u2019s basically useless for this theme */\n :host([has-label]) [part=\"value\"]:-ms-input-placeholder {\n opacity: 0;\n }\n\n /* According to material theme guidelines, helper text should be hidden when error message is set and input is invalid */\n :host([has-helper][invalid][has-error-message]) [part=\"helper-text\"] {\n display: none;\n }\n\n [part=\"label\"] {\n width: 133%;\n transition: transform 0.175s, color 0.175s, width 0.175s;\n transition-timing-function: ease, ease, step-end;\n }\n\n :host([has-helper]) [part=\"helper-text\"]::before {\n content: \"\";\n display: block;\n height: 6px;\n }\n\n [part=\"helper-text\"],\n [part=\"helper-text\"] ::slotted(*) {\n font-size: .75rem;\n line-height: 1;\n color: var(--material-secondary-text-color);\n }\n\n /* TODO: using unsupported selector to fix IE11 (even thought the label element is scaled down,\n the 133% width still takes the same space as an unscaled element */\n ::-ms-backdrop,\n .vaadin-text-field-container {\n overflow: hidden;\n }\n\n /* Same fix for MS Edge ^^ */\n @supports (-ms-ime-align:auto) {\n .vaadin-text-field-container {\n overflow: hidden;\n }\n }\n\n :host(:hover:not([readonly]):not([invalid])) [part=\"input-field\"]::before {\n opacity: var(--_material-text-field-input-line-hover-opacity, 0.87);\n }\n\n :host([focused]:not([invalid])) [part=\"label\"] {\n color: var(--material-primary-text-color);\n }\n\n :host([focused]) [part=\"input-field\"]::after,\n :host([invalid]) [part=\"input-field\"]::after {\n opacity: 1;\n transform: none;\n transition: transform 0.175s, opacity 0.175s;\n }\n\n :host([invalid]) [part=\"input-field\"]::after {\n background-color: var(--material-error-color);\n }\n\n :host([input-prevented]) [part=\"input-field\"] {\n color: var(--material-error-text-color);\n }\n\n :host([disabled]) {\n pointer-events: none;\n }\n\n :host([disabled]) [part=\"input-field\"] {\n color: var(--material-disabled-text-color);\n }\n\n :host([disabled]) [part=\"input-field\"]::before {\n background-color: transparent;\n background-image: linear-gradient(90deg, var(--_material-text-field-input-line-background-color, #000) 0, var(--_material-text-field-input-line-background-color, #000) 2px, transparent 2px);\n background-size: 4px 1px;\n background-repeat: repeat-x;\n }\n\n /* Only target the visible floating label */\n :host([has-label]:not([has-value]):not([focused]):not([invalid]):not([theme~=\"always-float-label\"])) [part=\"label\"] {\n width: 100%;\n /* IE11 doesn\u2019t work with calc inside the translate function, so we need to have a fixed pixel value instead of 50% + 16px */\n transform: scale(1) translateY(24px);\n transition-timing-function: ease, ease, step-start;\n pointer-events: none;\n left: auto;\n right: auto;\n transition-delay: 0.1s;\n }\n\n /* Slotted content */\n\n [part=\"input-field\"] ::slotted(*:not([part=\"value\"]):not([part$=\"-button\"]):not(input):not(textarea)) {\n color: var(--material-secondary-text-color);\n }\n\n [part=\"clear-button\"]::before {\n content: var(--material-icons-clear);\n }\n\n /* RTL specific styles */\n\n :host([disabled][dir=\"rtl\"]) [part=\"input-field\"]::before {\n background-image: linear-gradient(-90deg, var(--_material-text-field-input-line-background-color, #000) 0, var(--_material-text-field-input-line-background-color, #000) 2px, transparent 2px);\n }\n </style>\n </template>\n</dom-module>"], ["<dom-module id=\"material-text-field\" theme-for=\"vaadin-text-field\">\n <template>\n <style include=\"material-required-field material-field-button\">\n :host {\n display: inline-flex;\n position: relative;\n padding-top: 8px;\n margin-bottom: 8px;\n outline: none;\n color: var(--material-body-text-color);\n font-size: var(--material-body-font-size);\n line-height: 24px;\n font-family: var(--material-font-family);\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n }\n\n :host::before {\n line-height: 32px;\n }\n\n /* Strange gymnastics to make fields vertically align nicely in most cases\n (no label, with label, without prefix, with prefix, etc.) */\n\n :host([has-label]) {\n padding-top: 24px;\n }\n\n [part=\"label\"]:empty {\n display: none;\n }\n\n [part=\"label\"]:empty::before {\n content: \"\xA0\";\n position: absolute;\n }\n\n [part=\"input-field\"] {\n position: relative;\n top: -0.2px; /* NOTE(platosha): Adjusts for wrong flex baseline in Chrome & Safari */\n height: 32px;\n padding-left: 0;\n padding-right: 0;\n background-color: transparent;\n margin: 0;\n }\n\n [part=\"input-field\"]::before,\n [part=\"input-field\"]::after {\n content: \"\";\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n height: 1px;\n transform-origin: 50% 0%;\n background-color: var(--_material-text-field-input-line-background-color, #000);\n opacity: var(--_material-text-field-input-line-opacity, 0.42);\n }\n\n [part=\"input-field\"]::after {\n background-color: var(--material-primary-color);\n opacity: 0;\n height: 2px;\n bottom: 0;\n transform: scaleX(0);\n transition: opacity 0.175s;\n }\n\n :host([disabled]) [part=\"label\"],\n :host([disabled]) [part=\"value\"],\n :host([disabled]) [part=\"input-field\"] ::slotted(input),\n :host([disabled]) [part=\"input-field\"] ::slotted(textarea),\n :host([disabled]) [part=\"input-field\"] ::slotted([part=\"value\"]) {\n color: var(--material-disabled-text-color);\n -webkit-text-fill-color: var(--material-disabled-text-color);\n }\n\n [part=\"value\"],\n :host([disabled]) [part=\"input-field\"] ::slotted(input),\n :host([disabled]) [part=\"input-field\"] ::slotted(textarea),\n /* Slotted by vaadin-select-text-field */\n [part=\"input-field\"] ::slotted([part=\"value\"]) {\n outline: none;\n margin: 0;\n border: 0;\n border-radius: 0;\n padding: 8px 0;\n width: 100%;\n height: 100%;\n font-family: inherit;\n font-size: 1em;\n line-height: inherit;\n color: inherit;\n background-color: transparent;\n /* Disable default invalid style in Firefox */\n box-shadow: none;\n }\n\n /* TODO: the text opacity should be 42%, but the disabled style is 38%.\n Would need to introduce another property for it if we want to be 100% accurate. */\n [part=\"value\"]::-webkit-input-placeholder {\n color: var(--material-disabled-text-color);\n transition: opacity 0.175s 0.05s;\n opacity: 1;\n }\n\n [part=\"value\"]:-ms-input-placeholder {\n color: var(--material-disabled-text-color);\n }\n\n [part=\"value\"]::-moz-placeholder {\n color: var(--material-disabled-text-color);\n transition: opacity 0.175s 0.05s;\n opacity: 1;\n }\n\n [part=\"value\"]::placeholder {\n color: var(--material-disabled-text-color);\n transition: opacity 0.175s 0.1s;\n opacity: 1;\n }\n\n :host([has-label]:not([focused]):not([invalid]):not([theme=\"always-float-label\"])) [part=\"value\"]::-webkit-input-placeholder {\n opacity: 0;\n transition-delay: 0;\n }\n\n :host([has-label]:not([focused]):not([invalid]):not([theme=\"always-float-label\"])) [part=\"value\"]::-moz-placeholder {\n opacity: 0;\n transition-delay: 0;\n }\n\n :host([has-label]:not([focused]):not([invalid]):not([theme=\"always-float-label\"])) [part=\"value\"]::placeholder {\n opacity: 0;\n transition-delay: 0;\n }\n\n /* IE11 doesn\u2019t show the placeholder when the input is focused, so it\u2019s basically useless for this theme */\n :host([has-label]) [part=\"value\"]:-ms-input-placeholder {\n opacity: 0;\n }\n\n /* According to material theme guidelines, helper text should be hidden when error message is set and input is invalid */\n :host([has-helper][invalid][has-error-message]) [part=\"helper-text\"] {\n display: none;\n }\n\n [part=\"label\"] {\n width: 133%;\n transition: transform 0.175s, color 0.175s, width 0.175s;\n transition-timing-function: ease, ease, step-end;\n }\n\n :host([has-helper]) [part=\"helper-text\"]::before {\n content: \"\";\n display: block;\n height: 6px;\n }\n\n [part=\"helper-text\"],\n [part=\"helper-text\"] ::slotted(*) {\n font-size: .75rem;\n line-height: 1;\n color: var(--material-secondary-text-color);\n }\n\n /* TODO: using unsupported selector to fix IE11 (even thought the label element is scaled down,\n the 133% width still takes the same space as an unscaled element */\n ::-ms-backdrop,\n .vaadin-text-field-container {\n overflow: hidden;\n }\n\n /* Same fix for MS Edge ^^ */\n @supports (-ms-ime-align:auto) {\n .vaadin-text-field-container {\n overflow: hidden;\n }\n }\n\n :host(:hover:not([readonly]):not([invalid])) [part=\"input-field\"]::before {\n opacity: var(--_material-text-field-input-line-hover-opacity, 0.87);\n }\n\n :host([focused]:not([invalid])) [part=\"label\"] {\n color: var(--material-primary-text-color);\n }\n\n :host([focused]) [part=\"input-field\"]::after,\n :host([invalid]) [part=\"input-field\"]::after {\n opacity: 1;\n transform: none;\n transition: transform 0.175s, opacity 0.175s;\n }\n\n :host([invalid]) [part=\"input-field\"]::after {\n background-color: var(--material-error-color);\n }\n\n :host([input-prevented]) [part=\"input-field\"] {\n color: var(--material-error-text-color);\n }\n\n :host([disabled]) {\n pointer-events: none;\n }\n\n :host([disabled]) [part=\"input-field\"] {\n color: var(--material-disabled-text-color);\n }\n\n :host([disabled]) [part=\"input-field\"]::before {\n background-color: transparent;\n background-image: linear-gradient(90deg, var(--_material-text-field-input-line-background-color, #000) 0, var(--_material-text-field-input-line-background-color, #000) 2px, transparent 2px);\n background-size: 4px 1px;\n background-repeat: repeat-x;\n }\n\n /* Only target the visible floating label */\n :host([has-label]:not([has-value]):not([focused]):not([invalid]):not([theme~=\"always-float-label\"])) [part=\"label\"] {\n width: 100%;\n /* IE11 doesn\u2019t work with calc inside the translate function, so we need to have a fixed pixel value instead of 50% + 16px */\n transform: scale(1) translateY(24px);\n transition-timing-function: ease, ease, step-start;\n pointer-events: none;\n left: auto;\n right: auto;\n transition-delay: 0.1s;\n }\n\n /* Slotted content */\n\n [part=\"input-field\"] ::slotted(*:not([part=\"value\"]):not([part\\$=\"-button\"]):not(input):not(textarea)) {\n color: var(--material-secondary-text-color);\n }\n\n [part=\"clear-button\"]::before {\n content: var(--material-icons-clear);\n }\n\n /* RTL specific styles */\n\n :host([disabled][dir=\"rtl\"]) [part=\"input-field\"]::before {\n background-image: linear-gradient(-90deg, var(--_material-text-field-input-line-background-color, #000) 0, var(--_material-text-field-input-line-background-color, #000) 2px, transparent 2px);\n }\n </style>\n </template>\n</dom-module>"]))); document.head.appendChild($_documentContainer.content); });
let ModbusRequestBody = require('./request-body.js') /** Read Discrete Inputs Request Body * @extends ModbusRequestBody */ class ReadDiscreteInputsRequestBody extends ModbusRequestBody { static fromBuffer (buffer) { try { let fc = buffer.readUInt8(0) if (fc !== 0x02) { return null } let start = buffer.readUInt16BE(1) let quantity = buffer.readUInt16BE(3) return new ReadDiscreteInputsRequestBody(start, quantity) } catch (e) { return null } } /** Create a new Read Discrete Inputs Request Body. * @param {Number} start Start Address. * @param {Number} count Quantity of coils to be read. * @throws {InvalidStartAddressException} When Start address is larger than 0xFFFF. * @throws {InvalidQuantityException} When count is larger than 0x7D0. */ constructor (start, count) { super(0x02) if (start > 0xFFFF) { throw new Error('InvalidStartAddress') } if (count > 0x7D0) { throw new Error('InvalidQuantity') } this._start = start this._count = count } /** Start Address. */ get start () { return this._start } /** Coil Quantity. */ get count () { return this._count } get name () { return 'ReadDiscreteInput' } createPayload () { let payload = Buffer.alloc(5) payload.writeUInt8(this._fc, 0) // function code payload.writeUInt16BE(this._start, 1) // start address payload.writeUInt16BE(this._count, 3) // quantitiy of coils return payload } get byteCount () { return 5 } } module.exports = ReadDiscreteInputsRequestBody
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2019 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ var CONST = require('./const'); /** * Convert the given angle from degrees, to the equivalent angle in radians. * * @function Phaser.Math.DegToRad * @since 3.0.0 * * @param {integer} degrees - The angle (in degrees) to convert to radians. * * @return {number} The given angle converted to radians. */ var DegToRad = function (degrees) { return degrees * CONST.DEG_TO_RAD; }; module.exports = DegToRad;
export const ScheduleAction = { label: "ScheduleAction", description: `Scheduling future actions, events, or tasks. Related actions: * ReserveAction: Unlike ReserveAction, ScheduleAction allocates future actions (e.g. an event, a task, etc) towards a time slot / spatial allocation.`, _id: { viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], type: String, optional: true, }, createdAt: { viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], type: Date, optional: true, viewableBy: ["guests"], onInsert: (document, context) => { return new Date() }, }, userId: { viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], type: String, optional: true, resolveAs: { fieldName: "user", type: "User", resolver: (document, args, context) => { return context.Users.findOne( { _id: document.userId }, { fields: context.Users.getViewableFields( context.currentUser, context.Users ), } ) }, optional: true, }, }, identifierObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "identifierObject.$": { isbn: { label: "isbn", description: `The ISBN of the book.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, sku: { label: "sku", description: `The Stock Keeping Unit (SKU), i.e. a merchant-specific identifier for a product or service, or the product to which the offer refers.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, serialNumber: { label: "serialNumber", description: `The serial number or any alphanumeric identifier of a particular product. When attached to an offer, it is a shortcut for the serial number of the product included in the offer.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, orderNumber: { label: "orderNumber", description: `The identifier of the transaction.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, gtin8: { label: "gtin8", description: `The GTIN-8 code of the product, or the product to which the offer refers. This code is also known as EAN/UCC-8 or 8-digit EAN. See GS1 GTIN Summary for more details.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, flightNumber: { label: "flightNumber", description: `The unique identifier for a flight including the airline IATA code. For example, if describing United flight 110, where the IATA code for United is 'UA', the flightNumber is 'UA110'.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, globalLocationNumber: { label: "globalLocationNumber", description: `The Global Location Number (GLN, sometimes also referred to as International Location Number or ILN) of the respective organization, person, or place. The GLN is a 13-digit number used to identify parties and physical locations.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, confirmationNumber: { label: "confirmationNumber", description: `A number that confirms the given order or payment has been received.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, duns: { label: "duns", description: `The Dun & Bradstreet DUNS number for identifying an organization or business person.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, taxID: { label: "taxID", description: `The Tax / Fiscal ID of the organization or person, e.g. the TIN in the US or the CIF/NIF in Spain.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, issn: { label: "issn", description: `The International Standard Serial Number (ISSN) that identifies this serial publication. You can repeat this property to identify different formats of, or the linking ISSN (ISSN-L) for, this serial publication.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, leiCode: { label: "leiCode", description: `An organization identifier that uniquely identifies a legal entity as defined in ISO 17442.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, gtin14: { label: "gtin14", description: `The GTIN-14 code of the product, or the product to which the offer refers. See GS1 GTIN Summary for more details.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, gtin13: { label: "gtin13", description: `The GTIN-13 code of the product, or the product to which the offer refers. This is equivalent to 13-digit ISBN codes and EAN UCC-13. Former 12-digit UPC codes can be converted into a GTIN-13 code by simply adding a preceeding zero. See GS1 GTIN Summary for more details.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, gtin12: { label: "gtin12", description: `The GTIN-12 code of the product, or the product to which the offer refers. The GTIN-12 is the 12-digit GS1 Identification Key composed of a U.P.C. Company Prefix, Item Reference, and Check Digit used to identify trade items. See GS1 GTIN Summary for more details.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, productID: { label: "productID", description: `The product identifier, such as ISBN. For example: meta itemprop="productID" content="isbn:123-456-789".`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, accountId: { label: "accountId", description: `The identifier for the account the payment will be applied to.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, instrumentObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "instrumentObject.$": { query: { label: "query", description: `A sub property of instrument. The query used on this action.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, recipe: { label: "recipe", description: `A sub property of instrument. The recipe/instructions used to perform the action.`, resolveAs: { fieldName: "RecipeResolved", type: "Recipe", resolver: (document, args, context) => { return context.Recipe.findOne( { _id: document.Recipe }, { fields: context.Recipe.getViewableFields( context.currentUser, context.Recipe ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, deliveryMethod: { label: "deliveryMethod", description: `A sub property of instrument. The method of delivery.`, resolveAs: { fieldName: "DeliveryMethodResolved", type: "DeliveryMethod", resolver: (document, args, context) => { return context.DeliveryMethod.findOne( { _id: document.DeliveryMethod }, { fields: context.DeliveryMethod.getViewableFields( context.currentUser, context.DeliveryMethod ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, language: { label: "language", description: `A sub property of instrument. The language used on this action.`, resolveAs: { fieldName: "LanguageResolved", type: "Language", resolver: (document, args, context) => { return context.Language.findOne( { _id: document.Language }, { fields: context.Language.getViewableFields( context.currentUser, context.Language ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, supply: { label: "supply", description: `A sub-property of instrument. A supply consumed when performing instructions or a direction.`, resolveAs: { fieldName: "HowToSupplyResolved", type: "HowToSupply", resolver: (document, args, context) => { return context.HowToSupply.findOne( { _id: document.HowToSupply }, { fields: context.HowToSupply.getViewableFields( context.currentUser, context.HowToSupply ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, tool: { label: "tool", description: `A sub property of instrument. An object used (but not consumed) when performing instructions or a direction.`, resolveAs: { fieldName: "HowToToolResolved", type: "HowToTool", resolver: (document, args, context) => { return context.HowToTool.findOne( { _id: document.HowToTool }, { fields: context.HowToTool.getViewableFields( context.currentUser, context.HowToTool ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, sponsorObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "sponsorObject.$": { funder: { label: "funder", description: `A person or organization that supports (sponsors) something through some kind of financial contribution.`, resolveAs: { fieldName: "PersonResolved", type: "Person", resolver: (document, args, context) => { return context.Person.findOne( { _id: document.Person }, { fields: context.Person.getViewableFields( context.currentUser, context.Person ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, yieldObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "yieldObject.$": { recipeYield: { label: "recipeYield", description: `The quantity produced by the recipe (for example, number of people served, number of servings, etc).`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, participantObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "participantObject.$": { buyer: { label: "buyer", description: `A sub property of participant. The participant/person/organization that bought the object.`, resolveAs: { fieldName: "PersonResolved", type: "Person", resolver: (document, args, context) => { return context.Person.findOne( { _id: document.Person }, { fields: context.Person.getViewableFields( context.currentUser, context.Person ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, landlord: { label: "landlord", description: `A sub property of participant. The owner of the real estate property.`, resolveAs: { fieldName: "PersonResolved", type: "Person", resolver: (document, args, context) => { return context.Person.findOne( { _id: document.Person }, { fields: context.Person.getViewableFields( context.currentUser, context.Person ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, loser: { label: "loser", description: `A sub property of participant. The loser of the action.`, resolveAs: { fieldName: "PersonResolved", type: "Person", resolver: (document, args, context) => { return context.Person.findOne( { _id: document.Person }, { fields: context.Person.getViewableFields( context.currentUser, context.Person ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, sportsTeam: { label: "sportsTeam", description: `A sub property of participant. The sports team that participated on this action.`, resolveAs: { fieldName: "SportsTeamResolved", type: "SportsTeam", resolver: (document, args, context) => { return context.SportsTeam.findOne( { _id: document.SportsTeam }, { fields: context.SportsTeam.getViewableFields( context.currentUser, context.SportsTeam ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, opponent: { label: "opponent", description: `A sub property of participant. The opponent on this action.`, resolveAs: { fieldName: "PersonResolved", type: "Person", resolver: (document, args, context) => { return context.Person.findOne( { _id: document.Person }, { fields: context.Person.getViewableFields( context.currentUser, context.Person ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, vendor: { label: "vendor", description: `'vendor' is an earlier term for 'seller'.`, resolveAs: { fieldName: "OrganizationResolved", type: "Organization", resolver: (document, args, context) => { return context.Organization.findOne( { _id: document.Organization }, { fields: context.Organization.getViewableFields( context.currentUser, context.Organization ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, winner: { label: "winner", description: `A sub property of participant. The winner of the action.`, resolveAs: { fieldName: "PersonResolved", type: "Person", resolver: (document, args, context) => { return context.Person.findOne( { _id: document.Person }, { fields: context.Person.getViewableFields( context.currentUser, context.Person ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, recipient: { label: "recipient", description: `A sub property of participant. The participant who is at the receiving end of the action.`, resolveAs: { fieldName: "ContactPointResolved", type: "ContactPoint", resolver: (document, args, context) => { return context.ContactPoint.findOne( { _id: document.ContactPoint }, { fields: context.ContactPoint.getViewableFields( context.currentUser, context.ContactPoint ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, realEstateAgent: { label: "realEstateAgent", description: `A sub property of participant. The real estate agent involved in the action.`, resolveAs: { fieldName: "RealEstateAgentResolved", type: "RealEstateAgent", resolver: (document, args, context) => { return context.RealEstateAgent.findOne( { _id: document.RealEstateAgent }, { fields: context.RealEstateAgent.getViewableFields( context.currentUser, context.RealEstateAgent ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, endorsee: { label: "endorsee", description: `A sub property of participant. The person/organization being supported.`, resolveAs: { fieldName: "PersonResolved", type: "Person", resolver: (document, args, context) => { return context.Person.findOne( { _id: document.Person }, { fields: context.Person.getViewableFields( context.currentUser, context.Person ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, sender: { label: "sender", description: `A sub property of participant. The participant who is at the sending end of the action.`, resolveAs: { fieldName: "OrganizationResolved", type: "Organization", resolver: (document, args, context) => { return context.Organization.findOne( { _id: document.Organization }, { fields: context.Organization.getViewableFields( context.currentUser, context.Organization ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, seller: { label: "seller", description: `An entity which offers (sells / leases / lends / loans) the services / goods. A seller may also be a provider.`, resolveAs: { fieldName: "OrganizationResolved", type: "Organization", resolver: (document, args, context) => { return context.Organization.findOne( { _id: document.Organization }, { fields: context.Organization.getViewableFields( context.currentUser, context.Organization ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, lender: { label: "lender", description: `A sub property of participant. The person that lends the object being borrowed.`, resolveAs: { fieldName: "PersonResolved", type: "Person", resolver: (document, args, context) => { return context.Person.findOne( { _id: document.Person }, { fields: context.Person.getViewableFields( context.currentUser, context.Person ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, borrower: { label: "borrower", description: `A sub property of participant. The person that borrows the object being lent.`, resolveAs: { fieldName: "PersonResolved", type: "Person", resolver: (document, args, context) => { return context.Person.findOne( { _id: document.Person }, { fields: context.Person.getViewableFields( context.currentUser, context.Person ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, competitorObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "competitorObject.$": { awayTeam: { label: "awayTeam", description: `The away team in a sports event.`, resolveAs: { fieldName: "SportsTeamResolved", type: "SportsTeam", resolver: (document, args, context) => { return context.SportsTeam.findOne( { _id: document.SportsTeam }, { fields: context.SportsTeam.getViewableFields( context.currentUser, context.SportsTeam ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, homeTeam: { label: "homeTeam", description: `The home team in a sports event.`, resolveAs: { fieldName: "PersonResolved", type: "Person", resolver: (document, args, context) => { return context.Person.findOne( { _id: document.Person }, { fields: context.Person.getViewableFields( context.currentUser, context.Person ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, objectObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "objectObject.$": { actionOption: { label: "actionOption", description: `A sub property of object. The options subject to this action.`, resolveAs: { fieldName: "ThingResolved", type: "Thing", resolver: (document, args, context) => { return context.Thing.findOne( { _id: document.Thing }, { fields: context.Thing.getViewableFields( context.currentUser, context.Thing ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, option: { label: "option", description: `A sub property of object. The options subject to this action.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, followee: { label: "followee", description: `A sub property of object. The person or organization being followed.`, resolveAs: { fieldName: "PersonResolved", type: "Person", resolver: (document, args, context) => { return context.Person.findOne( { _id: document.Person }, { fields: context.Person.getViewableFields( context.currentUser, context.Person ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, replacee: { label: "replacee", description: `A sub property of object. The object that is being replaced.`, resolveAs: { fieldName: "ThingResolved", type: "Thing", resolver: (document, args, context) => { return context.Thing.findOne( { _id: document.Thing }, { fields: context.Thing.getViewableFields( context.currentUser, context.Thing ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, replacer: { label: "replacer", description: `A sub property of object. The object that replaces.`, resolveAs: { fieldName: "ThingResolved", type: "Thing", resolver: (document, args, context) => { return context.Thing.findOne( { _id: document.Thing }, { fields: context.Thing.getViewableFields( context.currentUser, context.Thing ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, question: { label: "question", description: `A sub property of object. A question.`, resolveAs: { fieldName: "QuestionResolved", type: "Question", resolver: (document, args, context) => { return context.Question.findOne( { _id: document.Question }, { fields: context.Question.getViewableFields( context.currentUser, context.Question ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, collection: { label: "collection", description: `A sub property of object. The collection target of the action.`, resolveAs: { fieldName: "ThingResolved", type: "Thing", resolver: (document, args, context) => { return context.Thing.findOne( { _id: document.Thing }, { fields: context.Thing.getViewableFields( context.currentUser, context.Thing ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, targetCollection: { label: "targetCollection", description: `A sub property of object. The collection target of the action.`, resolveAs: { fieldName: "ThingResolved", type: "Thing", resolver: (document, args, context) => { return context.Thing.findOne( { _id: document.Thing }, { fields: context.Thing.getViewableFields( context.currentUser, context.Thing ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, candidate: { label: "candidate", description: `A sub property of object. The candidate subject of this action.`, resolveAs: { fieldName: "PersonResolved", type: "Person", resolver: (document, args, context) => { return context.Person.findOne( { _id: document.Person }, { fields: context.Person.getViewableFields( context.currentUser, context.Person ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, locationObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "locationObject.$": { workLocation: { label: "workLocation", description: `A contact location for a person's place of work.`, resolveAs: { fieldName: "ContactPointResolved", type: "ContactPoint", resolver: (document, args, context) => { return context.ContactPoint.findOne( { _id: document.ContactPoint }, { fields: context.ContactPoint.getViewableFields( context.currentUser, context.ContactPoint ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, course: { label: "course", description: `A sub property of location. The course where this action was taken.`, resolveAs: { fieldName: "PlaceResolved", type: "Place", resolver: (document, args, context) => { return context.Place.findOne( { _id: document.Place }, { fields: context.Place.getViewableFields( context.currentUser, context.Place ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, homeLocation: { label: "homeLocation", description: `A contact location for a person's residence.`, resolveAs: { fieldName: "ContactPointResolved", type: "ContactPoint", resolver: (document, args, context) => { return context.ContactPoint.findOne( { _id: document.ContactPoint }, { fields: context.ContactPoint.getViewableFields( context.currentUser, context.ContactPoint ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, sportsEvent: { label: "sportsEvent", description: `A sub property of location. The sports event where this action occurred.`, resolveAs: { fieldName: "SportsEventResolved", type: "SportsEvent", resolver: (document, args, context) => { return context.SportsEvent.findOne( { _id: document.SportsEvent }, { fields: context.SportsEvent.getViewableFields( context.currentUser, context.SportsEvent ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, sportsActivityLocation: { label: "sportsActivityLocation", description: `A sub property of location. The sports activity location where this action occurred.`, resolveAs: { fieldName: "SportsActivityLocationResolved", type: "SportsActivityLocation", resolver: (document, args, context) => { return context.SportsActivityLocation.findOne( { _id: document.SportsActivityLocation }, { fields: context.SportsActivityLocation.getViewableFields( context.currentUser, context.SportsActivityLocation ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, foodEvent: { label: "foodEvent", description: `A sub property of location. The specific food event where the action occurred.`, resolveAs: { fieldName: "FoodEventResolved", type: "FoodEvent", resolver: (document, args, context) => { return context.FoodEvent.findOne( { _id: document.FoodEvent }, { fields: context.FoodEvent.getViewableFields( context.currentUser, context.FoodEvent ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, toLocation: { label: "toLocation", description: `A sub property of location. The final location of the object or the agent after the action.`, resolveAs: { fieldName: "PlaceResolved", type: "Place", resolver: (document, args, context) => { return context.Place.findOne( { _id: document.Place }, { fields: context.Place.getViewableFields( context.currentUser, context.Place ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, fromLocation: { label: "fromLocation", description: `A sub property of location. The original location of the object or the agent before the action.`, resolveAs: { fieldName: "PlaceResolved", type: "Place", resolver: (document, args, context) => { return context.Place.findOne( { _id: document.Place }, { fields: context.Place.getViewableFields( context.currentUser, context.Place ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, foodEstablishment: { label: "foodEstablishment", description: `A sub property of location. The specific food establishment where the action occurred.`, resolveAs: { fieldName: "PlaceResolved", type: "Place", resolver: (document, args, context) => { return context.Place.findOne( { _id: document.Place }, { fields: context.Place.getViewableFields( context.currentUser, context.Place ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, entertainmentBusiness: { label: "entertainmentBusiness", description: `A sub property of location. The entertainment business where the action occurred.`, resolveAs: { fieldName: "EntertainmentBusinessResolved", type: "EntertainmentBusiness", resolver: (document, args, context) => { return context.EntertainmentBusiness.findOne( { _id: document.EntertainmentBusiness }, { fields: context.EntertainmentBusiness.getViewableFields( context.currentUser, context.EntertainmentBusiness ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, exerciseCourse: { label: "exerciseCourse", description: `A sub property of location. The course where this action was taken.`, resolveAs: { fieldName: "PlaceResolved", type: "Place", resolver: (document, args, context) => { return context.Place.findOne( { _id: document.Place }, { fields: context.Place.getViewableFields( context.currentUser, context.Place ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, durationObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "durationObject.$": { loanTerm: { label: "loanTerm", description: `The duration of the loan or credit agreement.`, resolveAs: { fieldName: "QuantitativeValueResolved", type: "QuantitativeValue", resolver: (document, args, context) => { return context.QuantitativeValue.findOne( { _id: document.QuantitativeValue }, { fields: context.QuantitativeValue.getViewableFields( context.currentUser, context.QuantitativeValue ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, hasPartObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "hasPartObject.$": { season: { label: "season", description: `A season in a media series.`, resolveAs: { fieldName: "CreativeWorkSeasonResolved", type: "CreativeWorkSeason", resolver: (document, args, context) => { return context.CreativeWorkSeason.findOne( { _id: document.CreativeWorkSeason }, { fields: context.CreativeWorkSeason.getViewableFields( context.currentUser, context.CreativeWorkSeason ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, containsSeason: { label: "containsSeason", description: `A season that is part of the media series.`, resolveAs: { fieldName: "CreativeWorkSeasonResolved", type: "CreativeWorkSeason", resolver: (document, args, context) => { return context.CreativeWorkSeason.findOne( { _id: document.CreativeWorkSeason }, { fields: context.CreativeWorkSeason.getViewableFields( context.currentUser, context.CreativeWorkSeason ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, episode: { label: "episode", description: `An episode of a tv, radio or game media within a series or season.`, resolveAs: { fieldName: "EpisodeResolved", type: "Episode", resolver: (document, args, context) => { return context.Episode.findOne( { _id: document.Episode }, { fields: context.Episode.getViewableFields( context.currentUser, context.Episode ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, materialObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "materialObject.$": { artMedium: { label: "artMedium", description: `The material used. (e.g. Oil, Watercolour, Acrylic, Linoprint, Marble, Cyanotype, Digital, Lithograph, DryPoint, Intaglio, Pastel, Woodcut, Pencil, Mixed Media, etc.)`, type: String, input: "url", viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, surface: { label: "surface", description: `A material used as a surface in some artwork, e.g. Canvas, Paper, Wood, Board, etc.`, type: String, input: "url", viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, isPartOfObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "isPartOfObject.$": { partOfEpisode: { label: "partOfEpisode", description: `The episode to which this clip belongs.`, resolveAs: { fieldName: "EpisodeResolved", type: "Episode", resolver: (document, args, context) => { return context.Episode.findOne( { _id: document.Episode }, { fields: context.Episode.getViewableFields( context.currentUser, context.Episode ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, partOfSeries: { label: "partOfSeries", description: `The series to which this episode or season belongs.`, resolveAs: { fieldName: "CreativeWorkSeriesResolved", type: "CreativeWorkSeries", resolver: (document, args, context) => { return context.CreativeWorkSeries.findOne( { _id: document.CreativeWorkSeries }, { fields: context.CreativeWorkSeries.getViewableFields( context.currentUser, context.CreativeWorkSeries ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, partOfTVSeries: { label: "partOfTVSeries", description: `The TV series to which this episode or season belongs.`, resolveAs: { fieldName: "TVSeriesResolved", type: "TVSeries", resolver: (document, args, context) => { return context.TVSeries.findOne( { _id: document.TVSeries }, { fields: context.TVSeries.getViewableFields( context.currentUser, context.TVSeries ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, partOfSeason: { label: "partOfSeason", description: `The season to which this episode belongs.`, resolveAs: { fieldName: "CreativeWorkSeasonResolved", type: "CreativeWorkSeason", resolver: (document, args, context) => { return context.CreativeWorkSeason.findOne( { _id: document.CreativeWorkSeason }, { fields: context.CreativeWorkSeason.getViewableFields( context.currentUser, context.CreativeWorkSeason ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, imageObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "imageObject.$": { photo: { label: "photo", description: `A photograph of this place.`, resolveAs: { fieldName: "ImageObjectResolved", type: "ImageObject", resolver: (document, args, context) => { return context.ImageObject.findOne( { _id: document.ImageObject }, { fields: context.ImageObject.getViewableFields( context.currentUser, context.ImageObject ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, logo: { label: "logo", description: `An associated logo.`, type: String, input: "url", viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, "rdf:typeObject": { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "rdf:typeObject.$": { additionalType: { label: "additionalType", description: `An additional type for the item, typically used for adding more specific types from external vocabularies in microdata syntax. This is a relationship between something and a class that the thing is in. In RDFa syntax, it is better to use the native RDFa syntax - the 'typeof' attribute - for multiple types. Schema.org tools may have only weaker understanding of extra types, in particular those defined externally.`, type: String, input: "url", viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, "rdfs:labelObject": { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "rdfs:labelObject.$": { name: { label: "name", description: `The name of the item.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, resultObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "resultObject.$": { resultReview: { label: "resultReview", description: `A sub property of result. The review that resulted in the performing of the action.`, resolveAs: { fieldName: "ReviewResolved", type: "Review", resolver: (document, args, context) => { return context.Review.findOne( { _id: document.Review }, { fields: context.Review.getViewableFields( context.currentUser, context.Review ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, resultComment: { label: "resultComment", description: `A sub property of result. The Comment created or sent as a result of this action.`, resolveAs: { fieldName: "CommentResolved", type: "Comment", resolver: (document, args, context) => { return context.Comment.findOne( { _id: document.Comment }, { fields: context.Comment.getViewableFields( context.currentUser, context.Comment ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, recipientObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "recipientObject.$": { bccRecipient: { label: "bccRecipient", description: `A sub property of recipient. The recipient blind copied on a message.`, resolveAs: { fieldName: "PersonResolved", type: "Person", resolver: (document, args, context) => { return context.Person.findOne( { _id: document.Person }, { fields: context.Person.getViewableFields( context.currentUser, context.Person ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, ccRecipient: { label: "ccRecipient", description: `A sub property of recipient. The recipient copied on a message.`, resolveAs: { fieldName: "ContactPointResolved", type: "ContactPoint", resolver: (document, args, context) => { return context.ContactPoint.findOne( { _id: document.ContactPoint }, { fields: context.ContactPoint.getViewableFields( context.currentUser, context.ContactPoint ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, toRecipient: { label: "toRecipient", description: `A sub property of recipient. The recipient who was directly sent the message.`, resolveAs: { fieldName: "OrganizationResolved", type: "Organization", resolver: (document, args, context) => { return context.Organization.findOne( { _id: document.Organization }, { fields: context.Organization.getViewableFields( context.currentUser, context.Organization ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, serialNumberObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "serialNumberObject.$": { vehicleIdentificationNumber: { label: "vehicleIdentificationNumber", description: `The Vehicle Identification Number (VIN) is a unique serial number used by the automotive industry to identify individual motor vehicles.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, supplyObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "supplyObject.$": { recipeIngredient: { label: "recipeIngredient", description: `A single ingredient used in the recipe, e.g. sugar, flour or garlic.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, ingredients: { label: "ingredients", description: `A single ingredient used in the recipe, e.g. sugar, flour or garlic.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, stepObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "stepObject.$": { recipeInstructions: { label: "recipeInstructions", description: `A step in making the recipe, in the form of a single item (document, video, etc.) or an ordered list with HowToStep and/or HowToSection items.`, resolveAs: { fieldName: "ItemListResolved", type: "ItemList", resolver: (document, args, context) => { return context.ItemList.findOne( { _id: document.ItemList }, { fields: context.ItemList.getViewableFields( context.currentUser, context.ItemList ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, areaServedObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "areaServedObject.$": { availableAtOrFrom: { label: "availableAtOrFrom", description: `The place(s) from which the offer can be obtained (e.g. store locations).`, resolveAs: { fieldName: "PlaceResolved", type: "Place", resolver: (document, args, context) => { return context.Place.findOne( { _id: document.Place }, { fields: context.Place.getViewableFields( context.currentUser, context.Place ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, eligibleRegion: { label: "eligibleRegion", description: `The ISO 3166-1 (ISO 3166-1 alpha-2) or ISO 3166-2 code, the place, or the GeoShape for the geo-political region(s) for which the offer or delivery charge specification is valid. See also ineligibleRegion.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, contentLocationObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "contentLocationObject.$": { spatialCoverage: { label: "spatialCoverage", description: `The spatialCoverage of a CreativeWork indicates the place(s) which are the focus of the content. It is a subproperty of contentLocation intended primarily for more technical and detailed materials. For example with a Dataset, it indicates areas that the dataset describes: a dataset of New York weather would have spatialCoverage which was the place: the state of New York.`, resolveAs: { fieldName: "PlaceResolved", type: "Place", resolver: (document, args, context) => { return context.Place.findOne( { _id: document.Place }, { fields: context.Place.getViewableFields( context.currentUser, context.Place ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, positionObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "positionObject.$": { issueNumber: { label: "issueNumber", description: `Identifies the issue of publication; for example, "iii" or "2".`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, episodeNumber: { label: "episodeNumber", description: `Position of the episode within an ordered group of episodes.`, resolveAs: { fieldName: "IntegerResolved", type: "Integer", resolver: (document, args, context) => { return context.Integer.findOne( { _id: document.Integer }, { fields: context.Integer.getViewableFields( context.currentUser, context.Integer ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, volumeNumber: { label: "volumeNumber", description: `Identifies the volume of publication or multi-part work; for example, "iii" or "2".`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, seasonNumber: { label: "seasonNumber", description: `Position of the season within an ordered group of seasons.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, clipNumber: { label: "clipNumber", description: `Position of the clip within an ordered group of clips.`, resolveAs: { fieldName: "IntegerResolved", type: "Integer", resolver: (document, args, context) => { return context.Integer.findOne( { _id: document.Integer }, { fields: context.Integer.getViewableFields( context.currentUser, context.Integer ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, workFeaturedObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "workFeaturedObject.$": { workPerformed: { label: "workPerformed", description: `A work performed in some event, for example a play performed in a TheaterEvent.`, resolveAs: { fieldName: "CreativeWorkResolved", type: "CreativeWork", resolver: (document, args, context) => { return context.CreativeWork.findOne( { _id: document.CreativeWork }, { fields: context.CreativeWork.getViewableFields( context.currentUser, context.CreativeWork ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, workPresented: { label: "workPresented", description: `The movie presented during this event.`, resolveAs: { fieldName: "MovieResolved", type: "Movie", resolver: (document, args, context) => { return context.Movie.findOne( { _id: document.Movie }, { fields: context.Movie.getViewableFields( context.currentUser, context.Movie ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, suggestedAnswerObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "suggestedAnswerObject.$": { acceptedAnswer: { label: "acceptedAnswer", description: `The answer(s) that has been accepted as best, typically on a Question/Answer site. Sites vary in their selection mechanisms, e.g. drawing on community opinion and/or the view of the Question author.`, resolveAs: { fieldName: "ItemListResolved", type: "ItemList", resolver: (document, args, context) => { return context.ItemList.findOne( { _id: document.ItemList }, { fields: context.ItemList.getViewableFields( context.currentUser, context.ItemList ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, aboutObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "aboutObject.$": { mainEntity: { label: "mainEntity", description: `Indicates the primary entity described in some page or other CreativeWork.`, resolveAs: { fieldName: "ThingResolved", type: "Thing", resolver: (document, args, context) => { return context.Thing.findOne( { _id: document.Thing }, { fields: context.Thing.getViewableFields( context.currentUser, context.Thing ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, performTimeObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "performTimeObject.$": { cookTime: { label: "cookTime", description: `The time it takes to actually cook the dish, in ISO 8601 duration format.`, resolveAs: { fieldName: "DurationResolved", type: "Duration", resolver: (document, args, context) => { return context.Duration.findOne( { _id: document.Duration }, { fields: context.Duration.getViewableFields( context.currentUser, context.Duration ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, descriptionObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "descriptionObject.$": { disambiguatingDescription: { label: "disambiguatingDescription", description: `A sub property of description. A short description of the item used to disambiguate from other, similar items. Information from other properties (in particular, name) may be necessary for the description to be useful for disambiguation.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, memberOfObject: { label: "", description: ``, type: Object, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, "memberOfObject.$": { affiliation: { label: "affiliation", description: `An organization that this person is affiliated with. For example, a school/university, a club, or a team.`, resolveAs: { fieldName: "OrganizationResolved", type: "Organization", resolver: (document, args, context) => { return context.Organization.findOne( { _id: document.Organization }, { fields: context.Organization.getViewableFields( context.currentUser, context.Organization ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, }, scheduledTime: { label: "scheduledTime", description: `The time the object is scheduled to.`, type: Date, input: "datetime", viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, result: { label: "result", description: `The result produced in the action. e.g. John wrote a book.`, resolveAs: { fieldName: "ThingResolved", type: "Thing", resolver: (document, args, context) => { return context.Thing.findOne( { _id: document.Thing }, { fields: context.Thing.getViewableFields( context.currentUser, context.Thing ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, startTime: { label: "startTime", description: `The startTime of something. For a reserved event or service (e.g. FoodEstablishmentReservation), the time that it is expected to start. For actions that span a period of time, when the action was performed. e.g. John wrote a book from January to December. Note that Event uses startDate/endDate instead of startTime/endTime, even when describing dates with times. This situation may be clarified in future revisions.`, type: Date, input: "datetime", viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, actionStatus: { label: "actionStatus", description: `Indicates the current disposition of the Action.`, resolveAs: { fieldName: "ActionStatusTypeResolved", type: "ActionStatusType", resolver: (document, args, context) => { return context.ActionStatusType.findOne( { _id: document.ActionStatusType }, { fields: context.ActionStatusType.getViewableFields( context.currentUser, context.ActionStatusType ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, target: { label: "target", description: `Indicates a target EntryPoint for an Action.`, resolveAs: { fieldName: "EntryPointResolved", type: "EntryPoint", resolver: (document, args, context) => { return context.EntryPoint.findOne( { _id: document.EntryPoint }, { fields: context.EntryPoint.getViewableFields( context.currentUser, context.EntryPoint ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, agent: { label: "agent", description: `The direct performer or driver of the action (animate or inanimate). e.g. John wrote a book.`, resolveAs: { fieldName: "PersonResolved", type: "Person", resolver: (document, args, context) => { return context.Person.findOne( { _id: document.Person }, { fields: context.Person.getViewableFields( context.currentUser, context.Person ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, endTime: { label: "endTime", description: `The endTime of something. For a reserved event or service (e.g. FoodEstablishmentReservation), the time that it is expected to end. For actions that span a period of time, when the action was performed. e.g. John wrote a book from January to December. Note that Event uses startDate/endDate instead of startTime/endTime, even when describing dates with times. This situation may be clarified in future revisions.`, type: Date, input: "datetime", viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, participant: { label: "participant", description: `Other co-agents that participated in the action indirectly. e.g. John wrote a book with Steve.`, resolveAs: { fieldName: "OrganizationResolved", type: "Organization", resolver: (document, args, context) => { return context.Organization.findOne( { _id: document.Organization }, { fields: context.Organization.getViewableFields( context.currentUser, context.Organization ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, instrument: { label: "instrument", description: `The object that helped the agent perform the action. e.g. John wrote a book with a pen.`, resolveAs: { fieldName: "ThingResolved", type: "Thing", resolver: (document, args, context) => { return context.Thing.findOne( { _id: document.Thing }, { fields: context.Thing.getViewableFields( context.currentUser, context.Thing ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, object: { label: "object", description: `The object upon which the action is carried out, whose state is kept intact or changed. Also known as the semantic roles patient, affected or undergoer (which change their state) or theme (which doesn't). e.g. John read a book.`, resolveAs: { fieldName: "ThingResolved", type: "Thing", resolver: (document, args, context) => { return context.Thing.findOne( { _id: document.Thing }, { fields: context.Thing.getViewableFields( context.currentUser, context.Thing ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, error: { label: "error", description: `For failed actions, more information on the cause of the failure.`, resolveAs: { fieldName: "ThingResolved", type: "Thing", resolver: (document, args, context) => { return context.Thing.findOne( { _id: document.Thing }, { fields: context.Thing.getViewableFields( context.currentUser, context.Thing ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, location: { label: "location", description: `The location of for example where the event is happening, an organization is located, or where an action takes place.`, resolveAs: { fieldName: "PostalAddressResolved", type: "PostalAddress", resolver: (document, args, context) => { return context.PostalAddress.findOne( { _id: document.PostalAddress }, { fields: context.PostalAddress.getViewableFields( context.currentUser, context.PostalAddress ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, sameAs: { label: "sameAs", description: `URL of a reference Web page that unambiguously indicates the item's identity. E.g. the URL of the item's Wikipedia page, Wikidata entry, or official website.`, type: String, input: "url", viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, alternateName: { label: "alternateName", description: `An alias for the item.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, image: { label: "image", description: `An image of the item. This can be a URL or a fully described ImageObject.`, resolveAs: { fieldName: "ImageObjectResolved", type: "ImageObject", resolver: (document, args, context) => { return context.ImageObject.findOne( { _id: document.ImageObject }, { fields: context.ImageObject.getViewableFields( context.currentUser, context.ImageObject ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, identifier: { label: "identifier", description: `The identifier property represents any kind of identifier for any kind of Thing, such as ISBNs, GTIN codes, UUIDs etc. Schema.org provides dedicated properties for representing many of these, either as textual strings or as URL (URI) links. See background notes for more details.`, type: String, input: "url", viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, mainEntityOfPage: { label: "mainEntityOfPage", description: `Indicates a page (or other CreativeWork) for which this thing is the main entity being described. See background notes for details.`, type: String, input: "url", viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, url: { label: "url", description: `URL of the item.`, type: String, input: "url", viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, potentialAction: { label: "potentialAction", description: `Indicates a potential Action, which describes an idealized action in which this thing would play an 'object' role.`, resolveAs: { fieldName: "ActionResolved", type: "Action", resolver: (document, args, context) => { return context.Action.findOne( { _id: document.Action }, { fields: context.Action.getViewableFields( context.currentUser, context.Action ), } ) }, optional: true, }, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, description: { label: "description", description: `A description of the item.`, type: String, viewableBy: ["guests"], editableBy: ["members"], insertableBy: ["members"], }, } export default ScheduleAction
/** * @module connection-pool-party */ import debug from 'debug'; import ConnectionPoolParty from './connection-pool-party'; import defaultConnectionPoolFactory from './default-connection-pool-factory'; import forceFqdnConnectionPoolFactory from './force-fqdn-connection-pool-factory'; // Send all debug() logs to stdout instead of stderr /* eslint no-console:0 */ debug.log = console.log.bind(console); // export everything from mssql since we aren't overwriting the existing interface export * from 'mssql'; export { ConnectionPoolParty, defaultConnectionPoolFactory, forceFqdnConnectionPoolFactory, };
/** * Auto-generated action file for "Microsoft Graph API" API. * * Generated at: 2019-08-07T14:53:12.583Z * Mass generator version: 1.1.0 * * flowground :- Telekom iPaaS / microsoft-graph-api-connector * Copyright © 2019, Deutsche Telekom AG * contact: flowground@telekom.de * * All files of this connector are licensed under the Apache 2.0 License. For details * see the file LICENSE on the toplevel directory. * * * Operation: 'workbooks.driveItem.unprotect' * Endpoint Path: '/workbooks/{driveItem-id}/workbook/names/{workbookNamedItem-id}/worksheet/protection/unprotect' * Method: 'post' * */ const Swagger = require('swagger-client'); const processWrapper = require('../services/process-wrapper'); const spec = require('../spec.json'); // this wrapers offers a simplified emitData(data) function module.exports.process = processWrapper(processAction); // parameter names for this call const PARAMETERS = [ "driveItem-id", "workbookNamedItem-id" ]; // mappings from connector field names to API field names const FIELD_MAP = { "driveItem_id": "driveItem-id", "workbookNamedItem_id": "workbookNamedItem-id" }; function processAction(msg, cfg) { var isVerbose = process.env.debug || cfg.verbose; if (isVerbose) { console.log(`---MSG: ${JSON.stringify(msg)}`); console.log(`---CFG: ${JSON.stringify(cfg)}`); console.log(`---ENV: ${JSON.stringify(process.env)}`); } const contentType = undefined; const body = msg.body; mapFieldNames(body); let parameters = {}; for(let param of PARAMETERS) { parameters[param] = body[param]; } // credentials for this operation let securities = {}; let callParams = { spec: spec, operationId: 'workbooks.driveItem.unprotect', pathName: '/workbooks/{driveItem-id}/workbook/names/{workbookNamedItem-id}/worksheet/protection/unprotect', method: 'post', parameters: parameters, requestContentType: contentType, requestBody: body.requestBody, securities: {authorized: securities}, server: spec.servers[cfg.server] || cfg.otherServer, }; if (isVerbose) { let out = Object.assign({}, callParams); out.spec = '[omitted]'; console.log(`--SWAGGER CALL: ${JSON.stringify(out)}`); } // Call operation via Swagger client return Swagger.execute(callParams).then(data => { // emit a single message with data this.emitData(data); // if the response contains an array of entities, you can emit them one by one: // data.obj.someItems.forEach((item) => { // this.emitData(item); // } }); } function mapFieldNames(obj) { if(Array.isArray(obj)) { obj.forEach(mapFieldNames); } else if(typeof obj === 'object' && obj) { Object.keys(obj).forEach(key => { mapFieldNames(obj[key]); let goodKey = FIELD_MAP[key]; if(goodKey && goodKey !== key) { obj[goodKey] = obj[key]; delete obj[key]; } }); } }
module.exports = { presets: ["next/babel"], plugins: [["styled-components", { ssr: true }], "inline-react-svg"], };
import React from 'react' import styled, {keyframes} from 'styled-components' const lightshow = keyframes` 0% { color: #fb8a8b; } 16% { color: #f76272; } 32% { color: #e10079; } 48% { color: #e10079; } 64% { color: #a231ef; } 80% { color: #15216b; } 100% { color: #fb8a8b } ` export const Char = styled.span` animation: ${lightshow} ease-in-out ${({time = 0.85}) => time}s infinite backwards ${({delay = 0}) => delay}s; ` export const CharContainer = styled.div` background: var(--theme-surface); box-shadow: 0 0 0 1rem var(--theme-surface); ` const RainbowText = props => { const chars = props.text.split('') const time = 1 const {length} = chars const style = props.style return ( <React.Fragment> <CharContainer style={style}> {chars.map((char, i) => { const delay = (props.time / length) * (length - i) * -1 return ( <Char key={i} time={props.time} delay={delay}> {char} </Char> ) })} </CharContainer> </React.Fragment> ) } RainbowText.defaultProps = { time: 0.85 } export default RainbowText
//Userデータを管理 var Preferences = require("preferences");//データ保存 var DOMAIN = 'jp.ac.aitech.maslab'; module.exports.getAccount = function(){ var prefs = new Preferences(DOMAIN); return prefs; } module.exports.isLogin = function(){ var prefs = new Preferences(DOMAIN); return prefs.login; } module.exports.setUserData = function(data){ var prefs = new Preferences(DOMAIN); prefs.account = {}; prefs.account.username = data["username"]; prefs.account.password = data["password"]; return prefs; } module.exports.getDomain = function(){ return DOMAIN; }
import { combineReducers } from 'redux'; import keplerGlReducer from 'kepler.gl/reducers'; import { REQUEST_PARKING_DATA, GET_PARKING_DATA, SET_MAP_MODE } from './actions'; import { MAP_MODE } from '../configs/map'; const isLoadingReducer = function ( state = false, action) { switch (action.type) { case REQUEST_PARKING_DATA: return true; case GET_PARKING_DATA: return false; default: return state; } }; const mapModeReducer = function ( state = MAP_MODE.POINTS, action ) { if (action.type === SET_MAP_MODE) { return action.mapMode; } return state; }; const appReducer = combineReducers({ mapMode: mapModeReducer, isLoading: isLoadingReducer }); const mapReducer = keplerGlReducer .initialState({ uiState: { readOnly: true, mapControls: { visibleLayers: { show: false }, toggle3d: { show: false }, splitMap: { show: true }, mapLegend: { show: true, active: false } } } }) const reducers = combineReducers({ keplerGl: mapReducer, app: appReducer, }); export default reducers;
$(document).ready(function() { listenRemoveStudent(); $("#student_autocomplete").on('input', function() { const name = $(this).val(); if (name.length > 2) { refreshStudents(name); } else { $('#student_autocomplete_matches').hide(); } }); $('#formSubmit').on('click', function(event) { event.preventDefault(); getSelectedStudentsIds().map(id => $(this).append(`<input name="users[]" type="hidden" value=${id}>`)) $("#form").submit(); }); function refreshStudents(name) { $.ajax({ url: `/student/autocomplete?name=${name}`, success: function(students) { let html = ""; students.map(student => { html += `<div class="autocomplete_student" data-id=${student.id}> <span>${student.first_name} ${student.last_name}</span> <span class="autocomplete_select">+</span> </div>` }); $('#student_autocomplete_matches').html(html).show(); $('.autocomplete_select').on('click', function(e) { const studentName = $(e.target).parent().find('span:first').text(); const studentId = $(e.target).parent().attr('data-id'); // add only if not already in the list if (!getSelectedStudentsIds().filter(id => id == studentId).length) { $('#student_autocomplete_selected_container').append(` <li class="list-group-item" data-id=${studentId}> ${studentName} <span class="autocomplete_remove">x</span> </li> `); } listenRemoveStudent(); }); } }) } function listenRemoveStudent() { $(".autocomplete_remove").on('click', function() { $(this).parent().remove(); }); } /** * Go throught the selected users list, and read the ids * * @return array */ function getSelectedStudentsIds() { let ids = []; $('#student_autocomplete_selected_container > li').each(function(i, e) { ids.push($(e).attr('data-id')); }); return ids; } });
const { DateTime } = require("luxon"); const CleanCSS = require("clean-css"); const UglifyJS = require("uglify-es"); const htmlmin = require("html-minifier"); const eleventyNavigationPlugin = require("@11ty/eleventy-navigation"); module.exports = function(eleventyConfig) { // Eleventy Navigation https://www.11ty.dev/docs/plugins/navigation/ eleventyConfig.addPlugin(eleventyNavigationPlugin); // Configuration API: use eleventyConfig.addLayoutAlias(from, to) to add // layout aliases! Say you have a bunch of existing content using // layout: post. If you don’t want to rewrite all of those values, just map // post to a new file like this: // eleventyConfig.addLayoutAlias("post", "layouts/my_new_post_layout.njk"); // Merge data instead of overriding // https://www.11ty.dev/docs/data-deep-merge/ eleventyConfig.setDataDeepMerge(true); // Add support for maintenance-free post authors // Adds an authors collection using the author key in our post frontmatter // Thanks to @pdehaan: https://github.com/pdehaan eleventyConfig.addCollection("authors", collection => { const blogs = collection.getFilteredByGlob("posts/*.md"); return blogs.reduce((coll, post) => { const author = post.data.author; if (!author) { return coll; } if (!coll.hasOwnProperty(author)) { coll[author] = []; } coll[author].push(post.data); return coll; }, {}); }); // Date formatting (human readable) eleventyConfig.addFilter("readableDate", dateObj => { // return DateTime.fromJSDate(dateObj).toFormat("dd LLL yyyy"); return DateTime.fromJSDate(dateObj).toLocaleString(DateTime.DATE_FULL); }); // Date formatting (machine readable) eleventyConfig.addFilter("machineDate", dateObj => { return DateTime.fromJSDate(dateObj).toFormat("yyyy-MM-dd"); }); // Minify CSS eleventyConfig.addFilter("cssmin", function(code) { return new CleanCSS({}).minify(code).styles; }); // Minify JS eleventyConfig.addFilter("jsmin", function(code) { let minified = UglifyJS.minify(code); if (minified.error) { console.log("UglifyJS error: ", minified.error); return code; } return minified.code; }); // Minify HTML output eleventyConfig.addTransform("htmlmin", function(content, outputPath) { if (outputPath.indexOf(".html") > -1) { let minified = htmlmin.minify(content, { useShortDoctype: true, removeComments: true, collapseWhitespace: true }); return minified; } return content; }); // Don't process folders with static assets e.g. images eleventyConfig.addPassthroughCopy("favicon.ico"); eleventyConfig.addPassthroughCopy("static/img"); eleventyConfig.addPassthroughCopy("admin"); eleventyConfig.addPassthroughCopy("_includes/assets/"); /* Markdown Plugins */ let markdownIt = require("markdown-it"); let markdownItAnchor = require("markdown-it-anchor"); let options = { html: true, breaks: true, linkify: true }; let opts = { permalink: false }; eleventyConfig.setLibrary("md", markdownIt(options) .use(markdownItAnchor, opts) ); return { templateFormats: ["md", "njk", "html", "liquid"], // If your site lives in a different subdirectory, change this. // Leading or trailing slashes are all normalized away, so don’t worry about it. // If you don’t have a subdirectory, use "" or "/" (they do the same thing) // This is only used for URLs (it does not affect your file structure) pathPrefix: "/", markdownTemplateEngine: "liquid", htmlTemplateEngine: "njk", dataTemplateEngine: "njk", dir: { input: ".", includes: "_includes", data: "_data", output: "_site" } }; };