text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
QUnit.module( "group a" ); QUnit.test( "a basic test example", function( assert ) { assert.ok( true, "this test is fine" ); }); QUnit.test( "a basic test example 2", function( assert ) { assert.ok( true, "this test is fine" ); }); QUnit.module( "group b" ); QUnit.test( "a basic test example 3", function( assert ) { assert.ok( true, "this test is fine" ); }); QUnit.test( "a basic test example 4", function( assert ) { assert.ok( true, "this test is fine" ); }); QUnit.module( "module a", function() { QUnit.test( "a basic test example", function( assert ) { assert.ok( true, "this test is fine" ); }); }); QUnit.module( "module b", function() { QUnit.test( "a basic test example 2", function( assert ) { assert.ok( true, "this test is fine" ); }); QUnit.module( "nested module b.1", function() { // This test will be prefixed with the following module label: // "module b > nested module b.1" QUnit.test( "a basic test example 3", function( assert ) { assert.ok( true, "this test is fine" ); }); }); }); QUnit.module( "module A", { before: function() { // prepare something once for all tests }, beforeEach: function() { // prepare something before each test }, afterEach: function() { // clean up after each test }, after: function() { // clean up once after all tests are done } }); QUnit.module( "Machine Maker", { beforeEach: function() { let Maker: any = () => {}; this.maker = new Maker(); this.parts = [ "wheels", "motor", "chassis" ]; } }); QUnit.test( "makes a robot", function( assert ) { this.parts.push( "arduino" ); assert.equal( this.maker.build( this.parts ), "robot" ); assert.deepEqual( this.maker.made, [ "robot" ] ); }); QUnit.test( "makes a car", function( assert ) { assert.equal( this.maker.build( this.parts ), "car" ); this.maker.duplicate(); assert.deepEqual( this.maker.made, [ "car", "car" ] ); }); QUnit.module( "grouped tests argument hooks", function( hooks ) { hooks.beforeEach( function( assert ) { assert.ok( true, "beforeEach called" ); } ); hooks.afterEach( function( assert ) { assert.ok( true, "afterEach called" ); } ); QUnit.test( "call hooks", function( assert ) { assert.expect( 2 ); } ); QUnit.module( "stacked hooks", function( hooks ) { // This will run after the parent module's beforeEach hook hooks.beforeEach( function( assert ) { assert.ok( true, "nested beforeEach called" ); } ); // This will run before the parent module's afterEach hooks.afterEach( function( assert ) { assert.ok( true, "nested afterEach called" ); } ); QUnit.test( "call hooks", function( assert ) { assert.expect( 4 ); } ); } ); } ); QUnit.module.only( "exclusive module" , function( hooks ) { hooks.beforeEach( function( assert ) { assert.ok( true, "beforeEach called" ); } ); hooks.afterEach( function( assert ) { assert.ok( true, "afterEach called" ); } ); QUnit.test( "call hooks", function( assert ) { assert.expect( 2 ); } ); QUnit.module.only( "nested exclusive module", { // This will run after the parent module's beforeEach hook beforeEach: assert => { assert.ok( true, "nested beforeEach called" ); }, // This will run before the parent module's afterEach afterEach: assert => { assert.ok( true, "nested afterEach called" ); } } ); QUnit.test( "call nested hooks", function( assert ) { assert.expect( 4 ); } ); }); QUnit.test( "`ok` assertion defined in the callback parameter", function( assert ) { assert.ok( true, "on the object passed to the `test` function" ); }); QUnit.begin(function( details ) { console.log( "Test amount:", details.totalTests ); }); QUnit.config.autostart = false; // require( // [ "tests/testModule1", "tests/testModule2" ], (function() { QUnit.start(); }()) // ); QUnit.test("some test", function() { // a few regular assertions // then a call to another tool let codeUnderTest = () => {}; let speedTest = (name: string, cb: () => void) => cb(); speedTest( QUnit.config.current.testName, codeUnderTest ); }); QUnit.config.urlConfig.push({ id: "min", label: "Minified source", tooltip: "Load minified source files instead of the regular unminified ones." }); QUnit.config.urlConfig.push({ id: "jquery", label: "jQuery version", value: [ "1.7.2", "1.8.3", "1.9.1" ], tooltip: "What jQuery Core version to test against" }); QUnit.done(function( details ) { console.log( "Total: ", details.total, " Failed: ", details.failed, " Passed: ", details.passed, " Runtime: ", details.runtime ); }); QUnit.log(function( obj ) { // Parse some stuff before sending it. var actual = QUnit.dump.parse( obj.actual ); var expected = QUnit.dump.parse( obj.expected ); // Send it. // sendMessage( "qunit.log", obj.result, actual, expected, obj.message, obj.source ); console.log("qunit.log", obj.result, actual, expected, obj.message, obj.source); }); var qHeader = document.getElementById( "qunit-header" ), parsed = QUnit.dump.parse( qHeader ); console.log( parsed ); var input: any = { parts: { front: [], back: [] } }; QUnit.dump.maxDepth = 1; console.log( QUnit.dump.parse( input ) ); // Logs: { "parts": [object Object] } QUnit.dump.maxDepth = 2; console.log( QUnit.dump.parse( input ) ); // Logs: { "parts": { "back": [object Array], "front": [object Array] } } QUnit.test( "QUnit.extend", function( assert ) { var base: any = { a: 1, b: 2, z: 3 }; QUnit.extend( base, { b: 2.5, c: 3, z: undefined } ); assert.equal( base.a, 1, "Unspecified values are not modified" ); assert.equal( base.b, 2.5, "Existing values are updated" ); assert.equal( base.c, 3, "New values are defined" ); assert.ok( !( "z" in base ), "Values specified as `undefined` are removed" ); }); QUnit.log(function( details ) { console.log( "Log: ", details.result, details.message ); }); QUnit.log(function( details ) { if ( details.result ) { return; } var loc = details.module + ": " + details.name + ": ", output = "FAILED: " + loc + ( details.message ? details.message + ", " : "" ); if ( details.actual ) { output += "expected: " + details.expected + ", actual: " + details.actual; } if ( details.source ) { output += ", " + details.source; } console.log( output ); }); QUnit.log(function( details: QUnit.LogDetails ) { let x: { actual: number; expected: number; message: string; module: string; name: string; result: boolean; runtime: number; source: string } = details; x = details; }); QUnit.begin(function( details: QUnit.BeginDetails ) { console.log( "Total tests running: ", details.totalTests); }); QUnit.done(function( details: QUnit.DoneDetails ) { console.log( "Finished. Failed/total: ", details.failed, details.total, details.passed, details.runtime ); }); QUnit.moduleDone(function( details: QUnit.ModuleDoneDetails ) { console.log( "Finished running: ", details.name, "Failed/total: ", details.failed, details.total, details.passed, details.runtime ); }); QUnit.moduleStart(function( details: QUnit.ModuleStartDetails ) { console.log( "Now running: ", details.name ); }); QUnit.testDone(function( details: QUnit.TestDoneDetails ) { console.log( "Finished running: ", details.name, "Failed/total: ", details.failed, details.total, details.passed, details.runtime); }); QUnit.testStart(function( details: QUnit.TestStartDetails ) { console.log( "Now running: ", details.name, ' from module ', details.module ); }); let Robot: any = () => {}; QUnit.module( "robot", { beforeEach: function() { this.robot = new Robot(); } }); QUnit.test( "say", function( assert ) { assert.ok( false, "I'm not quite ready yet" ); }); QUnit.test( "stomp", function( assert ) { assert.ok( false, "I'm not quite ready yet" ); }); // You're currently working on the laser feature, so we run only this test QUnit.only( "laser", function( assert ) { assert.ok( this.robot.laser() ); }); QUnit.module( "robot", { beforeEach: function() { this.robot = new Robot(); } }); QUnit.test( "say", function( assert ) { assert.strictEqual( this.robot.say(), "Exterminate!" ); }); // Robot doesn't have a laser method, yet, skip this test // Will show up as skipped in the results QUnit.skip( "laser", function( assert ) { assert.ok( this.robot.laser() ); }); QUnit.log( function( details ) { if ( details.result ) { // 5 is the line reference for the assertion method, not the following line. console.log( QUnit.stack( 5 ) ); } } ); QUnit.test( "foo", function( assert ) { // the log callback will report the position of the following line. assert.ok( true ); } ); QUnit.config.autostart = false; // require(["test/tests1.js", "test/tests2.js"], function() { (() => { QUnit.start(); })() // }); QUnit.test( "a test", function( assert ) { function square( x: number ) { return x * x; } var result = square( 2 ); assert.equal( result, 4, "square(2) equals 4" ); }); // declare var Promise: any; QUnit.test( "a Promise-returning test", function( assert ) { assert.expect( 0 ); var thenable = new Promise(function( resolve: any, reject: any ) { setTimeout(function() { resolve( "result" ); }, 500 ); }); return thenable; }); declare var $: any; QUnit.test( "assert.async() test", function( assert ) { var done = assert.async(); var input = $( "#test-input" ).focus(); setTimeout(function() { assert.equal( document.activeElement, input[0], "Input was focused" ); done(); }); }); QUnit.test( "two async calls", function( assert ) { assert.expect( 2 ); var done1 = assert.async(); var done2 = assert.async(); setTimeout(function() { assert.ok( true, "test resumed from async operation 1" ); done1(); }, 500 ); setTimeout(function() { assert.ok( true, "test resumed from async operation 2" ); done2(); }, 150); }); QUnit.test( "multiple call done()", function( assert ) { assert.expect( 3 ); var done = assert.async( 3 ); setTimeout(function() { assert.ok( true, "first call done." ); done(); }, 500 ); setTimeout(function() { assert.ok( true, "second call done." ); done(); }, 500 ); setTimeout(function() { assert.ok( true, "third call done." ); done(); }, 500 ); }); QUnit.test( "deepEqual test", function( assert ) { var obj = { foo: "bar" }; assert.deepEqual( obj, { foo: "bar" }, "Two objects can be the same in value" ); }); QUnit.test( "ok test", function( assert ) { assert.ok( true, "true succeeds" ); assert.ok( "non-empty", "non-empty string succeeds" ); assert.ok( false, "false fails" ); assert.ok( 0, "0 fails" ); assert.ok( NaN, "NaN fails" ); assert.ok( "", "empty string fails" ); assert.ok( null, "null fails" ); assert.ok( undefined, "undefined fails" ); }); QUnit.test( "a test", function( assert ) { assert.equal( 1, "1", "String '1' and number 1 have the same value" ); }); QUnit.test( "equal test", function( assert ) { assert.equal( 0, 0, "Zero, Zero; equal succeeds" ); assert.equal( "", 0, "Empty, Zero; equal succeeds" ); assert.equal( "", "", "Empty, Empty; equal succeeds" ); assert.equal( "three", 3, "Three, 3; equal fails" ); assert.equal( null, false, "null, false; equal fails" ); }); QUnit.test( "a test", function( assert ) { assert.expect( 2 ); function calc( x: number, operation: (x:number)=> number ) { return operation( x ); } var result = calc( 2, function( x ) { assert.ok( true, "calc() calls operation function" ); return x * x; }); assert.equal( result, 4, "2 squared equals 4" ); }); QUnit.test( "notDeepEqual test", function( assert ) { var obj = { foo: "bar" }; assert.notDeepEqual( obj, { foo: "bla" }, "Different object, same key, different value, not equal" ); }); QUnit.test( "a test", function( assert ) { assert.notEqual( 1, "2", "String '2' and number 1 don't have the same value" ); }); QUnit.test( "notOk test", function( assert ) { assert.notOk( false, "false succeeds" ); assert.notOk( "", "empty string succeeds" ); assert.notOk( NaN, "NaN succeeds" ); assert.notOk( null, "null succeeds" ); assert.notOk( undefined, "undefined succeeds" ); assert.notOk( true, "true fails" ); assert.notOk( 1, "1 fails" ); assert.notOk( "not-empty", "not-empty string fails" ); }); QUnit.test( "notPropEqual test", function( assert ) { class Foo { x: any; y: any; z: any; constructor( x: any, y: any, z: any ) { this.x = x; this.y = y; this.z = z; } doA = function () {}; doB = function () {}; bar = 'prototype'; } var foo = new Foo( 1, "2", [] ); var bar = new Foo( "1", 2, {} ); assert.notPropEqual( foo, bar, "Properties values are strictly compared." ); }); QUnit.test( "a test", function( assert ) { assert.notStrictEqual( 1, "1", "String '1' and number 1 have the same value but not the same type" ); }); QUnit.test( "propEqual test", function( assert ) { class Foo { x: any; y: any; z: any; constructor( x: any, y: any, z: any ) { this.x = x; this.y = y; this.z = z; } doA = function () {}; doB = function () {}; bar = 'prototype'; } var foo = new Foo( 1, "2", [] ); var bar: any = { x : 1, y : "2", z : [] }; assert.propEqual( foo, bar, "Strictly the same properties without comparing objects constructors." ); }); // QUnit.assert['mod2'] = function( value: any, expected: any, message: string ): any { // var actual = value % 2; // this.pushResult({ // result: actual === expected, // actual: actual, // expected: expected, // message: message // }); // }; // QUnit.test( "mod2", function( assert ) { // assert.expect( 2 ); // assert['mod2']( 2, 0, "2 % 2 == 0" ); // assert['mod2']( 3, 1, "3 % 2 == 1" ); // }); QUnit.test( "throws", function( assert ) { class CustomError { message: string; constructor(message: string) { this.message = message; } toString = function() { return this.message; } } assert.throws( function() { throw "error" }, "throws with just a message, not using the 'expected' argument" ); assert.throws( function() { throw new CustomError("some error description"); }, /description/, "raised error message contains 'description'" ); assert.throws( function() { throw new Error(); }, CustomError, "raised error is an instance of CustomError" ); assert.throws( function() { throw new CustomError("some error description"); }, new CustomError("some error description"), "raised error instance matches the CustomError instance" ); assert.throws( function() { throw new CustomError("some error description"); }, function( err: any ) { return err.toString() === "some error description"; }, "raised error instance satisfies the callback function" ); }); QUnit.test( "rejects", function( assert ) { assert.rejects(Promise.reject("some error description")); assert.rejects( Promise.reject(new Error("some error description")), "rejects with just a message, not using the 'expectedMatcher' argument" ); assert.rejects( Promise.reject(new Error("some error description")), /description/, "`rejectionValue.toString()` contains `description`" ); // Using a custom error like object class CustomError { message?: string; constructor(message?: string) { this.message = message; } toString() { return this.message; } } assert.rejects( Promise.reject(new CustomError()), CustomError, "raised error is an instance of CustomError" ); assert.rejects( Promise.reject(new CustomError("some error description")), new CustomError("some error description"), "raised error instance matches the CustomError instance" ); assert.rejects( Promise.reject(new CustomError("some error description")), function( err ) { return err.toString() === "some error description"; }, "raised error instance satisfies the callback function" ); }); QUnit.module( "module", { beforeEach: function( assert ) { assert.ok( true, "one extra assert per test" ); }, afterEach: function( assert ) { assert.ok( true, "and one extra assert after each test" ); } }); QUnit.test( "test with beforeEach and afterEach", function( assert ) { assert.expect( 2 ); }); QUnit.todo( "a todo test", function( assert ) { assert.equal( 0, 1, "0 does not equal 1, so this todo should pass" ); }); let equivResult: boolean; equivResult = QUnit.equiv({}, {}); equivResult = QUnit.equiv(1, 2); equivResult = QUnit.equiv('foo', 'bar'); equivResult = QUnit.equiv(['foo'], ['bar']); QUnit.test('steps', assert => { assert.step('one'); assert.step('two'); assert.step('three'); assert.verifySteps(['one', 'two', 'three'], 'Counting to three correctly'); });
the_stack
import {Injectable} from '@angular/core'; import { BaseType as D3BaseType, ContainerElement as D3ContainerElement, event as d3Event, mouse as d3Mouse, select as d3Select, selectAll as d3SelectAll, Selection as D3Selection } from 'd3-selection'; import {Transition as D3Transition} from 'd3-transition'; import {TimeSeriesPoint} from '../../models/time-series-point.model'; import {UrlBuilderService} from '../url-builder.service'; import ContextMenuPosition from '../../models/context-menu-position.model'; import {ScaleTime as D3ScaleTime} from 'd3-scale'; import {TimeSeries} from '../../models/time-series.model'; import {BrushBehavior, brushX as d3BrushX} from 'd3-brush'; import {LineChartDrawService} from './line-chart-draw.service'; import {LineChartScaleService} from './line-chart-scale.service'; import {PointsSelection} from '../../models/points-selection.model'; import {TranslateService} from '@ngx-translate/core'; @Injectable({ providedIn: 'root' }) export class LineChartEventService { private _DOT_HIGHLIGHT_RADIUS = 5; private _contextMenuBackground: D3Selection<D3BaseType, number, D3BaseType, unknown>; private _contextMenu: D3Selection<D3BaseType, number, D3BaseType, unknown>; private _dotsOnMarker: D3Selection<D3BaseType, {}, HTMLElement, any>; private _contextMenuPoint: D3Selection<D3BaseType, TimeSeriesPoint, D3BaseType, any>; private brush: BrushBehavior<{}>; private brushMinDate: Date = null; private brushMaxDate: Date = null; constructor(private urlBuilderService: UrlBuilderService, private translationService: TranslateService, private lineChartDrawService: LineChartDrawService, private lineChartScaleService: LineChartScaleService) { } private _pointSelectionErrorHandler: Function; set pointSelectionErrorHandler(value: Function) { this._pointSelectionErrorHandler = value; } private _pointsSelection: PointsSelection; get pointsSelection(): PointsSelection { return this._pointsSelection; } private contextMenu: ContextMenuPosition[] = [ { title: 'summary', icon: 'fas fa-file-alt', action: (d: TimeSeriesPoint) => { window.open(this.urlBuilderService .buildSummaryUrl(d.wptInfo)); } }, { title: 'waterfall', icon: 'fas fa-bars', action: (d: TimeSeriesPoint) => { window.open(this.urlBuilderService .buildWaterfallUrl(d.wptInfo)); } }, { title: 'performanceReview', icon: 'fas fa-check', action: (d: TimeSeriesPoint) => { window.open(this.urlBuilderService .buildPerformanceReviewUrl(d.wptInfo)); } }, { title: 'contentBreakdown', icon: 'fas fa-chart-pie', action: (d: TimeSeriesPoint) => { window.open(this.urlBuilderService .buildContentBreakdownUrl(d.wptInfo)); } }, { title: 'domains', icon: 'fas fa-list', action: (d: TimeSeriesPoint) => { window.open(this.urlBuilderService .buildDomainsUrl(d.wptInfo)); } }, { title: 'screenshot', icon: 'fas fa-image', action: (d: TimeSeriesPoint) => { window.open(this.urlBuilderService .buildScreenshotUrl(d.wptInfo)); } }, { title: 'filmstrip', icon: 'fas fa-film', action: (d: TimeSeriesPoint) => { window.open(this.urlBuilderService .buildFilmstripUrl(d.wptInfo)); } }, { title: 'filmstripTool', icon: 'fas fa-money-check', action: (d: TimeSeriesPoint) => { window.open(this.urlBuilderService .buildFilmstripToolUrl(d.wptInfo)); } }, { title: 'compareFilmstrips', icon: 'fas fa-columns', visible: () => { return this._pointsSelection.count() > 0; }, action: () => { const selectedDots = this._pointsSelection.getAll(); const wptInfos = selectedDots.map(it => it.wptInfo); window.open(this.urlBuilderService .buildFilmstripsComparisionUrl(wptInfos)); } }, { divider: true }, { title: 'selectPoint', icon: 'fas fa-dot-circle', visible: (d: TimeSeriesPoint) => { return !this._pointsSelection.isPointSelected(d); }, action: (d: TimeSeriesPoint) => { this.changePointSelection(d); } }, { title: 'deselectPoint', icon: 'fas fa-trash-alt', visible: (d: TimeSeriesPoint) => { return this._pointsSelection.isPointSelected(d); }, action: (d: TimeSeriesPoint) => { this.changePointSelection(d); } }, ]; private backgroundContextMenu: ContextMenuPosition[] = [ { title: 'compareFilmstrips', icon: 'fas fa-columns', visible: () => { return this._pointsSelection.count() >= 2; }, action: () => { const selectedDots = this._pointsSelection.getAll(); const wptInfos = selectedDots.map(it => it.wptInfo); window.open(this.urlBuilderService .buildFilmstripsComparisionUrl(wptInfos)); } }, { title: 'deselectAllPoints', icon: 'fas fa-trash-alt', visible: () => { return this._pointsSelection.count() > 0; }, action: () => { this.unselectAllPoints(); } }, ]; prepareCleanState(): void { this._pointsSelection = new PointsSelection(); this._contextMenuPoint = null; this.lineChartDrawService.xAxisCluster = {}; } prepareMouseEventCatcher(chart: D3Selection<D3BaseType, {}, D3ContainerElement, {}>, width: number, height: number, marginTop: number, marginLeft): void { if (!chart.select('.chart-content').empty()) { return; } // Watcher for mouse events chart.append('svg:g') .attr('class', 'chart-content') .attr('width', width) .attr('height', height) .attr('fill', 'none') .on('mouseenter', () => this.showMarker()) .on('mouseleave', () => this.hideMarker()) .on('contextmenu', () => d3Event.preventDefault()) .on('mousemove', (_, index, nodes: D3ContainerElement[]) => { this.moveMarker(nodes[index], width, height, marginTop, marginLeft); }); } createContextMenu(): void { if (!this._contextMenuBackground) { this._contextMenuBackground = d3Select('body') .selectAll('.d3-context-menu-background') .data([1]) .enter() .append('div') .attr('class', 'd3-context-menu-background') .on('click', () => { this.closeContextMenu(); }).on('contextmenu', () => { this.closeContextMenu(); }, false); } if (!this._contextMenu) { this._contextMenu = d3Select('body') .selectAll('.d3-context-menu') .data([1]) .enter() .append('rect') .attr('class', 'd3-context-menu') .on('contextmenu', () => d3Event.preventDefault()); } } addBrush(chartContentContainer: D3Selection<D3BaseType, {}, D3ContainerElement, {}>, width: number, height: number, yAxisWidth: number, xScale: D3ScaleTime<number, number>, data: { [key: string]: TimeSeries[] }, dataTrimValues: { [key: string]: { [key: string]: number } }, legendDataMap: { [key: string]: { [key: string]: (boolean | string) } }): void { // remove old brush d3Select('.brush').remove(); this.brush = d3BrushX() .extent([[0, 0], [width, height]]) .on('end', () => this.zoomInTheChart(chartContentContainer, width, height, yAxisWidth, xScale, data, dataTrimValues, legendDataMap)); chartContentContainer .append('g') .attr('class', 'brush') .call(this.brush); d3Select('.overlay') .on('dblclick', () => this.resetChart(chartContentContainer, width, height, yAxisWidth, xScale, data, dataTrimValues, legendDataMap)) .on('contextmenu', (d, i, e) => this.showContextMenu(this.backgroundContextMenu)(d, i, e)); } restoreSelectedZoom(chartContentContainer: D3Selection<D3BaseType, {}, D3ContainerElement, {}>, width: number, height: number, yAxisWidth: number, xScale: D3ScaleTime<number, number>, data: { [key: string]: TimeSeries[] }, dataTrimValues: { [key: string]: { [key: string]: number } }, legendDataMap: { [key: string]: { [key: string]: (boolean | string) } }): void { if (this.brushMinDate !== null && this.brushMaxDate !== null) { this.updateChart(chartContentContainer, width, height, yAxisWidth, xScale, data, dataTrimValues, legendDataMap); } } addMouseMarkerToChart(markerParent: D3Selection<D3BaseType, {}, D3ContainerElement, {}>): void { if (!d3Select('.marker-line').empty()) { return; } // Append the marker line, initially hidden markerParent .append('path') .attr('class', 'marker-line') .style('opacity', '0') .style('pointer-events', 'none'); // Add tooltip box to chart d3Select('#time-series-chart') .select((_, index: number, elem) => (<SVGElement>elem[index]).parentNode) .append('div') .attr('id', 'marker-tooltip') .style('opacity', '0.9'); } private moveMarker(node: D3ContainerElement, width: number, containerHeight: number, marginTop: number, marginLeft: number): void { // marker can only be moved from one dot to another dot if there are at least two dots if (this.lineChartDrawService.xAxisCluster.length < 2) { return; } const nearestDot = this.findNearestDot(d3Mouse(node), d3SelectAll('.dot')); if (!nearestDot) { this._dotsOnMarker = d3Select(null); this.hideMarker(); return; } const markerPositionX = nearestDot.attr('cx'); // draw marker line const markerPath = `M${markerPositionX},${containerHeight} ${markerPositionX},0`; d3Select('.marker-line').attr('d', markerPath); this.hideOldDotsOnMarker(); const dotsOnMarker = this.findDotsOnMarker(markerPositionX); this.showDotsOnMarker(dotsOnMarker); nearestDot.attr('r', this._DOT_HIGHLIGHT_RADIUS); this._dotsOnMarker = dotsOnMarker; this.showTooltip(nearestDot, dotsOnMarker, nearestDot.datum().date, width, marginTop, marginLeft); } private zoomInTheChart(chartContentContainer: D3Selection<D3BaseType, {}, D3ContainerElement, {}>, width: number, height: number, yAxisWidth: number, xScale: D3ScaleTime<number, number>, data: { [key: string]: TimeSeries[] }, dataTrimValues: { [key: string]: { [key: string]: number } }, legendDataMap: { [key: string]: { [key: string]: (boolean | string) } }): void { const extent = d3Event.selection; if (!extent) { return; } // Remove the grey brush area d3Select('.brush').call(this.brush.move, null); this.brushMinDate = xScale.invert(extent[0]); this.brushMaxDate = xScale.invert(extent[1]); this.updateChart(chartContentContainer, width, height, yAxisWidth, xScale, data, dataTrimValues, legendDataMap); } private resetChart(chartContentContainer: D3Selection<D3BaseType, {}, D3ContainerElement, {}>, width: number, height: number, yAxisWidth: number, xScale: D3ScaleTime<number, number>, data: { [key: string]: TimeSeries[] }, dataTrimValues: { [key: string]: { [key: string]: number } }, legendDataMap: { [key: string]: { [key: string]: (boolean | string) } }): void { if (this.brushMinDate === null || this.brushMaxDate === null) { return; } this.brushMinDate = null; this.brushMaxDate = null; // Change X axis domain xScale.domain([this.lineChartScaleService.getMinDate(data), this.lineChartScaleService.getMaxDate(data)]); d3Select('.x-axis').transition().call((transition: D3Transition<SVGGElement, any, HTMLElement, any>) => this.lineChartDrawService.updateXAxis(transition, xScale)); const yNewScales = this.lineChartScaleService.getYScales(data, height, dataTrimValues); this.lineChartDrawService.updateYAxes(yNewScales, width, yAxisWidth); Object.keys(yNewScales).forEach((key: string, index: number) => { this.lineChartDrawService.addDataLinesToChart( chartContentContainer, this._pointsSelection, xScale, yNewScales[key], data[key], legendDataMap, index); }); this.showMarker(); } private updateChart(chartContentContainer: D3Selection<D3BaseType, {}, D3ContainerElement, {}>, width: number, height: number, yAxisWidth: number, xScale: D3ScaleTime<number, number>, data: { [key: string]: TimeSeries[] }, dataTrimValues: { [key: string]: { [key: string]: number } }, legendDataMap: { [key: string]: { [key: string]: (boolean | string) } }): void { xScale.domain([this.brushMinDate, this.brushMaxDate]); d3Select('.x-axis').transition().call((transition: D3Transition<SVGGElement, any, HTMLElement, any>) => this.lineChartDrawService.updateXAxis(transition, xScale)); const yNewScales = this.lineChartScaleService.getYScalesInTimeRange(data, height, dataTrimValues, this.brushMinDate, this.brushMaxDate); this.lineChartDrawService.updateYAxes(yNewScales, width, yAxisWidth); Object.keys(yNewScales).forEach((key: string, index: number) => { this.lineChartDrawService.addDataLinesToChart( chartContentContainer, this._pointsSelection, xScale, yNewScales[key], data[key], legendDataMap, index); }); } private findNearestDot(mouseCoordinates: [number, number], dots): D3Selection<any, TimeSeriesPoint, null, any> { const mousePosition = {x: mouseCoordinates[0], y: mouseCoordinates[1]}; let currentNearestDot = null; let minCompareDistance; dots.each((_, index: number, nodes: []) => { const pointSelection = d3Select(nodes[index]); const cx = parseFloat(pointSelection.attr('cx')); const cy = parseFloat(pointSelection.attr('cy')); const compareDistance = this.pointsCompareDistance(mousePosition, {x: cx, y: cy}); if (minCompareDistance === undefined || compareDistance < minCompareDistance) { currentNearestDot = pointSelection; minCompareDistance = compareDistance; } }); return currentNearestDot; } private showDotsOnMarker(dots: D3Selection<D3BaseType, {}, HTMLElement, any>): void { // show dots on marker dots .attr('visibility', 'visible') .style('fill', 'white') .style('cursor', 'pointer') .on('contextmenu', (d, i, e) => { this._contextMenuPoint = d3Select(e[i]); this.showContextMenu(this.contextMenu)(d, i, e); }) .on('click', (dotData: TimeSeriesPoint) => { d3Event.preventDefault(); if (d3Event.metaKey || d3Event.ctrlKey) { this.changePointSelection(dotData); } else { window.open(this.urlBuilderService .buildWaterfallUrl(dotData.wptInfo)); } }); } private pointsCompareDistance(p1: { [key: string]: number }, p2: { [key: string]: number }): number { // Taxicab/Manhattan approximation of euclidean distance return Math.abs(p1.x - p2.x) + Math.abs(p1.y - p2.y); } private findDotsOnMarker(pointX: string): D3Selection<D3BaseType, {}, HTMLElement, any> { const cx = pointX.toString().replace('.', '_'); return d3SelectAll(`.dot-x-${cx}`); } private showMarker(): void { d3Select('.marker-line').style('opacity', 1); d3Select('#marker-tooltip').style('opacity', 1); } private hideMarker(): void { d3Select('.marker-line').style('opacity', 0); d3Select('#marker-tooltip').style('opacity', 0); this.hideOldDotsOnMarker(); } private hideOldDotsOnMarker(): void { if (this._dotsOnMarker) { const contextMenuPointData = this._contextMenuPoint ? this._contextMenuPoint.data()[0] : null; this._dotsOnMarker .filter((s: TimeSeriesPoint) => !s.equals(contextMenuPointData)) .attr('r', this.lineChartDrawService.DOT_RADIUS) .attr('visibility', 'hidden') .style('cursor', 'auto') .on('click', null) .on('contextmenu', null); this.lineChartDrawService.drawSelectedPoints(this._dotsOnMarker, this._pointsSelection); } } private showContextMenu(menu: ContextMenuPosition[]) { // this gets executed when a contextmenu event occurs return (data, currentIndex, viewElements): void => { const selectedNode = viewElements[currentIndex]; const visibleMenuElements = menu.filter(elem => { // visible is optional value, so even without this property the element is visible return (elem.visible === undefined) || (elem.visible(data, currentIndex, selectedNode)); }); if (visibleMenuElements.length === 0) { // do not show empty context menu return; } const background = this._contextMenuBackground.html(''); const contextMenu = this._contextMenu.html(''); const contextMenuPositions = contextMenu .selectAll('li') .data(visibleMenuElements) .enter() .append('li'); const clickListener = (e: ContextMenuPosition) => { e.action(data, currentIndex, selectedNode); this.closeContextMenu(); }; contextMenuPositions.each((ctxMenuPositionData: ContextMenuPosition, ctxMenuPositionIndex, ctxMenuPositions) => { const currentMenuPosition = d3Select(ctxMenuPositions[ctxMenuPositionIndex]); if (ctxMenuPositionData.divider) { currentMenuPosition .attr('class', 'd3-context-menu-divider') .on('contextmenu', () => d3Event.preventDefault()); } else { currentMenuPosition.append('i').attr('class', (d: ContextMenuPosition) => d.icon); currentMenuPosition.append('span').html((d: ContextMenuPosition) => { return this.translationService.instant(`frontend.de.iteratec.chart.contextMenu.${d.title}`); }); currentMenuPosition .on('click', clickListener) .on('contextmenu', clickListener); } }); // display context menu background.style('display', 'block'); contextMenu.style('display', 'block'); // context menu must be displayed to take its width const contextMenuWidth = (<HTMLDivElement>this._contextMenu.node()).offsetWidth; const left = ((d3Event.pageX + contextMenuWidth + 40) < window.innerWidth) ? (d3Event.pageX) : (d3Event.pageX - contextMenuWidth); // move context menu contextMenu .style('left', `${left}px`) .style('top', `${(d3Event.pageY - 2)}px`); d3Event.preventDefault(); }; } private closeContextMenu() { d3Event.preventDefault(); this._contextMenuBackground.style('display', 'none'); this._contextMenu.style('display', 'none'); // hide context menu point this._contextMenuPoint = null; this.hideOldDotsOnMarker(); } private changePointSelection(point: TimeSeriesPoint) { let canPointBeSelected = true; if (this._pointsSelection.count() > 0) { const testServerUrl = this._pointsSelection.getFirst().wptInfo.baseUrl; if (point.wptInfo.baseUrl !== testServerUrl) { canPointBeSelected = false; } } if (!canPointBeSelected) { this._pointSelectionErrorHandler(); return; } if (this._pointsSelection.isPointSelected(point)) { this._pointsSelection.unselectPoint(point); } else { this._pointsSelection.selectPoint(point); } this.lineChartDrawService.drawAllSelectedPoints(this._pointsSelection); } private unselectAllPoints() { this._pointsSelection.unselectAll(); d3SelectAll('.dot').each((currentDotData: TimeSeriesPoint, index: number, dots: D3BaseType[]) => { const isDotOnMarkerLine: boolean = this._dotsOnMarker.data().some((elem: TimeSeriesPoint) => { return currentDotData.equals(elem); }); if (!isDotOnMarkerLine) { d3Select(dots[index]).attr('visibility', 'hidden'); } }); } private showTooltip(nearestDot: D3Selection<any, TimeSeriesPoint, null, undefined>, visibleDots: D3Selection<D3BaseType, {}, HTMLElement, any>, highlightedDate: Date, svgWidth: number, marginTop: number, marginLeft: number) { const tooltip = d3Select('#marker-tooltip'); const tooltipText = this.generateTooltipText(nearestDot, visibleDots, highlightedDate); tooltip.html(tooltipText.outerHTML); const tooltipWidth: number = (<HTMLDivElement>tooltip.node()).getBoundingClientRect().width; const nearestDotXPosition: number = parseFloat(nearestDot.attr('cx')); const top = parseFloat(nearestDot.attr('cy')) + marginTop; const left = (nearestDotXPosition + tooltipWidth > svgWidth) ? (nearestDotXPosition - tooltipWidth + marginLeft) : nearestDotXPosition + marginLeft + 50; tooltip.style('top', `${top}px`); tooltip.style('left', `${left}px`); } private generateTooltipText(nearestDot: D3Selection<any, TimeSeriesPoint, null, undefined>, visibleDots: D3Selection<D3BaseType, {}, HTMLElement, any>, highlightedDate: Date): HTMLTableElement { const nearestDotData = nearestDot.datum() as TimeSeriesPoint; const table: HTMLTableElement = document.createElement('table'); const tableBody: HTMLTableSectionElement = document.createElement('tbody'); table.append(tableBody); tableBody.append(this.generateTooltipTimestampRow(highlightedDate)); const tempArray = []; let testAgent: string | Node = ''; visibleDots .each((timeSeriesPoint: TimeSeriesPoint, index: number, nodes: D3BaseType[]) => { tempArray.push({ 'htmlNode': this.generateTooltipDataPointRow(timeSeriesPoint, nodes[index], nearestDotData), 'yPosition': nodes[index]['cy'].animVal.value }); if (index === 0) { testAgent = this.generateTooltipTestAgentRow(timeSeriesPoint); } }); tempArray .sort((a, b) => a.yPosition - b.yPosition) .forEach(elem => tableBody.append(elem.htmlNode)); tableBody.append(testAgent); return table; } private generateTooltipTimestampRow(highlightedDate: Date): string | Node { const label: HTMLTableCellElement = document.createElement('td'); const translatedLabel: string = this.translationService.instant('frontend.de.iteratec.osm.timeSeries.chart.label.timestamp'); label.append(translatedLabel); const date: HTMLTableCellElement = document.createElement('td'); date.append(highlightedDate.toLocaleString()); const row: HTMLTableRowElement = document.createElement('tr'); row.append(label); row.append(date); return row; } private generateTooltipDataPointRow(currentPoint: TimeSeriesPoint, node: D3BaseType, nearestDotData: TimeSeriesPoint): string | Node { const label: HTMLTableCellElement = document.createElement('td'); label.append(currentPoint.tooltipText); const value: HTMLTableCellElement = document.createElement('td'); const lineColorDot: HTMLElement = document.createElement('i'); lineColorDot.className = 'fas fa-circle'; lineColorDot.style.color = d3Select(node).style('stroke'); value.append(lineColorDot); if (currentPoint.value !== undefined && currentPoint.value !== null) { value.append(currentPoint.value.toString()); } const row: HTMLTableRowElement = document.createElement('tr'); if (currentPoint.equals(nearestDotData)) { row.className = 'active'; } row.append(label); row.append(value); return row; } private generateTooltipTestAgentRow(currentPoint: TimeSeriesPoint): string | Node { const label: HTMLTableCellElement = document.createElement('td'); const translatedLabel: string = this.translationService.instant('frontend.de.iteratec.osm.timeSeries.chart.label.testAgent'); label.append(translatedLabel); const testAgent: HTMLTableCellElement = document.createElement('td'); testAgent.append(currentPoint.agent); const row: HTMLTableRowElement = document.createElement('tr'); row.append(label); row.append(testAgent); return row; } }
the_stack
import * as coreHttp from "@azure/core-http"; /** Storage Service Properties. */ export interface QueueServiceProperties { /** Azure Analytics Logging settings */ queueAnalyticsLogging?: Logging; /** A summary of request statistics grouped by API in hourly aggregates for queues */ hourMetrics?: Metrics; /** a summary of request statistics grouped by API in minute aggregates for queues */ minuteMetrics?: Metrics; /** The set of CORS rules. */ cors?: CorsRule[]; } /** Azure Analytics Logging settings. */ export interface Logging { /** The version of Storage Analytics to configure. */ version: string; /** Indicates whether all delete requests should be logged. */ deleteProperty: boolean; /** Indicates whether all read requests should be logged. */ read: boolean; /** Indicates whether all write requests should be logged. */ write: boolean; /** the retention policy */ retentionPolicy: RetentionPolicy; } /** the retention policy */ export interface RetentionPolicy { /** Indicates whether a retention policy is enabled for the storage service */ enabled: boolean; /** Indicates the number of days that metrics or logging or soft-deleted data should be retained. All data older than this value will be deleted */ days?: number; } /** An interface representing Metrics. */ export interface Metrics { /** The version of Storage Analytics to configure. */ version?: string; /** Indicates whether metrics are enabled for the Queue service. */ enabled: boolean; /** Indicates whether metrics should generate summary statistics for called API operations. */ includeAPIs?: boolean; /** the retention policy */ retentionPolicy?: RetentionPolicy; } /** CORS is an HTTP feature that enables a web application running under one domain to access resources in another domain. Web browsers implement a security restriction known as same-origin policy that prevents a web page from calling APIs in a different domain; CORS provides a secure way to allow one domain (the origin domain) to call APIs in another domain */ export interface CorsRule { /** The origin domains that are permitted to make a request against the storage service via CORS. The origin domain is the domain from which the request originates. Note that the origin must be an exact case-sensitive match with the origin that the user age sends to the service. You can also use the wildcard character '*' to allow all origin domains to make requests via CORS. */ allowedOrigins: string; /** The methods (HTTP request verbs) that the origin domain may use for a CORS request. (comma separated) */ allowedMethods: string; /** the request headers that the origin domain may specify on the CORS request. */ allowedHeaders: string; /** The response headers that may be sent in the response to the CORS request and exposed by the browser to the request issuer */ exposedHeaders: string; /** The maximum amount time that a browser should cache the preflight OPTIONS request. */ maxAgeInSeconds: number; } export interface StorageError { message?: string; code?: string; } /** Stats for the storage service. */ export interface QueueServiceStatistics { /** Geo-Replication information for the Secondary Storage Service */ geoReplication?: GeoReplication; } /** Geo-Replication information for the Secondary Storage Service */ export interface GeoReplication { /** The status of the secondary location */ status: GeoReplicationStatusType; /** A GMT date/time value, to the second. All primary writes preceding this value are guaranteed to be available for read operations at the secondary. Primary writes after this point in time may or may not be available for reads. */ lastSyncOn: Date; } /** The object returned when calling List Queues on a Queue Service. */ export interface ListQueuesSegmentResponse { serviceEndpoint: string; prefix: string; marker?: string; maxPageSize: number; queueItems?: QueueItem[]; continuationToken: string; } /** An Azure Storage Queue. */ export interface QueueItem { /** The name of the Queue. */ name: string; /** Dictionary of <string> */ metadata?: { [propertyName: string]: string }; } /** signed identifier */ export interface SignedIdentifier { /** a unique id */ id: string; /** The access policy */ accessPolicy: AccessPolicy; } /** An Access policy */ export interface AccessPolicy { /** the date-time the policy is active */ startsOn?: string; /** the date-time the policy expires */ expiresOn?: string; /** the permissions for the acl policy */ permissions?: string; } /** The object returned in the QueueMessageList array when calling Get Messages on a Queue. */ export interface DequeuedMessageItem { /** The Id of the Message. */ messageId: string; /** The time the Message was inserted into the Queue. */ insertedOn: Date; /** The time that the Message will expire and be automatically deleted. */ expiresOn: Date; /** This value is required to delete the Message. If deletion fails using this popreceipt then the message has been dequeued by another client. */ popReceipt: string; /** The time that the message will again become visible in the Queue. */ nextVisibleOn: Date; /** The number of times the message has been dequeued. */ dequeueCount: number; /** The content of the Message. */ messageText: string; } /** A Message object which can be stored in a Queue */ export interface QueueMessage { /** The content of the message */ messageText: string; } /** The object returned in the QueueMessageList array when calling Put Message on a Queue */ export interface EnqueuedMessage { /** The Id of the Message. */ messageId: string; /** The time the Message was inserted into the Queue. */ insertedOn: Date; /** The time that the Message will expire and be automatically deleted. */ expiresOn: Date; /** This value is required to delete the Message. If deletion fails using this popreceipt then the message has been dequeued by another client. */ popReceipt: string; /** The time that the message will again become visible in the Queue. */ nextVisibleOn: Date; } /** The object returned in the QueueMessageList array when calling Peek Messages on a Queue */ export interface PeekedMessageItem { /** The Id of the Message. */ messageId: string; /** The time the Message was inserted into the Queue. */ insertedOn: Date; /** The time that the Message will expire and be automatically deleted. */ expiresOn: Date; /** The number of times the message has been dequeued. */ dequeueCount: number; /** The content of the Message. */ messageText: string; } /** Defines headers for Service_setProperties operation. */ export interface ServiceSetPropertiesHeaders { /** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */ requestId?: string; /** Indicates the version of the Queue service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */ version?: string; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; /** Error Code */ errorCode?: string; } /** Defines headers for Service_setProperties operation. */ export interface ServiceSetPropertiesExceptionHeaders { errorCode?: string; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; } /** Defines headers for Service_getProperties operation. */ export interface ServiceGetPropertiesHeaders { /** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */ requestId?: string; /** Indicates the version of the Queue service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */ version?: string; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; /** Error Code */ errorCode?: string; } /** Defines headers for Service_getProperties operation. */ export interface ServiceGetPropertiesExceptionHeaders { errorCode?: string; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; } /** Defines headers for Service_getStatistics operation. */ export interface ServiceGetStatisticsHeaders { /** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */ requestId?: string; /** Indicates the version of the Queue service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */ version?: string; /** UTC date/time value generated by the service that indicates the time at which the response was initiated */ date?: Date; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; /** Error Code */ errorCode?: string; } /** Defines headers for Service_getStatistics operation. */ export interface ServiceGetStatisticsExceptionHeaders { errorCode?: string; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; } /** Defines headers for Service_listQueuesSegment operation. */ export interface ServiceListQueuesSegmentHeaders { /** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */ requestId?: string; /** Indicates the version of the Queue service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */ version?: string; /** UTC date/time value generated by the service that indicates the time at which the response was initiated */ date?: Date; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; /** Error Code */ errorCode?: string; } /** Defines headers for Service_listQueuesSegment operation. */ export interface ServiceListQueuesSegmentExceptionHeaders { errorCode?: string; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; } /** Defines headers for Queue_create operation. */ export interface QueueCreateHeaders { /** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */ requestId?: string; /** Indicates the version of the Queue service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */ version?: string; /** UTC date/time value generated by the service that indicates the time at which the response was initiated */ date?: Date; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; /** Error Code */ errorCode?: string; } /** Defines headers for Queue_create operation. */ export interface QueueCreateExceptionHeaders { errorCode?: string; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; } /** Defines headers for Queue_delete operation. */ export interface QueueDeleteHeaders { /** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */ requestId?: string; /** Indicates the version of the Queue service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */ version?: string; /** UTC date/time value generated by the service that indicates the time at which the response was initiated */ date?: Date; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; /** Error Code */ errorCode?: string; } /** Defines headers for Queue_delete operation. */ export interface QueueDeleteExceptionHeaders { errorCode?: string; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; } /** Defines headers for Queue_getProperties operation. */ export interface QueueGetPropertiesHeaders { metadata?: { [propertyName: string]: string }; /** The approximate number of messages in the queue. This number is not lower than the actual number of messages in the queue, but could be higher. */ approximateMessagesCount?: number; /** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */ requestId?: string; /** Indicates the version of the Queue service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */ version?: string; /** UTC date/time value generated by the service that indicates the time at which the response was initiated */ date?: Date; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; /** Error Code */ errorCode?: string; } /** Defines headers for Queue_getProperties operation. */ export interface QueueGetPropertiesExceptionHeaders { errorCode?: string; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; } /** Defines headers for Queue_setMetadata operation. */ export interface QueueSetMetadataHeaders { /** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */ requestId?: string; /** Indicates the version of the Queue service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */ version?: string; /** UTC date/time value generated by the service that indicates the time at which the response was initiated */ date?: Date; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; /** Error Code */ errorCode?: string; } /** Defines headers for Queue_setMetadata operation. */ export interface QueueSetMetadataExceptionHeaders { errorCode?: string; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; } /** Defines headers for Queue_getAccessPolicy operation. */ export interface QueueGetAccessPolicyHeaders { /** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */ requestId?: string; /** Indicates the version of the Queue service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */ version?: string; /** UTC date/time value generated by the service that indicates the time at which the response was initiated */ date?: Date; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; /** Error Code */ errorCode?: string; } /** Defines headers for Queue_getAccessPolicy operation. */ export interface QueueGetAccessPolicyExceptionHeaders { errorCode?: string; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; } /** Defines headers for Queue_setAccessPolicy operation. */ export interface QueueSetAccessPolicyHeaders { /** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */ requestId?: string; /** Indicates the version of the Queue service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */ version?: string; /** UTC date/time value generated by the service that indicates the time at which the response was initiated */ date?: Date; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; /** Error Code */ errorCode?: string; } /** Defines headers for Queue_setAccessPolicy operation. */ export interface QueueSetAccessPolicyExceptionHeaders { errorCode?: string; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; } /** Defines headers for Messages_dequeue operation. */ export interface MessagesDequeueHeaders { /** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */ requestId?: string; /** Indicates the version of the Queue service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */ version?: string; /** UTC date/time value generated by the service that indicates the time at which the response was initiated */ date?: Date; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; /** Error Code */ errorCode?: string; } /** Defines headers for Messages_dequeue operation. */ export interface MessagesDequeueExceptionHeaders { errorCode?: string; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; } /** Defines headers for Messages_clear operation. */ export interface MessagesClearHeaders { /** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */ requestId?: string; /** Indicates the version of the Queue service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */ version?: string; /** UTC date/time value generated by the service that indicates the time at which the response was initiated */ date?: Date; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; /** Error Code */ errorCode?: string; } /** Defines headers for Messages_clear operation. */ export interface MessagesClearExceptionHeaders { errorCode?: string; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; } /** Defines headers for Messages_enqueue operation. */ export interface MessagesEnqueueHeaders { /** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */ requestId?: string; /** Indicates the version of the Queue service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */ version?: string; /** UTC date/time value generated by the service that indicates the time at which the response was initiated */ date?: Date; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; /** Error Code */ errorCode?: string; } /** Defines headers for Messages_enqueue operation. */ export interface MessagesEnqueueExceptionHeaders { errorCode?: string; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; } /** Defines headers for Messages_peek operation. */ export interface MessagesPeekHeaders { /** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */ requestId?: string; /** Indicates the version of the Queue service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */ version?: string; /** UTC date/time value generated by the service that indicates the time at which the response was initiated */ date?: Date; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; /** Error Code */ errorCode?: string; } /** Defines headers for Messages_peek operation. */ export interface MessagesPeekExceptionHeaders { errorCode?: string; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; } /** Defines headers for MessageId_update operation. */ export interface MessageIdUpdateHeaders { /** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */ requestId?: string; /** Indicates the version of the Queue service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */ version?: string; /** UTC date/time value generated by the service that indicates the time at which the response was initiated */ date?: Date; /** The pop receipt of the queue message. */ popReceipt?: string; /** A UTC date/time value that represents when the message will be visible on the queue. */ nextVisibleOn?: Date; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; /** Error Code */ errorCode?: string; } /** Defines headers for MessageId_update operation. */ export interface MessageIdUpdateExceptionHeaders { errorCode?: string; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; } /** Defines headers for MessageId_delete operation. */ export interface MessageIdDeleteHeaders { /** This header uniquely identifies the request that was made and can be used for troubleshooting the request. */ requestId?: string; /** Indicates the version of the Queue service used to execute the request. This header is returned for requests made against version 2009-09-19 and above. */ version?: string; /** UTC date/time value generated by the service that indicates the time at which the response was initiated */ date?: Date; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; /** Error Code */ errorCode?: string; } /** Defines headers for MessageId_delete operation. */ export interface MessageIdDeleteExceptionHeaders { errorCode?: string; /** If a client request id header is sent in the request, this header will be present in the response with the same value. */ clientRequestId?: string; } /** Known values of {@link StorageErrorCode} that the service accepts. */ export const enum KnownStorageErrorCode { AccountAlreadyExists = "AccountAlreadyExists", AccountBeingCreated = "AccountBeingCreated", AccountIsDisabled = "AccountIsDisabled", AuthenticationFailed = "AuthenticationFailed", AuthorizationFailure = "AuthorizationFailure", ConditionHeadersNotSupported = "ConditionHeadersNotSupported", ConditionNotMet = "ConditionNotMet", EmptyMetadataKey = "EmptyMetadataKey", InsufficientAccountPermissions = "InsufficientAccountPermissions", InternalError = "InternalError", InvalidAuthenticationInfo = "InvalidAuthenticationInfo", InvalidHeaderValue = "InvalidHeaderValue", InvalidHttpVerb = "InvalidHttpVerb", InvalidInput = "InvalidInput", InvalidMd5 = "InvalidMd5", InvalidMetadata = "InvalidMetadata", InvalidQueryParameterValue = "InvalidQueryParameterValue", InvalidRange = "InvalidRange", InvalidResourceName = "InvalidResourceName", InvalidUri = "InvalidUri", InvalidXmlDocument = "InvalidXmlDocument", InvalidXmlNodeValue = "InvalidXmlNodeValue", Md5Mismatch = "Md5Mismatch", MetadataTooLarge = "MetadataTooLarge", MissingContentLengthHeader = "MissingContentLengthHeader", MissingRequiredQueryParameter = "MissingRequiredQueryParameter", MissingRequiredHeader = "MissingRequiredHeader", MissingRequiredXmlNode = "MissingRequiredXmlNode", MultipleConditionHeadersNotSupported = "MultipleConditionHeadersNotSupported", OperationTimedOut = "OperationTimedOut", OutOfRangeInput = "OutOfRangeInput", OutOfRangeQueryParameterValue = "OutOfRangeQueryParameterValue", RequestBodyTooLarge = "RequestBodyTooLarge", ResourceTypeMismatch = "ResourceTypeMismatch", RequestUrlFailedToParse = "RequestUrlFailedToParse", ResourceAlreadyExists = "ResourceAlreadyExists", ResourceNotFound = "ResourceNotFound", ServerBusy = "ServerBusy", UnsupportedHeader = "UnsupportedHeader", UnsupportedXmlNode = "UnsupportedXmlNode", UnsupportedQueryParameter = "UnsupportedQueryParameter", UnsupportedHttpVerb = "UnsupportedHttpVerb", InvalidMarker = "InvalidMarker", MessageNotFound = "MessageNotFound", MessageTooLarge = "MessageTooLarge", PopReceiptMismatch = "PopReceiptMismatch", QueueAlreadyExists = "QueueAlreadyExists", QueueBeingDeleted = "QueueBeingDeleted", QueueDisabled = "QueueDisabled", QueueNotEmpty = "QueueNotEmpty", QueueNotFound = "QueueNotFound", AuthorizationSourceIPMismatch = "AuthorizationSourceIPMismatch", AuthorizationProtocolMismatch = "AuthorizationProtocolMismatch", AuthorizationPermissionMismatch = "AuthorizationPermissionMismatch", AuthorizationServiceMismatch = "AuthorizationServiceMismatch", AuthorizationResourceTypeMismatch = "AuthorizationResourceTypeMismatch", FeatureVersionMismatch = "FeatureVersionMismatch" } /** * Defines values for StorageErrorCode. \ * {@link KnownStorageErrorCode} can be used interchangeably with StorageErrorCode, * this enum contains the known values that the service supports. * ### Know values supported by the service * **AccountAlreadyExists** \ * **AccountBeingCreated** \ * **AccountIsDisabled** \ * **AuthenticationFailed** \ * **AuthorizationFailure** \ * **ConditionHeadersNotSupported** \ * **ConditionNotMet** \ * **EmptyMetadataKey** \ * **InsufficientAccountPermissions** \ * **InternalError** \ * **InvalidAuthenticationInfo** \ * **InvalidHeaderValue** \ * **InvalidHttpVerb** \ * **InvalidInput** \ * **InvalidMd5** \ * **InvalidMetadata** \ * **InvalidQueryParameterValue** \ * **InvalidRange** \ * **InvalidResourceName** \ * **InvalidUri** \ * **InvalidXmlDocument** \ * **InvalidXmlNodeValue** \ * **Md5Mismatch** \ * **MetadataTooLarge** \ * **MissingContentLengthHeader** \ * **MissingRequiredQueryParameter** \ * **MissingRequiredHeader** \ * **MissingRequiredXmlNode** \ * **MultipleConditionHeadersNotSupported** \ * **OperationTimedOut** \ * **OutOfRangeInput** \ * **OutOfRangeQueryParameterValue** \ * **RequestBodyTooLarge** \ * **ResourceTypeMismatch** \ * **RequestUrlFailedToParse** \ * **ResourceAlreadyExists** \ * **ResourceNotFound** \ * **ServerBusy** \ * **UnsupportedHeader** \ * **UnsupportedXmlNode** \ * **UnsupportedQueryParameter** \ * **UnsupportedHttpVerb** \ * **InvalidMarker** \ * **MessageNotFound** \ * **MessageTooLarge** \ * **PopReceiptMismatch** \ * **QueueAlreadyExists** \ * **QueueBeingDeleted** \ * **QueueDisabled** \ * **QueueNotEmpty** \ * **QueueNotFound** \ * **AuthorizationSourceIPMismatch** \ * **AuthorizationProtocolMismatch** \ * **AuthorizationPermissionMismatch** \ * **AuthorizationServiceMismatch** \ * **AuthorizationResourceTypeMismatch** \ * **FeatureVersionMismatch** */ export type StorageErrorCode = string; /** Defines values for GeoReplicationStatusType. */ export type GeoReplicationStatusType = "live" | "bootstrap" | "unavailable"; /** Optional parameters. */ export interface ServiceSetPropertiesOptionalParams extends coreHttp.OperationOptions { /** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */ timeoutInSeconds?: number; /** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */ requestId?: string; } /** Contains response data for the setProperties operation. */ export type ServiceSetPropertiesResponse = ServiceSetPropertiesHeaders & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: ServiceSetPropertiesHeaders; }; }; /** Optional parameters. */ export interface ServiceGetPropertiesOptionalParams extends coreHttp.OperationOptions { /** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */ timeoutInSeconds?: number; /** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */ requestId?: string; } /** Contains response data for the getProperties operation. */ export type ServiceGetPropertiesResponse = ServiceGetPropertiesHeaders & QueueServiceProperties & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: QueueServiceProperties; /** The parsed HTTP response headers. */ parsedHeaders: ServiceGetPropertiesHeaders; }; }; /** Optional parameters. */ export interface ServiceGetStatisticsOptionalParams extends coreHttp.OperationOptions { /** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */ timeoutInSeconds?: number; /** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */ requestId?: string; } /** Contains response data for the getStatistics operation. */ export type ServiceGetStatisticsResponse = ServiceGetStatisticsHeaders & QueueServiceStatistics & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: QueueServiceStatistics; /** The parsed HTTP response headers. */ parsedHeaders: ServiceGetStatisticsHeaders; }; }; /** Optional parameters. */ export interface ServiceListQueuesSegmentOptionalParams extends coreHttp.OperationOptions { /** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */ timeoutInSeconds?: number; /** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */ requestId?: string; /** Filters the results to return only queues whose name begins with the specified prefix. */ prefix?: string; /** A string value that identifies the portion of the list of queues to be returned with the next listing operation. The operation returns the ContinuationToken value within the response body if the listing operation did not return all queues remaining to be listed with the current page. The NextMarker value can be used as the value for the marker parameter in a subsequent call to request the next page of list items. The marker value is opaque to the client. */ marker?: string; /** Specifies the maximum number of queues to return. If the request does not specify maxresults, or specifies a value greater than 5000, the server will return up to 5000 items. Note that if the listing operation crosses a partition boundary, then the service will return a continuation token for retrieving the remainder of the results. For this reason, it is possible that the service will return fewer results than specified by maxresults, or than the default of 5000. */ maxPageSize?: number; /** Include this parameter to specify that the queues' metadata be returned as part of the response body. */ include?: string[]; } /** Contains response data for the listQueuesSegment operation. */ export type ServiceListQueuesSegmentResponse = ServiceListQueuesSegmentHeaders & ListQueuesSegmentResponse & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: ListQueuesSegmentResponse; /** The parsed HTTP response headers. */ parsedHeaders: ServiceListQueuesSegmentHeaders; }; }; /** Optional parameters. */ export interface QueueCreateOptionalParams extends coreHttp.OperationOptions { /** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */ timeoutInSeconds?: number; /** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */ requestId?: string; /** Optional. Include this parameter to specify that the queue's metadata be returned as part of the response body. Note that metadata requested with this parameter must be stored in accordance with the naming restrictions imposed by the 2009-09-19 version of the Queue service. Beginning with this version, all metadata names must adhere to the naming conventions for C# identifiers. */ metadata?: { [propertyName: string]: string }; } /** Contains response data for the create operation. */ export type QueueCreateResponse = QueueCreateHeaders & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: QueueCreateHeaders; }; }; /** Optional parameters. */ export interface QueueDeleteOptionalParams extends coreHttp.OperationOptions { /** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */ timeoutInSeconds?: number; /** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */ requestId?: string; } /** Contains response data for the delete operation. */ export type QueueDeleteResponse = QueueDeleteHeaders & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: QueueDeleteHeaders; }; }; /** Optional parameters. */ export interface QueueGetPropertiesOptionalParams extends coreHttp.OperationOptions { /** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */ timeoutInSeconds?: number; /** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */ requestId?: string; } /** Contains response data for the getProperties operation. */ export type QueueGetPropertiesResponse = QueueGetPropertiesHeaders & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: QueueGetPropertiesHeaders; }; }; /** Optional parameters. */ export interface QueueSetMetadataOptionalParams extends coreHttp.OperationOptions { /** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */ timeoutInSeconds?: number; /** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */ requestId?: string; /** Optional. Include this parameter to specify that the queue's metadata be returned as part of the response body. Note that metadata requested with this parameter must be stored in accordance with the naming restrictions imposed by the 2009-09-19 version of the Queue service. Beginning with this version, all metadata names must adhere to the naming conventions for C# identifiers. */ metadata?: { [propertyName: string]: string }; } /** Contains response data for the setMetadata operation. */ export type QueueSetMetadataResponse = QueueSetMetadataHeaders & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: QueueSetMetadataHeaders; }; }; /** Optional parameters. */ export interface QueueGetAccessPolicyOptionalParams extends coreHttp.OperationOptions { /** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */ timeoutInSeconds?: number; /** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */ requestId?: string; } /** Contains response data for the getAccessPolicy operation. */ export type QueueGetAccessPolicyResponse = QueueGetAccessPolicyHeaders & SignedIdentifier[] & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: SignedIdentifier[]; /** The parsed HTTP response headers. */ parsedHeaders: QueueGetAccessPolicyHeaders; }; }; /** Optional parameters. */ export interface QueueSetAccessPolicyOptionalParams extends coreHttp.OperationOptions { /** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */ timeoutInSeconds?: number; /** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */ requestId?: string; /** the acls for the queue */ queueAcl?: SignedIdentifier[]; } /** Contains response data for the setAccessPolicy operation. */ export type QueueSetAccessPolicyResponse = QueueSetAccessPolicyHeaders & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: QueueSetAccessPolicyHeaders; }; }; /** Optional parameters. */ export interface MessagesDequeueOptionalParams extends coreHttp.OperationOptions { /** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */ timeoutInSeconds?: number; /** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */ requestId?: string; /** Optional. A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. If fewer are visible, the visible messages are returned. By default, a single message is retrieved from the queue with this operation. */ numberOfMessages?: number; /** Optional. Specifies the new visibility timeout value, in seconds, relative to server time. The default value is 30 seconds. A specified value must be larger than or equal to 1 second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol versions prior to version 2011-08-18. The visibility timeout of a message can be set to a value later than the expiry time. */ visibilityTimeout?: number; } /** Contains response data for the dequeue operation. */ export type MessagesDequeueResponse = MessagesDequeueHeaders & DequeuedMessageItem[] & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: DequeuedMessageItem[]; /** The parsed HTTP response headers. */ parsedHeaders: MessagesDequeueHeaders; }; }; /** Optional parameters. */ export interface MessagesClearOptionalParams extends coreHttp.OperationOptions { /** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */ timeoutInSeconds?: number; /** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */ requestId?: string; } /** Contains response data for the clear operation. */ export type MessagesClearResponse = MessagesClearHeaders & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: MessagesClearHeaders; }; }; /** Optional parameters. */ export interface MessagesEnqueueOptionalParams extends coreHttp.OperationOptions { /** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */ timeoutInSeconds?: number; /** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */ requestId?: string; /** Optional. If specified, the request must be made using an x-ms-version of 2011-08-18 or later. If not specified, the default value is 0. Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message cannot be set to a value later than the expiry time. visibilitytimeout should be set to a value smaller than the time-to-live value. */ visibilityTimeout?: number; /** Optional. Specifies the time-to-live interval for the message, in seconds. Prior to version 2017-07-29, the maximum time-to-live allowed is 7 days. For version 2017-07-29 or later, the maximum time-to-live can be any positive number, as well as -1 indicating that the message does not expire. If this parameter is omitted, the default time-to-live is 7 days. */ messageTimeToLive?: number; } /** Contains response data for the enqueue operation. */ export type MessagesEnqueueResponse = MessagesEnqueueHeaders & EnqueuedMessage[] & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: EnqueuedMessage[]; /** The parsed HTTP response headers. */ parsedHeaders: MessagesEnqueueHeaders; }; }; /** Optional parameters. */ export interface MessagesPeekOptionalParams extends coreHttp.OperationOptions { /** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */ timeoutInSeconds?: number; /** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */ requestId?: string; /** Optional. A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. If fewer are visible, the visible messages are returned. By default, a single message is retrieved from the queue with this operation. */ numberOfMessages?: number; } /** Contains response data for the peek operation. */ export type MessagesPeekResponse = MessagesPeekHeaders & PeekedMessageItem[] & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: PeekedMessageItem[]; /** The parsed HTTP response headers. */ parsedHeaders: MessagesPeekHeaders; }; }; /** Optional parameters. */ export interface MessageIdUpdateOptionalParams extends coreHttp.OperationOptions { /** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */ timeoutInSeconds?: number; /** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */ requestId?: string; /** A Message object which can be stored in a Queue */ queueMessage?: QueueMessage; } /** Contains response data for the update operation. */ export type MessageIdUpdateResponse = MessageIdUpdateHeaders & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: MessageIdUpdateHeaders; }; }; /** Optional parameters. */ export interface MessageIdDeleteOptionalParams extends coreHttp.OperationOptions { /** The The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting Timeouts for Queue Service Operations.</a> */ timeoutInSeconds?: number; /** Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. */ requestId?: string; } /** Contains response data for the delete operation. */ export type MessageIdDeleteResponse = MessageIdDeleteHeaders & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: MessageIdDeleteHeaders; }; }; /** Optional parameters. */ export interface StorageClientOptionalParams extends coreHttp.ServiceClientOptions { /** Specifies the version of the operation to use for this request. */ version?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
* @fileoverview Mappings for TeX parsing for the bussproofs package. * * @author v.sorge@mathjax.org (Volker Sorge) */ import {ParseMethod} from '../Types.js'; import TexError from '../TexError.js'; import TexParser from '../TexParser.js'; import ParseUtil from '../ParseUtil.js'; import {StackItem} from '../StackItem.js'; import {MmlNode} from '../../../core/MmlTree/MmlNode.js'; import * as BussproofsUtil from './BussproofsUtil.js'; // Namespace let BussproofsMethods: Record<string, ParseMethod> = {}; /** * Implements the proof tree environment. * @param {TexParser} parser The current parser. * @param {StackItem} begin The opening element of the environment. * @return {StackItem} The proof tree stackitem. */ // TODO: Error handling if we have leftover elements or elements are not in the // required order. BussproofsMethods.Prooftree = function(parser: TexParser, begin: StackItem): StackItem { parser.Push(begin); // TODO: Check if opening a proof tree is legal. let newItem = parser.itemFactory.create('proofTree'). setProperties({name: begin.getName(), line: 'solid', currentLine: 'solid', rootAtTop: false}); // parser.Push(item); return newItem; }; /** * Implements the Axiom command. * @param {TexParser} parser The current parser. * @param {string} name The name of the command. */ BussproofsMethods.Axiom = function(parser: TexParser, name: string) { let top = parser.stack.Top(); // TODO: Label error if (top.kind !== 'proofTree') { throw new TexError('IllegalProofCommand', 'Proof commands only allowed in prooftree environment.'); } let content = paddedContent(parser, parser.GetArgument(name)); BussproofsUtil.setProperty(content, 'axiom', true); top.Push(content); }; /** * Pads content of an inference rule. * @param {TexParser} parser The calling parser. * @param {string} content The content to be padded. * @return {MmlNode} The mrow element with padded content. */ const paddedContent = function(parser: TexParser, content: string): MmlNode { // Add padding on either site. let nodes = ParseUtil.internalMath(parser, ParseUtil.trimSpaces(content), 0); if (!nodes[0].childNodes[0].childNodes.length) { return parser.create('node', 'mrow', []); } let lpad = parser.create('node', 'mspace', [], {width: '.5ex'}); let rpad = parser.create('node', 'mspace', [], {width: '.5ex'}); return parser.create('node', 'mrow', [lpad, ...nodes, rpad]); }; /** * Implements the Inference rule commands. * @param {TexParser} parser The current parser. * @param {string} name The name of the command. * @param {number} n Number of premises for this inference rule. */ BussproofsMethods.Inference = function(parser: TexParser, name: string, n: number) { let top = parser.stack.Top(); if (top.kind !== 'proofTree') { throw new TexError('IllegalProofCommand', 'Proof commands only allowed in prooftree environment.'); } if (top.Size() < n) { throw new TexError('BadProofTree', 'Proof tree badly specified.'); } const rootAtTop = top.getProperty('rootAtTop') as boolean; const childCount = (n === 1 && !top.Peek()[0].childNodes.length) ? 0 : n; let children: MmlNode[] = []; do { if (children.length) { children.unshift(parser.create('node', 'mtd', [], {})); } children.unshift( parser.create('node', 'mtd', [top.Pop()], {'rowalign': (rootAtTop ? 'top' : 'bottom')})); n--; } while (n > 0); let row = parser.create('node', 'mtr', children, {}); let table = parser.create('node', 'mtable', [row], {framespacing: '0 0'}); let conclusion = paddedContent(parser, parser.GetArgument(name)); let style = top.getProperty('currentLine') as string; if (style !== top.getProperty('line')) { top.setProperty('currentLine', top.getProperty('line')); } let rule = createRule( parser, table, [conclusion], top.getProperty('left') as MmlNode, top.getProperty('right') as MmlNode, style, rootAtTop); top.setProperty('left', null); top.setProperty('right', null); BussproofsUtil.setProperty(rule, 'inference', childCount); parser.configuration.addNode('inference', rule); top.Push(rule); }; /** * Creates a ND style inference rule. * @param {TexParser} parser The calling parser. * @param {MmlNode} premise The premise (a single table). * @param {MmlNode[]} conclusions Elements that are combined into the conclusion. * @param {MmlNode|null} left The left label if it exists. * @param {MmlNode|null} right The right label if it exists. * @param {string} style Style of inference rule line. * @param {boolean} rootAtTop Direction of inference rule: true for root at top. */ function createRule(parser: TexParser, premise: MmlNode, conclusions: MmlNode[], left: MmlNode | null, right: MmlNode | null, style: string, rootAtTop: boolean) { const upper = parser.create( 'node', 'mtr', [parser.create('node', 'mtd', [premise], {})], {}); const lower = parser.create( 'node', 'mtr', [parser.create('node', 'mtd', conclusions, {})], {}); let rule = parser.create('node', 'mtable', rootAtTop ? [lower, upper] : [upper, lower], {align: 'top 2', rowlines: style, framespacing: '0 0'}); BussproofsUtil.setProperty(rule, 'inferenceRule', rootAtTop ? 'up' : 'down'); let leftLabel, rightLabel; if (left) { leftLabel = parser.create( 'node', 'mpadded', [left], {height: '+.5em', width: '+.5em', voffset: '-.15em'}); BussproofsUtil.setProperty(leftLabel, 'prooflabel', 'left'); } if (right) { rightLabel = parser.create( 'node', 'mpadded', [right], {height: '+.5em', width: '+.5em', voffset: '-.15em'}); BussproofsUtil.setProperty(rightLabel, 'prooflabel', 'right'); } let children, label; if (left && right) { children = [leftLabel, rule, rightLabel]; label = 'both'; } else if (left) { children = [leftLabel, rule]; label = 'left'; } else if (right) { children = [rule, rightLabel]; label = 'right'; } else { return rule; } rule = parser.create('node', 'mrow', children); BussproofsUtil.setProperty(rule, 'labelledRule', label); return rule; } /** * Implements the label command. * @param {TexParser} parser The current parser. * @param {string} name The name of the command. * @param {string} side The side of the label. */ BussproofsMethods.Label = function(parser: TexParser, name: string, side: string) { let top = parser.stack.Top(); // Label error if (top.kind !== 'proofTree') { throw new TexError('IllegalProofCommand', 'Proof commands only allowed in prooftree environment.'); } let content = ParseUtil.internalMath(parser, parser.GetArgument(name), 0); let label = (content.length > 1) ? parser.create('node', 'mrow', content, {}) : content[0]; top.setProperty(side, label); }; /** * Sets line style for inference rules. * @param {TexParser} parser The current parser. * @param {string} name The name of the command. * @param {string} style The line style to set. * @param {boolean} always Set as permanent style. */ BussproofsMethods.SetLine = function(parser: TexParser, _name: string, style: string, always: boolean) { let top = parser.stack.Top(); // Label error if (top.kind !== 'proofTree') { throw new TexError('IllegalProofCommand', 'Proof commands only allowed in prooftree environment.'); } top.setProperty('currentLine', style); if (always) { top.setProperty('line', style); } }; /** * Implements commands indicating where the root of the proof tree is. * @param {TexParser} parser The current parser. * @param {string} name The name of the command. * @param {string} where If true root is at top, otherwise at bottom. */ BussproofsMethods.RootAtTop = function(parser: TexParser, _name: string, where: boolean) { let top = parser.stack.Top(); if (top.kind !== 'proofTree') { throw new TexError('IllegalProofCommand', 'Proof commands only allowed in prooftree environment.'); } top.setProperty('rootAtTop', where); }; /** * Implements Axiom command for sequents. * @param {TexParser} parser The current parser. * @param {string} name The name of the command. */ BussproofsMethods.AxiomF = function(parser: TexParser, name: string) { let top = parser.stack.Top(); if (top.kind !== 'proofTree') { throw new TexError('IllegalProofCommand', 'Proof commands only allowed in prooftree environment.'); } let line = parseFCenterLine(parser, name); BussproofsUtil.setProperty(line, 'axiom', true); top.Push(line); }; /** * Parses a line with a sequent (i.e., one containing \\fcenter). * @param {TexParser} parser The current parser. * @param {string} name The name of the calling command. * @return {MmlNode} The parsed line. */ function parseFCenterLine(parser: TexParser, name: string): MmlNode { let dollar = parser.GetNext(); if (dollar !== '$') { throw new TexError('IllegalUseOfCommand', 'Use of %1 does not match it\'s definition.', name); } parser.i++; let axiom = parser.GetUpTo(name, '$'); if (axiom.indexOf('\\fCenter') === -1) { throw new TexError('IllegalUseOfCommand', 'Missing \\fCenter in %1.', name); } // Check for fCenter and throw error? let [prem, conc] = axiom.split('\\fCenter'); let premise = (new TexParser(prem, parser.stack.env, parser.configuration)).mml(); let conclusion = (new TexParser(conc, parser.stack.env, parser.configuration)).mml(); let fcenter = (new TexParser('\\fCenter', parser.stack.env, parser.configuration)).mml(); const left = parser.create('node', 'mtd', [premise], {}); const middle = parser.create('node', 'mtd', [fcenter], {}); const right = parser.create('node', 'mtd', [conclusion], {}); const row = parser.create('node', 'mtr', [left, middle, right], {}); const table = parser.create('node', 'mtable', [row], {columnspacing: '.5ex', columnalign: 'center 2'}); BussproofsUtil.setProperty(table, 'sequent', true); parser.configuration.addNode('sequent', row); return table; } /** * Placeholder for Fcenter macro that can be overwritten with renewcommand. * @param {TexParser} parser The current parser. * @param {string} name The name of the command. */ BussproofsMethods.FCenter = function(_parser: TexParser, _name: string) { }; /** * Implements inference rules for sequents. * @param {TexParser} parser The current parser. * @param {string} name The name of the command. * @param {number} n Number of premises for this inference rule. */ BussproofsMethods.InferenceF = function(parser: TexParser, name: string, n: number) { let top = parser.stack.Top(); if (top.kind !== 'proofTree') { throw new TexError('IllegalProofCommand', 'Proof commands only allowed in prooftree environment.'); } if (top.Size() < n) { throw new TexError('BadProofTree', 'Proof tree badly specified.'); } const rootAtTop = top.getProperty('rootAtTop') as boolean; const childCount = (n === 1 && !top.Peek()[0].childNodes.length) ? 0 : n; let children: MmlNode[] = []; do { if (children.length) { children.unshift(parser.create('node', 'mtd', [], {})); } children.unshift( parser.create('node', 'mtd', [top.Pop()], {'rowalign': (rootAtTop ? 'top' : 'bottom')})); n--; } while (n > 0); let row = parser.create('node', 'mtr', children, {}); let table = parser.create('node', 'mtable', [row], {framespacing: '0 0'}); let conclusion = parseFCenterLine(parser, name); // TODO: Padding let style = top.getProperty('currentLine') as string; if (style !== top.getProperty('line')) { top.setProperty('currentLine', top.getProperty('line')); } let rule = createRule( parser, table, [conclusion], top.getProperty('left') as MmlNode, top.getProperty('right') as MmlNode, style, rootAtTop); top.setProperty('left', null); top.setProperty('right', null); BussproofsUtil.setProperty(rule, 'inference', childCount); parser.configuration.addNode('inference', rule); top.Push(rule); }; export default BussproofsMethods;
the_stack
import { Map } from 'immutable'; import { NodeRecord, NestedNodeRecord } from '../../constants/flowdesigner.model'; import * as Node from './node'; import * as Position from '../position/position'; import * as Size from '../size/size'; const isNotNodeException = `NodeRecord should be a NodeRecord, was given """ object """ Map {} """`; const improperSizeMessage = `SizeRecord should be a SizeRecord, was given """ object """ Map { "width": 20, "height": 50 } """ you should use Size module functions to create and transform Size`; const improperPositionMessage = `PositionRecord should be a PositionRecord, was given """ object """ Map { "x": 10, "y": 10 } """ `; const protectedValueException = 'position is a protected value of the Node, please use getPosition setPosition from this module to make change on those values'; describe('isNodeElseThrow', () => { it('return true if parameter node is a NodeRecord', () => { // given const testNode = new NodeRecord(); // when const test = Node.isNodeElseThrow(testNode); // expect expect(test).toEqual(true); }); it('return true if parameter node is a NestedNodeRecord', () => { // given const testNode = new NestedNodeRecord(); // when const test = Node.isNodeElseThrow(testNode); // expect expect(test).toEqual(true); }); it('thow an error if parameter is not a NodeRecord', () => { // given const testNode = Map(); // when // expect expect(() => Node.isNodeElseThrow(testNode)).toThrow(isNotNodeException); }); }); describe('Node', () => { const id = 'ID'; const position = Position.create(10, 10); const size = Size.create(50, 80); const nodeType = 'NodeType'; const testNode = Node.create(id, position, size, nodeType); const key = 'KEY'; const value = { whatever: 'whatever' }; const improperId = 34; const improperPosition = Map({ x: 10, y: 10 }); const improperSize = Map({ width: 20, height: 50 }); const improperNodeType = {}; const improperNode = Map(); describe('create', () => { it('given proper id, position, size and componentType return a Node', () => { // given // when const test = Node.create(id, position, size, nodeType); // expect expect(Node.isNode(test)).toEqual(true); }); it('throw if given an improper id', () => { // given // when // expect expect(() => Node.create(improperId as any, position, size, nodeType)).toThrow( 'nodeId should be a string, was given 34', ); }); it('throw if given an improper Position', () => { // given // when // expect expect(() => Node.create(id, improperPosition, size, nodeType)).toThrow( improperPositionMessage, ); }); it('throw if given an improper Size', () => { // given // when // expect expect(() => Node.create(id, position, improperSize, nodeType)).toThrow( improperSizeMessage, ); }); it('throw if given an improper componentType', () => { // given // when // expect expect(() => Node.create(id, position, size, improperNodeType as any)).toThrow( 'nodeType should be a string, was given [object Object]', ); }); }); describe('isNode', () => { it('return true if parameter node is a NodeRecord', () => { // given // when const test = Node.isNode(testNode); // expect expect(test).toEqual(true); }); it('thow an error if parameter is not a NodeRecord', () => { // given // when const test = Node.isNode(improperNode); // expect expect(test).toEqual(false); }); }); describe('getId', () => { it('given a proper Node return an Id', () => { // given // when const test = Node.getId(testNode); // expect expect(test).toEqual(id); }); it('throw given an improper node', () => { expect(() => Node.getId(improperNode)).toThrow(isNotNodeException); }); }); describe('getPosition', () => { it('given a proper Node return a Position', () => { // given // when const test = Node.getPosition(testNode); // expect expect(test).toEqual(position); }); it('throw given an improper node', () => { expect(() => Node.getPosition(improperNode)).toThrow(isNotNodeException); }); }); describe('setPosition', () => { it('given a proper Node and Position return a Node with updated Position', () => { // given const newPosition = Position.create(100, 100); // when const test = Node.setPosition(newPosition, testNode); // expect expect(Node.getPosition(test)).toEqual(newPosition); }); it('throw given an improper Position', () => { // given // when // expect expect(() => Node.setPosition(improperPosition, testNode)) .toThrow(`PositionRecord should be a PositionRecord, was given """ object """ Map { "x": 10, "y": 10 } """ you should use Position module functions to create and transform Position`); }); it('throw given an improper Node', () => { // given // when // expect expect(() => Node.setPosition(position, improperNode)).toThrow(isNotNodeException); }); }); describe('getSize', () => { it('given a proper Node return a Size', () => { // given // when const test = Node.getSize(testNode); // expect expect(test).toEqual(size); }); it('throw given an improper node', () => { // given // when // expect expect(() => Node.getSize(improperNode)).toThrow(isNotNodeException); }); }); describe('setSize', () => { it('given a proper Node and Size return a Node with updated Size', () => { // given const newSize = Size.create(100, 100); // when const test = Node.setSize(newSize, testNode); // expect expect(Node.getSize(test)).toEqual(newSize); }); it('throw given an improper Size', () => { // given // when // expect expect(() => Node.setSize(improperSize, testNode)).toThrow(improperSizeMessage); }); it('throw given an improper Node', () => { // given // when // expect expect(() => Node.setSize(size, improperNode)).toThrow(isNotNodeException); }); }); describe('getComponentType', () => { it('given a proper Node return a ComponentType', () => { // given // when const test = Node.getComponentType(testNode); // expect expect(test).toEqual(nodeType); }); it('throw given an improper Link', () => { // given // when // expect expect(() => Node.getComponentType(improperNode)).toThrow(isNotNodeException); }); }); describe('setComponentType', () => { it('given a proper Node and ComponentType return a Node with updated ComponentType', () => { // given const newComponentType = 'squareOne'; // when const test = Node.setComponentType(newComponentType, testNode); // expect expect(Node.getComponentType(test)).toEqual(newComponentType); }); it('throw given an improper ComponentType', () => { // given const newComponentType = { type: 'squareOne' }; // when // expect expect(() => Node.setComponentType(newComponentType as any, testNode)).toThrow( 'nodeType should be a string, was given [object Object]', ); }); it('throw given an improper Node', () => { // given // when // expect expect(() => Node.setComponentType(nodeType, improperNode)).toThrow(isNotNodeException); }); }); describe('setData', () => { it('given a proper key, value and node return said node with the new key/value', () => { // given const newKey = 'newKey'; const newValue = 'newValue'; // when const test = Node.setData(newKey, newValue, testNode); // expect expect(Node.getData(newKey, test)).toEqual(newValue); }); it('throw given an improper key', () => { // given const improperKey = 8; // when // expect expect(() => Node.setData(improperKey as any, value, testNode)).toThrow( `key should be a string, was given ${ improperKey && improperKey.toString() } of type ${typeof improperKey}`, ); }); it('throw given an improper node', () => { // given // when // expect expect(() => Node.setData(key, value, improperNode)).toThrow(isNotNodeException); }); }); describe('getData', () => { it('given a proper key and node return value associated with the key', () => { // given const newKey = 'newKey'; const newValue = 'newValue'; const preparedNode = Node.setData(newKey, newValue, testNode); // when const test = Node.getData(newKey, preparedNode); // expect expect(test).toEqual(newValue); }); it('throw given an improper key', () => { // given const improperKey = 8; // when // expect expect(() => Node.getData(improperKey as any, testNode)).toThrow( `key should be a string, was given ${ improperKey && improperKey.toString() } of type ${typeof improperKey}`, ); }); it('throw given an improper node', () => { // given // when // expect expect(() => Node.getData(key, improperNode)).toThrow(isNotNodeException); }); }); describe('hasData', () => { it('given a proper key and node return true if key exist', () => { // given const newKey = 'newKey'; const newValue = 'newValue'; const preparedNode = Node.setData(newKey, newValue, testNode); // when const test = Node.hasData(newKey, preparedNode); // expect expect(test).toEqual(true); }); it('throw given an improper key', () => { // given const improperKey = 8; // when // expect expect(() => Node.hasData(improperKey as any, testNode)).toThrow( `key should be a string, was given ${ improperKey && improperKey.toString() } of type ${typeof improperKey}`, ); }); it('throw given an improper node', () => { // given // when // expect expect(() => Node.hasData(key, improperNode)).toThrow(isNotNodeException); }); }); describe('deleteData', () => { it('given a proper key and node return node without the key in data property if key exist', () => { // given const newKey = 'newKey'; const newValue = 'newValue'; const preparedNode = Node.setData(newKey, newValue, testNode); // when const test = Node.deleteData(newKey, preparedNode); // expect expect(Node.hasData(newKey, test)).toEqual(false); }); it('throw given an improper key', () => { // given const improperKey = 8; // when // expect expect(() => Node.deleteData(improperKey as any, testNode)).toThrow( `key should be a string, was given ${ improperKey && improperKey.toString() } of type ${typeof improperKey}`, ); }); it('throw given an improper node', () => { // given // when // expect expect(() => Node.deleteData(key, improperNode)).toThrow(isNotNodeException); }); }); describe('setGraphicalAttribute', () => { it('given a proper key, value and node return said node with the new key/value', () => { // given const newKey = 'newKey'; const newValue = 'newValue'; // when const test = Node.setGraphicalAttribute(newKey, newValue, testNode); // expect expect(Node.getGraphicalAttribute(newKey, test)).toEqual(newValue); }); it('throw given a key being part of FORBIDEN_GRAPHICAL_ATTRIBUTES', () => { // given const improperNewKey = 'position'; const newValue = 'newValue'; // when // expect expect(() => Node.setGraphicalAttribute(improperNewKey, newValue, testNode)).toThrow( protectedValueException, ); }); it('throw given an improper key', () => { // given const improperKey = 8; // when // expect expect(() => Node.setGraphicalAttribute(improperKey as any, value, testNode)).toThrow( `key should be a string, was given ${ improperKey && improperKey.toString() } of type ${typeof improperKey}`, ); }); it('throw given an improper node', () => { // given // when // expect expect(() => Node.setGraphicalAttribute(key, value, improperNode)).toThrow( isNotNodeException, ); }); }); describe('getGraphicalAttribute', () => { it('given a proper key and node return value associated with the key', () => { // given const newKey = 'newKey'; const newValue = 'newValue'; const preparedNode = Node.setGraphicalAttribute(newKey, newValue, testNode); // when const test = Node.getGraphicalAttribute(newKey, preparedNode); // expect expect(test).toEqual(newValue); }); it('throw given a key being part of FORBIDEN_GRAPHICAL_ATTRIBUTES', () => { // given const improperNewKey = 'position'; // when // expect expect(() => Node.getGraphicalAttribute(improperNewKey, testNode)).toThrow( protectedValueException, ); }); it('throw given an improper key', () => { // given const improperKey = 8; // when // expect expect(() => Node.getGraphicalAttribute(improperKey as any, testNode)).toThrow( `key should be a string, was given ${ improperKey && improperKey.toString() } of type ${typeof improperKey}`, ); }); it('throw given an improper node', () => { // given // when // expect expect(() => Node.getGraphicalAttribute(key, improperNode)).toThrow(isNotNodeException); }); }); describe('hasGraphicalAttribute', () => { it('given a proper key and node return true if key exist', () => { // given const newKey = 'newKey'; const newValue = 'newValue'; const preparedNode = Node.setGraphicalAttribute(newKey, newValue, testNode); // when const test = Node.hasGraphicalAttribute(newKey, preparedNode); // expect expect(test).toEqual(true); }); it('throw given a key being part of FORBIDEN_GRAPHICAL_ATTRIBUTES', () => { // given const improperKey = 'position'; // when // expect expect(() => Node.hasGraphicalAttribute(improperKey, testNode)).toThrow( protectedValueException, ); }); it('throw given an improper key', () => { // given const improperKey = 8; // when // expect expect(() => Node.hasGraphicalAttribute(improperKey as any, testNode)).toThrow( `key should be a string, was given ${ improperKey && improperKey.toString() } of type ${typeof improperKey}`, ); }); it('throw given an improper node', () => { // given // when // expect expect(() => Node.hasGraphicalAttribute(key, improperNode)).toThrow(isNotNodeException); }); }); describe('deleteGraphicalAttribute', () => { it('given a proper key and node return node without the key in data property if key exist', () => { // given const newKey = 'newKey'; const newValue = 'newValue'; const preparedNode = Node.setGraphicalAttribute(newKey, newValue, testNode); // when const test = Node.deleteGraphicalAttribute(newKey, preparedNode); // expect expect(Node.hasGraphicalAttribute(newKey, test)).toEqual(false); }); it('throw given a key being part of FORBIDEN_GRAPHICAL_ATTRIBUTES', () => { // given const improperKey = 'position'; // when // expect expect(() => Node.deleteGraphicalAttribute(improperKey, testNode)).toThrow( protectedValueException, ); }); it('throw given an improper key', () => { // given const improperKey = 8; // when // expect expect(() => Node.deleteGraphicalAttribute(improperKey as any, testNode)).toThrow( `key should be a string, was given ${ improperKey && improperKey.toString() } of type ${typeof improperKey}`, ); }); it('throw given an improper node', () => { // given // when // expect expect(() => Node.deleteGraphicalAttribute(key, improperNode)).toThrow( isNotNodeException, ); }); }); });
the_stack
import { promisify } from "util"; import * as fs from "fs"; import * as path from "path"; import * as should from "should"; import * as mocha from "mocha"; import { BinaryStream } from "node-opcua-binary-stream"; import { coerceLocalizedText, LocalizedText } from "node-opcua-data-model"; import { hexDump } from "node-opcua-debug"; import { DataTypeFactory, parameters } from "node-opcua-factory"; import { DataType, Variant, VariantArrayType } from "node-opcua-variant"; import { ExtensionObject } from "node-opcua-extension-object"; import { encode_decode_round_trip_test } from "node-opcua-packet-analyzer/test_helpers"; import { getOrCreateConstructor, parseBinaryXSDAsync } from ".."; import { MockProvider } from "./mock_id_provider"; const doDebug = false; const idProvider = new MockProvider(); // ts-lint:disable:no-string-literal describe("BSHA - Binary Schemas Helper 1", () => { let dataTypeFactory: DataTypeFactory; let old_schema_helpers_doDebug = false; before(async () => { const sample_file = path.join(__dirname, "fixtures/sample_type.xsd"); old_schema_helpers_doDebug = parameters.debugSchemaHelper; parameters.debugSchemaHelper = true; const sample = fs.readFileSync(sample_file, "ascii"); dataTypeFactory = new DataTypeFactory([]); await parseBinaryXSDAsync(sample, idProvider, dataTypeFactory); }); after(() => { parameters.debugSchemaHelper = old_schema_helpers_doDebug; }); it("BSH1 - should parse some structure types", async () => { dataTypeFactory.hasStructuredType("WorkOrderType").should.eql(true); }); it("BSH2 - should parse some enumerated types", async () => { dataTypeFactory.hasEnumeration("Priority").should.eql(true); }); it("BSH3 - should construct a dynamic object structure", () => { const WorkOrderType = getOrCreateConstructor("WorkOrderType", dataTypeFactory); const workOrderType = new WorkOrderType({ assetID: "AssetId1234", ID: "00000000-0000-0000-ABCD-000000000000", startTime: new Date(), statusComments: [ { actor: "Foo", comment: /* localized text*/ new LocalizedText({ text: "bar" }), timestamp: new Date() } ] }); workOrderType.assetID.should.eql("AssetId1234"); if (doDebug) { console.log(workOrderType.toString()); } encode_decode_round_trip_test(workOrderType, (stream: BinaryStream) => { if (doDebug) { console.log(hexDump(stream.buffer)); } stream.length.should.equal(66); }); }); it("BSH4 - should handle StructureWithOptionalFields - 1", () => { const StructureWithOptionalFields = getOrCreateConstructor("StructureWithOptionalFields", dataTypeFactory); const structureWithOptionalFields1 = new StructureWithOptionalFields({ mandatoryInt32: 42, mandatoryStringArray: ["a"] }); should(structureWithOptionalFields1.optionalInt32).eql(undefined); should(structureWithOptionalFields1.optionalStringArray).eql(undefined); if (doDebug) { console.log((StructureWithOptionalFields as any).schema); } encode_decode_round_trip_test(structureWithOptionalFields1, (buffer: Buffer) => { if (doDebug) { console.log(hexDump(buffer)); } // 32 bits (4) => bitfield buffer.readInt32LE(0).should.eql(0); // 32 bits (4) => mandatoryInt32 buffer.readInt32LE(4).should.eql(42); // 32 bits (4) => length mandatoryStringArray buffer.readInt32LE(8).should.eql(1); // 32 bits+1 (5) => element 1 buffer.readInt32LE(12).should.eql(1); buffer.length.should.equal(17, "expected stream length to be 17 bytes"); }); structureWithOptionalFields1.toJSON().should.eql({ mandatoryInt32: 42, mandatoryStringArray: ["a"] }); }); it("BSH5 - should handle StructureWithOptionalFields - 2", () => { const StructureWithOptionalFields = getOrCreateConstructor("StructureWithOptionalFields", dataTypeFactory); const structureWithOptionalFields2 = new StructureWithOptionalFields({ mandatoryInt32: 42, mandatoryStringArray: ["h"], optionalInt32: 43, optionalStringArray: ["a", "b"] }); encode_decode_round_trip_test(structureWithOptionalFields2, (buffer: Buffer) => { if (doDebug) { console.log(hexDump(buffer)); } // 32 bits (4) => bitfield buffer.readInt32LE(0).should.eql(3); // 32 bits (4) => mandatoryInt32 buffer.readInt32LE(4).should.eql(42); // 32 bits (4) => optionalInt32 buffer.readInt32LE(8).should.eql(43); // 32 bits (4) => length mandatoryStringArray // 32 bits+1 (5) => element 1 buffer.readInt32LE(12).should.eql(1); buffer.readInt32LE(16).should.eql(1); // 32 bits (4) => length optionalStringArray // 32 bits+1 (5) => element 2 buffer.readInt32LE(21).should.eql(2); buffer.readInt32LE(25).should.eql(1); // length of "a" buffer.readInt32LE(30).should.eql(1); // length of "b" buffer.length.should.equal(35); }); structureWithOptionalFields2.toJSON().should.eql({ mandatoryInt32: 42, mandatoryStringArray: ["h"], optionalInt32: 43, optionalStringArray: ["a", "b"] }); }); it("BSH6 - should handle StructureWithOptionalFields - 13 (all options fields missing)", () => { const StructWithOnlyOptionals = getOrCreateConstructor("StructWithOnlyOptionals", dataTypeFactory); const unionTest1 = new StructWithOnlyOptionals({ /* empty */ }); encode_decode_round_trip_test(unionTest1, (buffer: Buffer) => { buffer.length.should.eql(0); if (doDebug) { console.log("Buffer = ", hexDump(buffer)); } }); }); it("BSH7 - should handle StructureWithOptionalFields - 13 (one field missing)", () => { const StructWithOnlyOptionals = getOrCreateConstructor("StructWithOnlyOptionals", dataTypeFactory); const unionTest1 = new StructWithOnlyOptionals({ optionalStringArray: ["Hello", "World"] }); encode_decode_round_trip_test(unionTest1, (buffer: Buffer) => { buffer.length.should.eql(26); if (doDebug) { console.log("Buffer = ", hexDump(buffer)); } }); }); it("BSH8 - should handle StructureWithOptionalFields - 13 (one field missing 2)", () => { const StructWithOnlyOptionals = getOrCreateConstructor("StructWithOnlyOptionals", dataTypeFactory); const unionTest1 = new StructWithOnlyOptionals({ optionalInt32: 0 }); encode_decode_round_trip_test(unionTest1, (buffer: Buffer) => { buffer.length.should.eql(8); if (doDebug) { console.log("Buffer = ", hexDump(buffer)); } }); }); it("issue#982 - toJSON should not fail if one field is null", () => { const StructureWithOptionalFields = getOrCreateConstructor("StructureWithOptionalFields", dataTypeFactory); const structureWithOptionalFields2 = new StructureWithOptionalFields({ mandatoryInt32: 42, mandatoryStringArray: [null], optionalInt32: 43, optionalStringArray: [null, null] }); structureWithOptionalFields2.toJSON().should.eql({ mandatoryInt32: 42, mandatoryStringArray: [null], optionalInt32: 43, optionalStringArray: [null, null] }); const v = new Variant({ dataType: DataType.ExtensionObject, arrayType: VariantArrayType.Array, value: [null, structureWithOptionalFields2] }); v.toJSON().should.eql({ dataType: "ExtensionObject", arrayType: "Array", value: [ null, { mandatoryInt32: 42, optionalInt32: 43, mandatoryStringArray: [null], optionalStringArray: [null, null] } ] }); }); }); describe("BSHB - Binary Schemas Helper 2", () => { let dataTypeFactory: DataTypeFactory; let old_schema_helpers_doDebug = false; before(async () => { const sample_file = path.join(__dirname, "fixtures/sample_type1.xsd"); old_schema_helpers_doDebug = parameters.debugSchemaHelper; parameters.debugSchemaHelper = true; const sample = fs.readFileSync(sample_file, "ascii"); dataTypeFactory = new DataTypeFactory([]); await parseBinaryXSDAsync(sample, idProvider, dataTypeFactory); }); after(() => { parameters.debugSchemaHelper = old_schema_helpers_doDebug; }); it("BSHB1 - should parse some structure types", async () => { dataTypeFactory.hasStructuredType("SystemStateDescriptionDataType").should.eql(true); }); it("BSHB2 - should parse some enumerated types", async () => { dataTypeFactory.hasEnumeration("SystemStateDataType").should.eql(true); }); enum SystemStateEnum2 { PRD_1 = 1, SBY_2 = 2, ENG_3 = 3, SDT_4 = 4, UDT_5 = 5, NST_6 = 6 } it("BSHB3 - should construct a dynamic object structure 1", () => { const SystemStateDescriptionDataType = getOrCreateConstructor("SystemStateDescriptionDataType", dataTypeFactory); const SystemState = dataTypeFactory.getEnumeration("SystemStateDataType")!.enumValues as SystemStateEnum2; const systemStateDescription = new SystemStateDescriptionDataType({ state: SystemStateEnum2.ENG_3, stateDescription: "Hello" }); systemStateDescription.state.should.eql(SystemStateEnum2.ENG_3); encode_decode_round_trip_test(systemStateDescription, (buffer: Buffer) => { if (doDebug) { console.log(hexDump(buffer)); } // 32 bits (4) => bitfield // 32 bits (4) => state // 32 bits + 5 (9) => stateDescription with 5 letter buffer.length.should.equal(17); }); systemStateDescription.toJSON().should.eql({ state: SystemStateEnum2.ENG_3, stateDescription: "Hello" }); }); it("BSHB4 - should construct a dynamic object structure 2", () => { const SystemStateDescriptionDataType = getOrCreateConstructor("SystemStateDescriptionDataType", dataTypeFactory); const systemStateDescription = new SystemStateDescriptionDataType({ state: SystemStateEnum2.ENG_3 // not specified ( can be omitted ) stateDescription: undefined }); encode_decode_round_trip_test(systemStateDescription, (buffer: Buffer) => { // 32 bits => bitfield // 32 bits => state // 0 bits => stateDescription is missing buffer.length.should.equal(8); }); }); }); describe("BSHC - Binary Schemas Helper 3 (with bit fields)", () => { let dataTypeFactory: DataTypeFactory; let old_schema_helpers_doDebug = false; before(async () => { const sample_file = path.join(__dirname, "fixtures/sample_type2.xsd"); old_schema_helpers_doDebug = parameters.debugSchemaHelper; parameters.debugSchemaHelper = true; const sample = fs.readFileSync(sample_file, "ascii"); dataTypeFactory = new DataTypeFactory([]); await parseBinaryXSDAsync(sample, idProvider, dataTypeFactory); }); after(() => { parameters.debugSchemaHelper = old_schema_helpers_doDebug; }); it("BSHC1 - should parse ProcessingTimesDataType structure types", async () => { dataTypeFactory.hasStructuredType("ProcessingTimesDataType").should.eql(true); const ProcessingTimesDataType = dataTypeFactory.getStructuredTypeSchema("ProcessingTimesDataType"); ProcessingTimesDataType.name.should.eql("ProcessingTimesDataType"); }); it("BSHC2 - should construct a dynamic object structure ProcessingTimesDataType - 1", () => { interface ProcessingTimes extends ExtensionObject { startTime: Date; endTime: Date; acquisitionDuration?: number; processingDuration?: number; } const ProcessingTimesDataType = getOrCreateConstructor("ProcessingTimesDataType", dataTypeFactory); const refDate = new Date(Date.UTC(2020, 14, 2, 13, 0)).getTime(); const pojo = { endTime: new Date(refDate - 110), startTime: new Date(refDate - 150) }; const processingTimes: ProcessingTimes = new ProcessingTimesDataType(pojo); encode_decode_round_trip_test(processingTimes, (buffer: Buffer) => { if (doDebug) { console.log(hexDump(buffer)); } // 32 bits (4) => bitfield // 64 bits (8) => startTime // 64 bits (8) => endTime buffer.length.should.equal(20); }); processingTimes.toJSON().should.eql({ endTime: new Date(refDate - 110), startTime: new Date(refDate - 150) }); }); it("BSHC3 - should construct a dynamic object structure ProcessingTimesDataType - 2", () => { const ProcessingTimesDataType = getOrCreateConstructor("ProcessingTimesDataType", dataTypeFactory); const processingTimes = new ProcessingTimesDataType({ acquisitionDuration: 1000, endTime: new Date(Date.now() - 110), processingDuration: 500, startTime: new Date(Date.now() - 150) }); encode_decode_round_trip_test(processingTimes, (buffer: Buffer) => { // 32 bits (4) => bitfield // 64 bits (8) => startTime // 64 bits (8) => endTime // 64 bits (8) => acquisitionDuration // 64 bits (8) => processingDuration buffer.length.should.equal(36); }); }); it("BSHC4 - should construct a ConfigurationDataType - 1", () => { const ConfigurationDataType = getOrCreateConstructor("ConfigurationDataType", dataTypeFactory); const configuration = new ConfigurationDataType({ externalId: { id: "SomeID1", major: 1 }, internalId: { id: "SomeID2", major: 1, minor: 2, version: "Version1", description: coerceLocalizedText("Some description") }, lastModified: new Date(Date.now() - 1000), hasTransferableDataOnFile: undefined }); configuration.internalId.description.should.eql(coerceLocalizedText("Some description")); const reloaded = encode_decode_round_trip_test(configuration, (buffer: Buffer) => { buffer.length.should.eql(87); }); console.log(reloaded.toString()); console.log(reloaded.toJSON()); }); it("BSHC5 - should construct a ResultDataType - 1", () => { const ResultDataType = getOrCreateConstructor("ResultDataType", dataTypeFactory); const result = new ResultDataType({ resultContent: [new Variant({ dataType: DataType.Double, value: 1000 })] }); const reloaded = encode_decode_round_trip_test(result, (buffer: Buffer) => { buffer.length.should.eql(35); }); console.log(reloaded.toString()); console.log(reloaded.toJSON()); }); }); describe("BSHD - Binary Schemas Helper 4", () => { let dataTypeFactory: DataTypeFactory; let old_schema_helpers_doDebug = false; before(async () => { const sample_file = path.join(__dirname, "fixtures/sample_type3.xsd"); old_schema_helpers_doDebug = parameters.debugSchemaHelper; parameters.debugSchemaHelper = true; const sample = fs.readFileSync(sample_file, "ascii"); dataTypeFactory = new DataTypeFactory([]); await parseBinaryXSDAsync(sample, idProvider, dataTypeFactory); }); after(() => { parameters.debugSchemaHelper = old_schema_helpers_doDebug; }); it("BSHD1 - should parse NodeIdType structure types", async () => { dataTypeFactory.hasStructuredType("NodeId").should.eql(true); }); it("BSHD2 - should construct a dynamic object structure ProcessingTimesDataType - 1", () => { // }); }); describe("BSHE - Binary Schemas Helper 5 (Union)", () => { let dataTypeFactory: DataTypeFactory; let old_schema_helpers_doDebug = false; before(async () => { const sample_file = path.join(__dirname, "fixtures/sample_type4.xsd"); old_schema_helpers_doDebug = parameters.debugSchemaHelper; parameters.debugSchemaHelper = true; const sample = fs.readFileSync(sample_file, "ascii"); dataTypeFactory = new DataTypeFactory([]); await parseBinaryXSDAsync(sample, idProvider, dataTypeFactory); }); after(() => { parameters.debugSchemaHelper = old_schema_helpers_doDebug; }); it("BSHE1 - should parse ScanData union", async () => { const ScanData = getOrCreateConstructor("ScanData", dataTypeFactory); const scanData2a = new ScanData({ byteString: Buffer.allocUnsafe(10) }); const scanData2b = new ScanData({ switchField: 1, byteString: Buffer.allocUnsafe(10) }); const reloaded2b = encode_decode_round_trip_test(scanData2b, (buffer: Buffer) => { buffer.length.should.eql(4 + 4 + 10); }); const scanData4a = new ScanData({ string: "Hello" }); const reloaded4a = encode_decode_round_trip_test(scanData4a, (buffer: Buffer) => { buffer.length.should.eql(4 + 4 + 5); }); const scanData4b = new ScanData({ switchField: 2, string: "Hello" }); const reloaded4b = encode_decode_round_trip_test(scanData4b, (buffer: Buffer) => { buffer.length.should.eql(4 + 4 + 5); }); const scanData5a = new ScanData({ string: "36" }); const reloaded5a = encode_decode_round_trip_test(scanData5a, (buffer: Buffer) => { buffer.length.should.eql(10); }); const scanData5b = new ScanData({ switchField: 3, value: 36 }); const reloaded5b = encode_decode_round_trip_test(scanData5b, (buffer: Buffer) => { buffer.length.should.eql(8); }); const scanData6a = new ScanData({ custom: { dataType: "Double", value: 36 } }); const scanData6b = new ScanData({ switchField: 4, custom: { dataType: "Double", value: 36 } }); const reloaded6b = encode_decode_round_trip_test(scanData6b, (buffer: Buffer) => { // buffer.length.should.eql(35); }); console.log(reloaded6b.toString()); reloaded6b.switchField.should.eql(4); reloaded6b.custom.dataType.should.eql(DataType.Double); reloaded6b.custom.value.should.eql(36); const scanData1 = new ScanData({}); // should throw const reloaded1 = encode_decode_round_trip_test(scanData1, (buffer: Buffer) => { buffer.length.should.eql(4); }); }); it("BSHE2 - should parse MyScanResult structure types", async () => { dataTypeFactory.hasStructuredType("MyScanResult").should.eql(true); const MyScanResult = getOrCreateConstructor("MyScanResult", dataTypeFactory); const result = new MyScanResult({ scanData: { string: "36" } }); const reloaded = encode_decode_round_trip_test(result, (buffer: Buffer) => { // buffer.length.should.eql(35); }); console.log(reloaded.toString()); // xx console.log(reloaded.toJSON()); }); it("BSHE3 - should construct a dynamic object structure ProcessingTimesDataType - 1", () => { /* */ }); }); describe("BSSGF - Binary Schemas Helper 5 (DerivedType -1)", () => { let dataTypeFactory: DataTypeFactory; let old_schema_helpers_doDebug = false; before(async () => { const sample_file = path.join(__dirname, "fixtures/sample_type5.xsd"); old_schema_helpers_doDebug = parameters.debugSchemaHelper; parameters.debugSchemaHelper = true; const sample = fs.readFileSync(sample_file, "ascii"); dataTypeFactory = new DataTypeFactory([]); await parseBinaryXSDAsync(sample, idProvider, dataTypeFactory); }); after(() => { parameters.debugSchemaHelper = old_schema_helpers_doDebug; }); it("BSHF1 - should handle RecipeIdExternalDataType", async () => { const RecipeIdExternalDataType = getOrCreateConstructor("RecipeIdExternalDataType", dataTypeFactory); const data = new RecipeIdExternalDataType({ id: "Id", hash: Buffer.alloc(10) }); const reloadedData = encode_decode_round_trip_test(data, (buffer: Buffer) => { buffer.length.should.eql(4 /* optionalBit*/ + 4 + 4 + 2 + 10); }); console.log(reloadedData.toJSON()); }); }); describe("BSHG - Binary Schema Helper 6 - Milo", () => { let dataTypeFactory: DataTypeFactory; let old_schema_helpers_doDebug = false; before(async () => { const sample_file = path.join(__dirname, "fixtures/sample_milo.xsd"); old_schema_helpers_doDebug = parameters.debugSchemaHelper; parameters.debugSchemaHelper = true; const sample = fs.readFileSync(sample_file, "ascii"); dataTypeFactory = new DataTypeFactory([]); await parseBinaryXSDAsync(sample, idProvider, dataTypeFactory); }); after(() => { parameters.debugSchemaHelper = old_schema_helpers_doDebug; }); it("BSHG-1 - should handle CustomUnionType", async () => { const CustomUnionType = getOrCreateConstructor("CustomUnionType", dataTypeFactory); const data1 = new CustomUnionType({ foo: 42 }); const reloadedData1 = encode_decode_round_trip_test(data1, (buffer: Buffer) => { buffer.length.should.eql(4 /* optionalBit*/ + 4 /* UInt32 */); const stream = new BinaryStream(buffer); stream.readUInt32().should.eql(0x0001); stream.readUInt32().should.eql(42); }); console.log(reloadedData1.toJSON()); const data2 = new CustomUnionType({ bar: "Hello" }); const reloadedData2 = encode_decode_round_trip_test(data2, (buffer: Buffer) => { buffer.length.should.eql(4 /* optionalBit*/ + 4 /* string length*/ + 5 /* Hello*/); }); console.log(reloadedData1.toJSON()); }); });
the_stack
import assert from "assert"; import testHelpers from "../../../test/helpers"; import newScheduleGood from "./newScheduleGood"; import { g, helpers } from "../../util"; import range from "lodash-es/range"; describe("worker/core/season/newScheduleGood", () => { let defaultTeams: { seasonAttrs: { cid: number; did: number; }; tid: number; }[]; beforeAll(() => { defaultTeams = helpers.getTeamsDefault().map(t => ({ // Don't need tid to start at 0, could be disabled teams! tid: t.tid + 2, seasonAttrs: { cid: t.cid, did: t.did, }, })); }); describe("old basketball tests", () => { beforeAll(() => { testHelpers.resetG(); g.setWithoutSavingToDB("allStarGame", null); }); test("schedule 1230 games (82 each for 30 teams)", () => { const { tids, warning } = newScheduleGood(defaultTeams); assert.strictEqual(warning, undefined); assert.strictEqual(tids.length, 1230); }); test("schedule 41 home games and 41 away games for each team", () => { const { tids, warning } = newScheduleGood(defaultTeams); assert.strictEqual(warning, undefined); const home: Record<number, number> = {}; // Number of home games for each team const away: Record<number, number> = {}; // Number of away games for each team for (let i = 0; i < tids.length; i++) { if (home[tids[i][0]] === undefined) { home[tids[i][0]] = 0; } if (away[tids[i][1]] === undefined) { away[tids[i][1]] = 0; } home[tids[i][0]] += 1; away[tids[i][1]] += 1; } assert.strictEqual(Object.keys(home).length, defaultTeams.length); for (const numGames of [...Object.values(home), ...Object.values(away)]) { assert.strictEqual(numGames, 41); } }); test("schedule each team one home game against every team in the other conference", () => { const { tids, warning } = newScheduleGood(defaultTeams); assert.strictEqual(warning, undefined); // Each element in this object is an object representing the number of home games against each other team (only the ones in the other conference will be populated) const home: Record<number, Record<number, number>> = {}; for (let i = 0; i < tids.length; i++) { const t0 = defaultTeams.find(t => t.tid === tids[i][0]); const t1 = defaultTeams.find(t => t.tid === tids[i][1]); if (!t0 || !t1) { console.log(tids[i]); throw new Error("Team not found"); } if (t0.seasonAttrs.cid !== t1.seasonAttrs.cid) { if (home[tids[i][1]] === undefined) { home[tids[i][1]] = {}; } if (home[tids[i][1]][tids[i][0]] === undefined) { home[tids[i][1]][tids[i][0]] = 0; } home[tids[i][1]][tids[i][0]] += 1; } } assert.strictEqual(Object.keys(home).length, defaultTeams.length); for (const { tid } of defaultTeams) { assert.strictEqual(Object.values(home[tid]).length, 15); assert.strictEqual( testHelpers.numInArrayEqualTo(Object.values(home[tid]), 1), 15, ); } }); test("schedule each team two home games against every team in the same division", () => { const { tids, warning } = newScheduleGood(defaultTeams); assert.strictEqual(warning, undefined); // Each element in this object is an object representing the number of home games against each other team (only the ones in the same division will be populated) const home: Record<number, Record<number, number>> = {}; for (let i = 0; i < tids.length; i++) { const t0 = defaultTeams.find(t => t.tid === tids[i][0]); const t1 = defaultTeams.find(t => t.tid === tids[i][1]); if (!t0 || !t1) { console.log(tids[i]); throw new Error("Team not found"); } if (t0.seasonAttrs.did === t1.seasonAttrs.did) { if (home[tids[i][1]] === undefined) { home[tids[i][1]] = {}; } if (home[tids[i][1]][tids[i][0]] === undefined) { home[tids[i][1]][tids[i][0]] = 0; } home[tids[i][1]][tids[i][0]] += 1; } } assert.strictEqual(Object.keys(home).length, defaultTeams.length); for (const { tid } of defaultTeams) { assert.strictEqual(Object.values(home[tid]).length, 4); assert.strictEqual( testHelpers.numInArrayEqualTo(Object.values(home[tid]), 2), 4, ); } }); test.skip("schedule each team one or two home games against every team in the same conference but not in the same division (one game: 2/10 teams; two games: 8/10 teams)", () => { const { tids, warning } = newScheduleGood(defaultTeams); assert.strictEqual(warning, undefined); // Each element in this object is an object representing the number of home games against each other team (only the ones in the same conference but different division will be populated) const home: Record<number, Record<number, number>> = {}; for (let i = 0; i < tids.length; i++) { const t0 = defaultTeams.find(t => t.tid === tids[i][0]); const t1 = defaultTeams.find(t => t.tid === tids[i][1]); if (!t0 || !t1) { console.log(tids[i]); throw new Error("Team not found"); } if ( t0.seasonAttrs.cid === t1.seasonAttrs.cid && t0.seasonAttrs.did !== t1.seasonAttrs.did ) { if (home[tids[i][1]] === undefined) { home[tids[i][1]] = {}; } if (home[tids[i][1]][tids[i][0]] === undefined) { home[tids[i][1]][tids[i][0]] = 0; } home[tids[i][1]][tids[i][0]] += 1; } } assert.strictEqual(Object.keys(home).length, defaultTeams.length); for (const { tid } of defaultTeams) { console.log(tid, Object.values(home[tid])); assert.strictEqual(Object.values(home[tid]).length, 10); assert.strictEqual( testHelpers.numInArrayEqualTo(Object.values(home[tid]), 1), 2, ); assert.strictEqual( testHelpers.numInArrayEqualTo(Object.values(home[tid]), 2), 8, ); } }); }); describe("old newScheduleCrappy tests", () => { const makeTeams = (numTeams: number) => { return range(numTeams).map(tid => ({ // Don't need tid to start at 0, could be disabled teams! tid: 5 + tid, seasonAttrs: { did: 0, cid: 0, }, })); }; beforeEach(() => { testHelpers.resetG(); g.setWithoutSavingToDB("allStarGame", null); }); test("when numTeams*numGames is even, everyone gets a full schedule", () => { for (let numGames = 2; numGames < 50; numGames += 1) { for (let numTeams = 2; numTeams < 50; numTeams += 1) { if ((numTeams * numGames) % 2 === 1) { continue; } g.setWithoutSavingToDB("numGames", numGames); const teams = makeTeams(numTeams); const { tids: matchups } = newScheduleGood(teams); // Total number of games assert.strictEqual( matchups.length * 2, numGames * numTeams, `Total number of games is wrong for ${numTeams} teams and ${numGames} games`, ); // Number of games for each teams const tids = matchups.flat(); for (const t of teams) { const count = tids.filter(tid => t.tid === tid).length; assert.strictEqual(count, numGames); } } } }); test("when numTeams*numGames is odd, one team is a game short", () => { for (let numGames = 2; numGames < 50; numGames += 1) { for (let numTeams = 2; numTeams < 50; numTeams += 1) { if ((numTeams * numGames) % 2 === 0) { continue; } g.setWithoutSavingToDB("numGames", numGames); const teams = makeTeams(numTeams); const { tids: matchups } = newScheduleGood(teams); // Total number of games assert.strictEqual( matchups.length, (numGames * numTeams - 1) / 2, `Total number of games is wrong for ${numTeams} teams and ${numGames} games`, ); // Number of games for each teams const tids = matchups.flat(); let oneShort = false; for (const t of teams) { const count = tids.filter(tid => t.tid === tid).length; if (count + 1 === numGames) { if (oneShort) { throw new Error("Two teams are one game short"); } oneShort = true; } else { assert.strictEqual(count, numGames); } } assert( oneShort, `Did not find team with one game short for ${numTeams} teams and ${numGames} games`, ); } } }); test("when numGames is even and there are enough games, everyone gets even home and away games", () => { for (let numGames = 20; numGames < 50; numGames += 1) { if (numGames % 2 === 1) { continue; } for (let numTeams = 2; numTeams < 25; numTeams += 1) { g.setWithoutSavingToDB("numGames", numGames); const teams = makeTeams(numTeams); const { tids: matchups } = newScheduleGood(teams); // Total number of games assert.strictEqual( matchups.length * 2, numGames * numTeams, "Total number of games is wrong", ); const home: Record<number, number> = {}; // Number of home games for each team const away: Record<number, number> = {}; // Number of away games for each team for (let i = 0; i < matchups.length; i++) { if (home[matchups[i][0]] === undefined) { home[matchups[i][0]] = 0; } if (away[matchups[i][1]] === undefined) { away[matchups[i][1]] = 0; } home[matchups[i][0]] += 1; away[matchups[i][1]] += 1; } for (const t of teams) { assert.strictEqual(home[t.tid], numGames / 2); assert.strictEqual(away[t.tid], numGames / 2); } } } }); }); describe("error handling", () => { test("warning if cannot make a full schedule due to there not being enough non-conference games", () => { testHelpers.resetG(); g.setWithoutSavingToDB("numGamesDiv", 2); g.setWithoutSavingToDB("numGamesConf", 2); g.setWithoutSavingToDB( "divs", g.get("divs").map(div => ({ ...div, cid: 0, })), ); g.setWithoutSavingToDB( "confs", g.get("confs").filter(conf => conf.cid === 0), ); const { tids, warning } = newScheduleGood( defaultTeams.map(t => ({ ...t, seasonAttrs: { cid: 0, did: t.seasonAttrs.did, }, })), ); assert.strictEqual(tids.length, 1230); assert.strictEqual(typeof warning, "string"); }); }); describe("random test cases", () => { beforeEach(() => { testHelpers.resetG(); }); test("4 games, null div, 2 conf", () => { // Test many times to make sure it doesn't intermittently skip a game due to faulty numGames*numTeams odd detection for (let i = 0; i < 100; i++) { const { tids, warning } = newScheduleGood(defaultTeams, { divs: g.get("divs"), numGames: 4, numGamesDiv: null, numGamesConf: 2, }); if (tids.length < 60) { const counts: Record<number, number> = {}; for (const matchup of tids) { for (const tid of matchup) { if (counts[tid] === undefined) { counts[tid] = 0; } counts[tid] += 1; } } for (const [tid, count] of Object.entries(counts)) { if (count < 4) { console.log("tid", tid, "count", count); console.log(defaultTeams.find(t => t.tid === parseInt(tid))); } } console.log("tids.length", tids.length); } assert.strictEqual(tids.length, 60); assert.strictEqual(warning, undefined); } }); // There are 15 teams in the conference, so they can't all get exactly one conference game. Needs to handle the 2 teams that have a missed conference game. test("4 games, null div, 1 conf", () => { const { tids, warning } = newScheduleGood(defaultTeams, { divs: g.get("divs"), numGames: 4, numGamesDiv: null, numGamesConf: 1, }); assert.strictEqual(tids.length, 60); assert.strictEqual(warning, undefined); }); test("82 games, 65 div, 17 conf", () => { const { tids, warning } = newScheduleGood(defaultTeams, { divs: g.get("divs"), numGames: 82, numGamesDiv: 65, numGamesConf: 17, }); assert.strictEqual(tids.length, 1230); assert.strictEqual(warning, undefined); }); // the conf with the new team thinks "i can get all my non-conf games with even home/away matchups, 0 excess games!". the conf without the new team thinks "i can play each team once, and then need 14 excess matchups (16+14)". but there are no games available for excess matchups, since the other conf has no excess test.skip("one expansion team", () => { const { tids, warning } = newScheduleGood([ ...defaultTeams, { tid: defaultTeams.at(-1)!.tid + 1, seasonAttrs: { cid: 0, did: 0, }, }, ]); console.log("warning", warning, tids.length); assert.strictEqual(tids.length, 1271); assert.strictEqual(warning, undefined); }); test("numGamesDiv null should roll up to conf not other", () => { const numGames = 29; // 1 for each other team const { tids, warning } = newScheduleGood(defaultTeams, { divs: g.get("divs"), numGames, numGamesDiv: null, numGamesConf: 14, // 1 for each other team }); assert.strictEqual(tids.length, (numGames * defaultTeams.length) / 2); assert.strictEqual(warning, undefined); // Should be one game for each matchup, no dupes const seen = new Set(); for (const matchup of tids) { const key = JSON.stringify([...matchup].sort()); if (seen.has(key)) { throw new Error(`Dupe matchup: ${key}`); } seen.add(key); } }); test("tons of games", () => { const numGames = 820; const { tids, warning } = newScheduleGood(defaultTeams, { divs: g.get("divs"), numGames, numGamesDiv: 160, numGamesConf: 360, }); assert.strictEqual(tids.length, (numGames * defaultTeams.length) / 2); assert.strictEqual(warning, undefined); }); test("odd numGamesConf*numTeamsConf, so some team needs to play an extra non-conf game", () => { const teams = defaultTeams.slice(0, 10).map((t, i) => ({ ...t, seasonAttrs: { ...t.seasonAttrs, cid: i < 5 ? 0 : 1, did: i < 5 ? 0 : 1, }, })); const divs = [ { did: 0, cid: 0, name: "Div1", }, { did: 1, cid: 1, name: "Div2", }, ]; const { tids, warning } = newScheduleGood(teams, { divs, numGames: 13, numGamesDiv: null, numGamesConf: 9, }); assert.strictEqual(tids.length, 65); assert.strictEqual(warning, undefined); }); }); });
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormRTV { interface tab__8B74A7E7_5EDB_4A59_9B52_77FBD784E116_Sections { _7E0518DA_7EF7_44EE_922D_7BB9472EB9EF: DevKit.Controls.Section; _8B74A7E7_5EDB_4A59_9B52_77FBD784E116_SECTION_2: DevKit.Controls.Section; } interface tab_rtvproductstab_Sections { tab_3_section_1: DevKit.Controls.Section; } interface tab__8B74A7E7_5EDB_4A59_9B52_77FBD784E116 extends DevKit.Controls.ITab { Section: tab__8B74A7E7_5EDB_4A59_9B52_77FBD784E116_Sections; } interface tab_rtvproductstab extends DevKit.Controls.ITab { Section: tab_rtvproductstab_Sections; } interface Tabs { _8B74A7E7_5EDB_4A59_9B52_77FBD784E116: tab__8B74A7E7_5EDB_4A59_9B52_77FBD784E116; rtvproductstab: tab_rtvproductstab; } interface Body { Tab: Tabs; /** Shows the unique number for identifying this RTV record. */ msdyn_name: DevKit.Controls.String; /** Originating RMA if items were returned from customer */ msdyn_OriginatingRMA: DevKit.Controls.Lookup; /** RTV Substatus */ msdyn_SubStatus: DevKit.Controls.Lookup; /** Enter the current status of the RTV. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; /** Shows the total Amount to be credited on this RTV. */ msdyn_TotalAmount: DevKit.Controls.Money; /** Vendor where items will be returned */ msdyn_Vendor: DevKit.Controls.Lookup; /** Contact person at Vendor */ msdyn_VendorContact: DevKit.Controls.Lookup; notescontrol: DevKit.Controls.Note; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.Controls.Lookup; } interface Footer extends DevKit.Controls.IFooter { /** Status of the RTV */ statecode: DevKit.Controls.OptionSet; } interface Navigation { nav_msdyn_msdyn_rtv_msdyn_rmareceiptproduct_RTV: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_rtv_msdyn_rtvproduct_RTV: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem } interface Grid { rtvproductsgrid: DevKit.Controls.Grid; } } class FormRTV extends DevKit.IForm { /** * DynamicsCrm.DevKit form RTV * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form RTV */ Body: DevKit.FormRTV.Body; /** The Footer section of form RTV */ Footer: DevKit.FormRTV.Footer; /** The Navigation of form RTV */ Navigation: DevKit.FormRTV.Navigation; /** The Grid of form RTV */ Grid: DevKit.FormRTV.Grid; } class msdyn_rtvApi { /** * DynamicsCrm.DevKit msdyn_rtvApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Shows the exchange rate for the currency associated with the entity with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Shows the sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; msdyn_Address1: DevKit.WebApi.StringValue; msdyn_Address2: DevKit.WebApi.StringValue; msdyn_Address3: DevKit.WebApi.StringValue; /** The user who approved or rejected this return */ msdyn_ApprovedDeclinedBy: DevKit.WebApi.LookupValue; /** Internal field used to generate the next name upon entity creation. It is optionally copied to the msdyn_name field. */ msdyn_AutoNumbering: DevKit.WebApi.StringValue; /** Unique identifier for Resource Booking associated with RTV. */ msdyn_Booking: DevKit.WebApi.LookupValue; msdyn_City: DevKit.WebApi.StringValue; msdyn_Country: DevKit.WebApi.StringValue; msdyn_Latitude: DevKit.WebApi.DoubleValue; msdyn_Longitude: DevKit.WebApi.DoubleValue; /** Shows the unique number for identifying this RTV record. */ msdyn_name: DevKit.WebApi.StringValue; /** Purchase Order from where items are originating */ msdyn_OriginalPurchaseOrder: DevKit.WebApi.LookupValue; /** Originating RMA if items were returned from customer */ msdyn_OriginatingRMA: DevKit.WebApi.LookupValue; msdyn_PostalCode: DevKit.WebApi.StringValue; msdyn_ReferenceNo: DevKit.WebApi.StringValue; /** Enter the date when return was requested. */ msdyn_RequestDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the date items were returned to vendor. */ msdyn_ReturnDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** User processing this return */ msdyn_ReturnedBy: DevKit.WebApi.LookupValue; /** Shows the entity instances. */ msdyn_rtvId: DevKit.WebApi.GuidValue; /** Method of Shipment to Vendor */ msdyn_ShipVia: DevKit.WebApi.LookupValue; msdyn_StateOrProvince: DevKit.WebApi.StringValue; /** RTV Substatus */ msdyn_SubStatus: DevKit.WebApi.LookupValue; /** Enter the current status of the RTV. */ msdyn_SystemStatus: DevKit.WebApi.OptionSetValue; /** Tax code vendor charges you */ msdyn_TaxCode: DevKit.WebApi.LookupValue; /** Shows the total Amount to be credited on this RTV. */ msdyn_TotalAmount: DevKit.WebApi.MoneyValue; /** Shows the value of the total amount in the base currency. */ msdyn_totalamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Vendor where items will be returned */ msdyn_Vendor: DevKit.WebApi.LookupValue; /** Contact person at Vendor */ msdyn_VendorContact: DevKit.WebApi.LookupValue; /** RMA from Vendor */ msdyn_VendorRMA: DevKit.WebApi.StringValue; /** Unique identifier for Work Order associated with RTV. */ msdyn_WorkOrder: DevKit.WebApi.LookupValue; /** Shows the date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Status of the RTV */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the RTV */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** Shows the time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyn_rtv { enum msdyn_SystemStatus { /** 690970001 */ Approved, /** 690970004 */ Canceled, /** 690970000 */ Draft, /** 690970003 */ Received, /** 690970002 */ Shipped } enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['RTV'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import * as router from "./router" // tslint:disable-next-line declare namespace hyperdom { export interface VdomFragment { children: any[] } abstract class HyperdomComponent { public refreshImmediately (): void public refreshComponent (): void public refresh (): void } export abstract class RenderComponent extends HyperdomComponent { public abstract render (): VdomFragment | Component } export abstract class RoutesComponent extends HyperdomComponent { public abstract routes (): router.Route[] protected renderLayout (content: any): VdomFragment | Component } export type Component = RoutesComponent | RenderComponent interface DomAttachement { remove (): void detach (): void } export interface MountOpts { requestRender?: (render: () => void) => void window?: Window document?: Document router?: typeof router } export interface ObjectBinding { get (): string set (value: string): void } export type SimpleBinding = [object, string] | [object, string, (param: string) => any] export type Binding = ObjectBinding | SimpleBinding export type FnComponent = (model?: any) => VdomFragment export function append (root: HTMLElement, component: Component | FnComponent, opts?: MountOpts): DomAttachement export function replace (root: HTMLElement, component: Component | FnComponent, opts?: MountOpts): DomAttachement interface ModelMeta { error: { message: string, } } export interface HtmlNodeProps { [key: string]: string | number | object | boolean | undefined | null } export interface HyperdomNodeProps { binding?: Binding key?: string | number class?: string | string[] | object tabindex?: number onclick? (e?: Event): void } export type NodeProps = HtmlNodeProps & HyperdomNodeProps export interface HTMLLabelProps { for?: string } // TODO Date? export type Renderable = string | number | boolean | undefined | null | VdomFragment | Component const html: { (tag: string, nodeProps: NodeProps, ...children: Renderable[]): VdomFragment, (tag: string, ...children: Renderable[]): VdomFragment, rawHtml (tag: string, ...children: Renderable[]): VdomFragment, refresh (component?: object): void refreshAfter (promise?: Promise<any>): void meta (model: object, property: string): ModelMeta, } export {html} export function rawHtml (tag: string, ...children: Renderable[]): VdomFragment export function rawHtml (tag: string, nodeProps: NodeProps, ...children: Renderable[]): VdomFragment export function viewComponent (component: Component): VdomFragment export function appendVDom (root: VdomFragment, component: Component | FnComponent): DomAttachement const jsx: ( tag: string | { new<T extends object>(props: T, children: Renderable[]): Component }, nodeProps: NodeProps | undefined, children?: Renderable | Renderable[], ) => VdomFragment export {jsx} export function norefresh (): void export function refreshify (fn: () => void, opts?: object): () => void export function binding (opts: object): void } export = hyperdom declare global { namespace JSX { interface WebViewHTMLAttributes extends HTMLElement { allowFullScreen?: boolean allowpopups?: boolean autoFocus?: boolean autosize?: boolean blinkfeatures?: string disableblinkfeatures?: string disableguestresize?: boolean disablewebsecurity?: boolean guestinstance?: string httpreferrer?: string nodeintegration?: boolean partition?: string plugins?: boolean preload?: string src?: string useragent?: string webpreferences?: string } interface SVGAttributes { // Attributes which also defined in HTMLAttributes // See comment in SVGDOMPropertyConfig.js className?: string color?: string height?: number | string id?: string lang?: string max?: number | string media?: string method?: string min?: number | string name?: string target?: string type?: string width?: number | string // Other HTML properties supported by SVG elements in browsers role?: string tabIndex?: number // SVG Specific attributes accentHeight?: number | string accumulate?: "none" | "sum" additive?: "replace" | "sum" alignmentBaseline?: "auto" | "baseline" | "before-edge" | "text-before-edge" | "middle" | "central" | "after-edge" | "text-after-edge" | "ideographic" | "alphabetic" | "hanging" | "mathematical" | "inherit" allowReorder?: "no" | "yes" alphabetic?: number | string amplitude?: number | string arabicForm?: "initial" | "medial" | "terminal" | "isolated" ascent?: number | string attributeName?: string attributeType?: string autoReverse?: number | string azimuth?: number | string baseFrequency?: number | string baselineShift?: number | string baseProfile?: number | string bbox?: number | string begin?: number | string bias?: number | string by?: number | string calcMode?: number | string capHeight?: number | string clip?: number | string clipPath?: string clipPathUnits?: number | string clipRule?: number | string colorInterpolation?: number | string colorInterpolationFilters?: "auto" | "sRGB" | "linearRGB" | "inherit" colorProfile?: number | string colorRendering?: number | string contentScriptType?: number | string contentStyleType?: number | string cursor?: number | string cx?: number | string cy?: number | string d?: string decelerate?: number | string descent?: number | string diffuseConstant?: number | string direction?: number | string display?: number | string divisor?: number | string dominantBaseline?: number | string dur?: number | string dx?: number | string dy?: number | string edgeMode?: number | string elevation?: number | string enableBackground?: number | string end?: number | string exponent?: number | string externalResourcesRequired?: number | string fill?: string fillOpacity?: number | string fillRule?: "nonzero" | "evenodd" | "inherit" filter?: string filterRes?: number | string filterUnits?: number | string floodColor?: number | string floodOpacity?: number | string focusable?: number | string fontFamily?: string fontSize?: number | string fontSizeAdjust?: number | string fontStretch?: number | string fontStyle?: number | string fontVariant?: number | string fontWeight?: number | string format?: number | string from?: number | string fx?: number | string fy?: number | string g1?: number | string g2?: number | string glyphName?: number | string glyphOrientationHorizontal?: number | string glyphOrientationVertical?: number | string glyphRef?: number | string gradientTransform?: string gradientUnits?: string hanging?: number | string horizAdvX?: number | string horizOriginX?: number | string href?: string ideographic?: number | string imageRendering?: number | string in2?: number | string in?: string intercept?: number | string k1?: number | string k2?: number | string k3?: number | string k4?: number | string k?: number | string kernelMatrix?: number | string kernelUnitLength?: number | string kerning?: number | string keyPoints?: number | string keySplines?: number | string keyTimes?: number | string lengthAdjust?: number | string letterSpacing?: number | string lightingColor?: number | string limitingConeAngle?: number | string local?: number | string markerEnd?: string markerHeight?: number | string markerMid?: string markerStart?: string markerUnits?: number | string markerWidth?: number | string mask?: string maskContentUnits?: number | string maskUnits?: number | string mathematical?: number | string mode?: number | string numOctaves?: number | string offset?: number | string opacity?: number | string operator?: number | string order?: number | string orient?: number | string orientation?: number | string origin?: number | string overflow?: number | string overlinePosition?: number | string overlineThickness?: number | string paintOrder?: number | string panose1?: number | string pathLength?: number | string patternContentUnits?: string patternTransform?: number | string patternUnits?: string pointerEvents?: number | string points?: string pointsAtX?: number | string pointsAtY?: number | string pointsAtZ?: number | string preserveAlpha?: number | string preserveAspectRatio?: string primitiveUnits?: number | string r?: number | string radius?: number | string refX?: number | string refY?: number | string renderingIntent?: number | string repeatCount?: number | string repeatDur?: number | string requiredExtensions?: number | string requiredFeatures?: number | string restart?: number | string result?: string rotate?: number | string rx?: number | string ry?: number | string scale?: number | string seed?: number | string shapeRendering?: number | string slope?: number | string spacing?: number | string specularConstant?: number | string specularExponent?: number | string speed?: number | string spreadMethod?: string startOffset?: number | string stdDeviation?: number | string stemh?: number | string stemv?: number | string stitchTiles?: number | string stopColor?: string stopOpacity?: number | string strikethroughPosition?: number | string strikethroughThickness?: number | string string?: number | string stroke?: string strokeDasharray?: string | number strokeDashoffset?: string | number strokeLinecap?: "butt" | "round" | "square" | "inherit" strokeLinejoin?: "miter" | "round" | "bevel" | "inherit" strokeMiterlimit?: number | string strokeOpacity?: number | string strokeWidth?: number | string surfaceScale?: number | string systemLanguage?: number | string tableValues?: number | string targetX?: number | string targetY?: number | string textAnchor?: string textDecoration?: number | string textLength?: number | string textRendering?: number | string to?: number | string transform?: string u1?: number | string u2?: number | string underlinePosition?: number | string underlineThickness?: number | string unicode?: number | string unicodeBidi?: number | string unicodeRange?: number | string unitsPerEm?: number | string vAlphabetic?: number | string values?: string vectorEffect?: number | string version?: string vertAdvY?: number | string vertOriginX?: number | string vertOriginY?: number | string vHanging?: number | string vIdeographic?: number | string viewBox?: string viewTarget?: number | string visibility?: number | string vMathematical?: number | string widths?: number | string wordSpacing?: number | string writingMode?: number | string x1?: number | string x2?: number | string x?: number | string xChannelSelector?: string xHeight?: number | string xlinkActuate?: string xlinkArcrole?: string xlinkHref?: string xlinkRole?: string xlinkShow?: string xlinkTitle?: string xlinkType?: string xmlBase?: string xmlLang?: string xmlns?: string xmlnsXlink?: string xmlSpace?: string y1?: number | string y2?: number | string y?: number | string yChannelSelector?: string z?: number | string zoomAndPan?: string } type HyperdomSVGAttributes<T> = SVGAttributes & Exclude<SVGAttributes, T> & hyperdom.HyperdomNodeProps interface IntrinsicElements { // HTML & hyperdom.HyperdomNodeProps a: Partial<HTMLAnchorElement> & hyperdom.HyperdomNodeProps abbr: Partial<HTMLElement> & hyperdom.HyperdomNodeProps address: Partial<HTMLElement> & hyperdom.HyperdomNodeProps area: Partial<HTMLAreaElement> & hyperdom.HyperdomNodeProps article: Partial<HTMLElement> & hyperdom.HyperdomNodeProps aside: Partial<HTMLElement> & hyperdom.HyperdomNodeProps audio: Partial<HTMLAudioElement> & hyperdom.HyperdomNodeProps b: Partial<HTMLElement> & hyperdom.HyperdomNodeProps base: Partial<HTMLBaseElement> & hyperdom.HyperdomNodeProps bdi: Partial<HTMLElement> & hyperdom.HyperdomNodeProps bdo: Partial<HTMLElement> & hyperdom.HyperdomNodeProps big: Partial<HTMLElement> & hyperdom.HyperdomNodeProps blockquote: Partial<HTMLElement> & hyperdom.HyperdomNodeProps body: Partial<HTMLBodyElement> & hyperdom.HyperdomNodeProps br: Partial<HTMLBRElement> & hyperdom.HyperdomNodeProps button: Partial<HTMLButtonElement> & hyperdom.HyperdomNodeProps canvas: Partial<HTMLCanvasElement> & hyperdom.HyperdomNodeProps caption: Partial<HTMLElement> & hyperdom.HyperdomNodeProps cite: Partial<HTMLElement> & hyperdom.HyperdomNodeProps code: Partial<HTMLElement> & hyperdom.HyperdomNodeProps col: Partial<HTMLTableColElement> & hyperdom.HyperdomNodeProps colgroup: Partial<HTMLTableColElement> & hyperdom.HyperdomNodeProps data: Partial<HTMLElement> & hyperdom.HyperdomNodeProps datalist: Partial<HTMLDataListElement> & hyperdom.HyperdomNodeProps dd: Partial<HTMLElement> & hyperdom.HyperdomNodeProps del: Partial<HTMLElement> & hyperdom.HyperdomNodeProps details: Partial<HTMLElement> & hyperdom.HyperdomNodeProps dfn: Partial<HTMLElement> & hyperdom.HyperdomNodeProps dialog: Partial<HTMLDialogElement> & hyperdom.HyperdomNodeProps div: Partial<HTMLDivElement> & hyperdom.HyperdomNodeProps dl: Partial<HTMLDListElement> & hyperdom.HyperdomNodeProps dt: Partial<HTMLElement> & hyperdom.HyperdomNodeProps em: Partial<HTMLElement> & hyperdom.HyperdomNodeProps embed: Partial<HTMLEmbedElement> & hyperdom.HyperdomNodeProps fieldset: Partial<HTMLFieldSetElement> & hyperdom.HyperdomNodeProps figcaption: Partial<HTMLElement> & hyperdom.HyperdomNodeProps figure: Partial<HTMLElement> & hyperdom.HyperdomNodeProps footer: Partial<HTMLElement> & hyperdom.HyperdomNodeProps form: Partial<HTMLFormElement> & hyperdom.HyperdomNodeProps h1: Partial<HTMLHeadingElement> & hyperdom.HyperdomNodeProps h2: Partial<HTMLHeadingElement> & hyperdom.HyperdomNodeProps h3: Partial<HTMLHeadingElement> & hyperdom.HyperdomNodeProps h4: Partial<HTMLHeadingElement> & hyperdom.HyperdomNodeProps h5: Partial<HTMLHeadingElement> & hyperdom.HyperdomNodeProps h6: Partial<HTMLHeadingElement> & hyperdom.HyperdomNodeProps head: Partial<HTMLHeadElement> & hyperdom.HyperdomNodeProps header: Partial<HTMLElement> & hyperdom.HyperdomNodeProps hgroup: Partial<HTMLElement> & hyperdom.HyperdomNodeProps hr: Partial<HTMLHRElement> & hyperdom.HyperdomNodeProps html: Partial<HTMLHtmlElement> & hyperdom.HyperdomNodeProps i: Partial<HTMLElement> & hyperdom.HyperdomNodeProps iframe: Partial<HTMLIFrameElement> & hyperdom.HyperdomNodeProps img: Partial<HTMLImageElement> & hyperdom.HyperdomNodeProps input: Partial<HTMLInputElement> & hyperdom.HyperdomNodeProps ins: Partial<HTMLModElement> & hyperdom.HyperdomNodeProps kbd: Partial<HTMLElement> & hyperdom.HyperdomNodeProps keygen: Partial<HTMLElement> & hyperdom.HyperdomNodeProps label: Partial<HTMLLabelElement> & hyperdom.HyperdomNodeProps & hyperdom.HTMLLabelProps legend: Partial<HTMLLegendElement> & hyperdom.HyperdomNodeProps li: Partial<HTMLLIElement> & hyperdom.HyperdomNodeProps link: Partial<HTMLLinkElement> & hyperdom.HyperdomNodeProps main: Partial<HTMLElement> & hyperdom.HyperdomNodeProps map: Partial<HTMLMapElement> & hyperdom.HyperdomNodeProps mark: Partial<HTMLElement> & hyperdom.HyperdomNodeProps menu: Partial<HTMLElement> & hyperdom.HyperdomNodeProps menuitem: Partial<HTMLElement> & hyperdom.HyperdomNodeProps meta: Partial<HTMLMetaElement> & hyperdom.HyperdomNodeProps meter: Partial<HTMLElement> & hyperdom.HyperdomNodeProps nav: Partial<HTMLElement> & hyperdom.HyperdomNodeProps noindex: Partial<HTMLElement> & hyperdom.HyperdomNodeProps noscript: Partial<HTMLElement> & hyperdom.HyperdomNodeProps object: Partial<HTMLObjectElement> & hyperdom.HyperdomNodeProps ol: Partial<HTMLOListElement> & hyperdom.HyperdomNodeProps optgroup: Partial<HTMLOptGroupElement> & hyperdom.HyperdomNodeProps option: Partial<HTMLOptionElement> & hyperdom.HyperdomNodeProps output: Partial<HTMLElement> & hyperdom.HyperdomNodeProps p: Partial<HTMLParagraphElement> & hyperdom.HyperdomNodeProps param: Partial<HTMLParamElement> & hyperdom.HyperdomNodeProps picture: Partial<HTMLElement> & hyperdom.HyperdomNodeProps pre: Partial<HTMLPreElement> & hyperdom.HyperdomNodeProps progress: Partial<HTMLProgressElement> & hyperdom.HyperdomNodeProps q: Partial<HTMLQuoteElement> & hyperdom.HyperdomNodeProps rp: Partial<HTMLElement> & hyperdom.HyperdomNodeProps rt: Partial<HTMLElement> & hyperdom.HyperdomNodeProps ruby: Partial<HTMLElement> & hyperdom.HyperdomNodeProps s: Partial<HTMLElement> & hyperdom.HyperdomNodeProps samp: Partial<HTMLElement> & hyperdom.HyperdomNodeProps script: Partial<HTMLScriptElement> & hyperdom.HyperdomNodeProps section: Partial<HTMLElement> & hyperdom.HyperdomNodeProps select: Partial<HTMLSelectElement> & hyperdom.HyperdomNodeProps small: Partial<HTMLElement> & hyperdom.HyperdomNodeProps source: Partial<HTMLSourceElement> & hyperdom.HyperdomNodeProps span: Partial<HTMLSpanElement> & hyperdom.HyperdomNodeProps strong: Partial<HTMLElement> & hyperdom.HyperdomNodeProps style: Partial<HTMLStyleElement> & hyperdom.HyperdomNodeProps sub: Partial<HTMLElement> & hyperdom.HyperdomNodeProps summary: Partial<HTMLElement> & hyperdom.HyperdomNodeProps sup: Partial<HTMLElement> & hyperdom.HyperdomNodeProps table: Partial<HTMLTableElement> & hyperdom.HyperdomNodeProps tbody: Partial<HTMLTableSectionElement> & hyperdom.HyperdomNodeProps td: Partial<HTMLTableDataCellElement> & hyperdom.HyperdomNodeProps textarea: Partial<HTMLTextAreaElement> & hyperdom.HyperdomNodeProps tfoot: Partial<HTMLTableSectionElement> & hyperdom.HyperdomNodeProps th: Partial<HTMLTableHeaderCellElement> & hyperdom.HyperdomNodeProps thead: Partial<HTMLTableSectionElement> & hyperdom.HyperdomNodeProps time: Partial<HTMLElement> & hyperdom.HyperdomNodeProps title: Partial<HTMLTitleElement> & hyperdom.HyperdomNodeProps tr: Partial<HTMLTableRowElement> & hyperdom.HyperdomNodeProps track: Partial<HTMLTrackElement> & hyperdom.HyperdomNodeProps u: Partial<HTMLElement> & hyperdom.HyperdomNodeProps ul: Partial<HTMLUListElement> & hyperdom.HyperdomNodeProps "var": Partial<HTMLElement> & hyperdom.HyperdomNodeProps video: Partial<HTMLVideoElement> & hyperdom.HyperdomNodeProps wbr: Partial<HTMLElement> & hyperdom.HyperdomNodeProps webview: Partial<WebViewHTMLAttributes> & hyperdom.HyperdomNodeProps // SVG svg: HyperdomSVGAttributes<SVGSVGElement> animate: HyperdomSVGAttributes<SVGElement> animateTransform: HyperdomSVGAttributes<SVGElement> circle: HyperdomSVGAttributes<SVGCircleElement> clipPath: HyperdomSVGAttributes<SVGClipPathElement> defs: HyperdomSVGAttributes<SVGDefsElement> desc: HyperdomSVGAttributes<SVGDescElement> ellipse: HyperdomSVGAttributes<SVGEllipseElement> feBlend: HyperdomSVGAttributes<SVGFEBlendElement> feColorMatrix: HyperdomSVGAttributes<SVGFEColorMatrixElement> feComponentTransfer: HyperdomSVGAttributes<SVGFEComponentTransferElement> feComposite: HyperdomSVGAttributes<SVGFECompositeElement> feConvolveMatrix: HyperdomSVGAttributes<SVGFEConvolveMatrixElement> feDiffuseLighting: HyperdomSVGAttributes<SVGFEDiffuseLightingElement> feDisplacementMap: HyperdomSVGAttributes<SVGFEDisplacementMapElement> feDistantLight: HyperdomSVGAttributes<SVGFEDistantLightElement> feFlood: HyperdomSVGAttributes<SVGFEFloodElement> feFuncA: HyperdomSVGAttributes<SVGFEFuncAElement> feFuncB: HyperdomSVGAttributes<SVGFEFuncBElement> feFuncG: HyperdomSVGAttributes<SVGFEFuncGElement> feFuncR: HyperdomSVGAttributes<SVGFEFuncRElement> feGaussianBlur: HyperdomSVGAttributes<SVGFEGaussianBlurElement> feImage: HyperdomSVGAttributes<SVGFEImageElement> feMerge: HyperdomSVGAttributes<SVGFEMergeElement> feMergeNode: HyperdomSVGAttributes<SVGFEMergeNodeElement> feMorphology: HyperdomSVGAttributes<SVGFEMorphologyElement> feOffset: HyperdomSVGAttributes<SVGFEOffsetElement> fePointLight: HyperdomSVGAttributes<SVGFEPointLightElement> feSpecularLighting: HyperdomSVGAttributes<SVGFESpecularLightingElement> feSpotLight: HyperdomSVGAttributes<SVGFESpotLightElement> feTile: HyperdomSVGAttributes<SVGFETileElement> feTurbulence: HyperdomSVGAttributes<SVGFETurbulenceElement> filter: HyperdomSVGAttributes<SVGFilterElement> foreignObject: HyperdomSVGAttributes<SVGForeignObjectElement> g: HyperdomSVGAttributes<SVGGElement> image: HyperdomSVGAttributes<SVGImageElement> line: HyperdomSVGAttributes<SVGLineElement> linearGradient: HyperdomSVGAttributes<SVGLinearGradientElement> marker: HyperdomSVGAttributes<SVGMarkerElement> mask: HyperdomSVGAttributes<SVGMaskElement> metadata: HyperdomSVGAttributes<SVGMetadataElement> path: HyperdomSVGAttributes<SVGPathElement> pattern: HyperdomSVGAttributes<SVGPatternElement> polygon: HyperdomSVGAttributes<SVGPolygonElement> polyline: HyperdomSVGAttributes<SVGPolylineElement> radialGradient: HyperdomSVGAttributes<SVGRadialGradientElement> rect: HyperdomSVGAttributes<SVGRectElement> stop: HyperdomSVGAttributes<SVGStopElement> switch: HyperdomSVGAttributes<SVGSwitchElement> symbol: HyperdomSVGAttributes<SVGSymbolElement> text: HyperdomSVGAttributes<SVGTextElement> textPath: HyperdomSVGAttributes<SVGTextPathElement> tspan: HyperdomSVGAttributes<SVGTSpanElement> use: HyperdomSVGAttributes<SVGUseElement> view: HyperdomSVGAttributes<SVGViewElement> } } }
the_stack
import { parse as parseUrl, format as formatUrl } from 'url'; import { pathToRegexp, compile, Key } from 'path-to-regexp'; import { Route, Redirect, Rewrite, HasField, Header } from './types'; const UN_NAMED_SEGMENT = '__UN_NAMED_SEGMENT__'; export function getCleanUrls( filePaths: string[] ): { html: string; clean: string }[] { const htmlFiles = filePaths .map(toRoute) .filter(f => f.endsWith('.html')) .map(f => ({ html: f, clean: f.slice(0, -5), })); return htmlFiles; } export function convertCleanUrls( cleanUrls: boolean, trailingSlash?: boolean, status = 308 ): Route[] { const routes: Route[] = []; if (cleanUrls) { const loc = trailingSlash ? '/$1/' : '/$1'; routes.push({ src: '^/(?:(.+)/)?index(?:\\.html)?/?$', headers: { Location: loc }, status, }); routes.push({ src: '^/(.*)\\.html/?$', headers: { Location: loc }, status, }); } return routes; } export function convertRedirects( redirects: Redirect[], defaultStatus = 308 ): Route[] { return redirects.map(r => { const { src, segments } = sourceToRegex(r.source); const hasSegments = collectHasSegments(r.has); try { const loc = replaceSegments(segments, hasSegments, r.destination, true); let status: number; if (typeof r.permanent === 'boolean') { status = r.permanent ? 308 : 307; } else if (r.statusCode) { status = r.statusCode; } else { status = defaultStatus; } const route: Route = { src, headers: { Location: loc }, status, }; if (r.has) { route.has = r.has; } return route; } catch (e) { throw new Error(`Failed to parse redirect: ${JSON.stringify(r)}`); } }); } export function convertRewrites( rewrites: Rewrite[], internalParamNames?: string[] ): Route[] { return rewrites.map(r => { const { src, segments } = sourceToRegex(r.source); const hasSegments = collectHasSegments(r.has); try { const dest = replaceSegments( segments, hasSegments, r.destination, false, internalParamNames ); const route: Route = { src, dest, check: true }; if (r.has) { route.has = r.has; } return route; } catch (e) { throw new Error(`Failed to parse rewrite: ${JSON.stringify(r)}`); } }); } export function convertHeaders(headers: Header[]): Route[] { return headers.map(h => { const obj: { [key: string]: string } = {}; const { src, segments } = sourceToRegex(h.source); const hasSegments = collectHasSegments(h.has); const namedSegments = segments.filter(name => name !== UN_NAMED_SEGMENT); const indexes: { [k: string]: string } = {}; segments.forEach((name, index) => { indexes[name] = toSegmentDest(index); }); hasSegments.forEach(name => { indexes[name] = '$' + name; }); h.headers.forEach(({ key, value }) => { if (namedSegments.length > 0 || hasSegments.length > 0) { if (key.includes(':')) { key = safelyCompile(key, indexes); } if (value.includes(':')) { value = safelyCompile(value, indexes); } } obj[key] = value; }); const route: Route = { src, headers: obj, continue: true, }; if (h.has) { route.has = h.has; } return route; }); } export function convertTrailingSlash(enable: boolean, status = 308): Route[] { const routes: Route[] = []; if (enable) { routes.push({ src: '^/\\.well-known(?:/.*)?$', }); routes.push({ src: '^/((?:[^/]+/)*[^/\\.]+)$', headers: { Location: '/$1/' }, status, }); routes.push({ src: '^/((?:[^/]+/)*[^/]+\\.\\w+)/$', headers: { Location: '/$1' }, status, }); } else { routes.push({ src: '^/(.*)\\/$', headers: { Location: '/$1' }, status, }); } return routes; } export function sourceToRegex(source: string): { src: string; segments: string[]; } { const keys: Key[] = []; const r = pathToRegexp(source, keys, { strict: true, sensitive: true, delimiter: '/', }); const segments = keys .map(k => k.name) .map(name => { if (typeof name !== 'string') { return UN_NAMED_SEGMENT; } return name; }); return { src: r.source, segments }; } const namedGroupsRegex = /\(\?<([a-zA-Z][a-zA-Z0-9]*)>/g; export function collectHasSegments(has?: HasField) { const hasSegments = new Set<string>(); for (const hasItem of has || []) { if ('key' in hasItem && hasItem.type === 'header') { hasItem.key = hasItem.key.toLowerCase(); } if (!hasItem.value && 'key' in hasItem) { hasSegments.add(hasItem.key); } if (hasItem.value) { for (const match of hasItem.value.matchAll(namedGroupsRegex)) { if (match[1]) { hasSegments.add(match[1]); } } if (hasItem.type === 'host') { hasSegments.add('host'); } } } return [...hasSegments]; } const escapeSegment = (str: string, segmentName: string) => str.replace(new RegExp(`:${segmentName}`, 'g'), `__ESC_COLON_${segmentName}`); const unescapeSegments = (str: string) => str.replace(/__ESC_COLON_/gi, ':'); function replaceSegments( segments: string[], hasItemSegments: string[], destination: string, isRedirect?: boolean, internalParamNames?: string[] ): string { const namedSegments = segments.filter(name => name !== UN_NAMED_SEGMENT); const canNeedReplacing = (destination.includes(':') && namedSegments.length > 0) || hasItemSegments.length > 0 || !isRedirect; if (!canNeedReplacing) { return destination; } let escapedDestination = destination; const indexes: { [k: string]: string } = {}; segments.forEach((name, index) => { indexes[name] = toSegmentDest(index); escapedDestination = escapeSegment(escapedDestination, name); }); // 'has' matches override 'source' matches hasItemSegments.forEach(name => { indexes[name] = '$' + name; escapedDestination = escapeSegment(escapedDestination, name); }); const parsedDestination = parseUrl(escapedDestination, true); delete (parsedDestination as any).href; delete (parsedDestination as any).path; delete (parsedDestination as any).search; delete (parsedDestination as any).host; // eslint-disable-next-line prefer-const let { pathname, hash, query, hostname, ...rest } = parsedDestination; pathname = unescapeSegments(pathname || ''); hash = unescapeSegments(hash || ''); hostname = unescapeSegments(hostname || ''); let destParams = new Set<string>(); const pathnameKeys: Key[] = []; const hashKeys: Key[] = []; const hostnameKeys: Key[] = []; try { pathToRegexp(pathname, pathnameKeys); pathToRegexp(hash || '', hashKeys); pathToRegexp(hostname || '', hostnameKeys); } catch (_) { // this is not fatal so don't error when failing to parse the // params from the destination } destParams = new Set( [...pathnameKeys, ...hashKeys, ...hostnameKeys] .map(key => key.name) .filter(val => typeof val === 'string') as string[] ); pathname = safelyCompile(pathname, indexes, true); hash = hash ? safelyCompile(hash, indexes, true) : null; hostname = hostname ? safelyCompile(hostname, indexes, true) : null; for (const [key, strOrArray] of Object.entries(query)) { if (Array.isArray(strOrArray)) { query[key] = strOrArray.map(str => safelyCompile(unescapeSegments(str), indexes, true) ); } else { query[key] = safelyCompile(unescapeSegments(strOrArray), indexes, true); } } // We only add path segments to redirect queries if manually // specified and only automatically add them for rewrites if one // or more params aren't already used in the destination's path const paramKeys = Object.keys(indexes); const needsQueryUpdating = // we do not consider an internal param since it is added automatically !isRedirect && !paramKeys.some( param => !(internalParamNames && internalParamNames.includes(param)) && destParams.has(param) ); if (needsQueryUpdating) { for (const param of paramKeys) { if (!(param in query) && param !== UN_NAMED_SEGMENT) { query[param] = indexes[param]; } } } destination = formatUrl({ ...rest, hostname, pathname, query, hash, }); // url.format() escapes the dollar sign but it must be preserved for now-proxy return destination.replace(/%24/g, '$'); } function safelyCompile( value: string, indexes: { [k: string]: string }, attemptDirectCompile?: boolean ): string { if (!value) { return value; } if (attemptDirectCompile) { try { // Attempt compiling normally with path-to-regexp first and fall back // to safely compiling to handle edge cases if path-to-regexp compile // fails return compile(value, { validate: false })(indexes); } catch (e) { // non-fatal, we continue to safely compile } } for (const key of Object.keys(indexes)) { if (value.includes(`:${key}`)) { value = value .replace( new RegExp(`:${key}\\*`, 'g'), `:${key}--ESCAPED_PARAM_ASTERISK` ) .replace( new RegExp(`:${key}\\?`, 'g'), `:${key}--ESCAPED_PARAM_QUESTION` ) .replace(new RegExp(`:${key}\\+`, 'g'), `:${key}--ESCAPED_PARAM_PLUS`) .replace( new RegExp(`:${key}(?!\\w)`, 'g'), `--ESCAPED_PARAM_COLON${key}` ); } } value = value .replace(/(:|\*|\?|\+|\(|\)|\{|\})/g, '\\$1') .replace(/--ESCAPED_PARAM_PLUS/g, '+') .replace(/--ESCAPED_PARAM_COLON/g, ':') .replace(/--ESCAPED_PARAM_QUESTION/g, '?') .replace(/--ESCAPED_PARAM_ASTERISK/g, '*'); // the value needs to start with a forward-slash to be compiled // correctly return compile(`/${value}`, { validate: false })(indexes).substr(1); } function toSegmentDest(index: number): string { const i = index + 1; // js is base 0, regex is base 1 return '$' + i.toString(); } function toRoute(filePath: string): string { return filePath.startsWith('/') ? filePath : '/' + filePath; }
the_stack
import {QueryProcessManager} from './process-manager'; import type * as sqlite from 'better-sqlite3'; import {FS} from './fs'; // @ts-ignore in case not installed import type {SQLStatement} from 'sql-template-strings'; export const DB_NOT_FOUND = null; export interface SQLOptions { file: string; /** file to import database functions from - this should be relative to this filename. */ extension?: string; /** options to be passed to better-sqlite3 */ sqliteOptions?: sqlite.Options; /** * You can choose to return custom error information, or just crashlog and return void. * doing that will make it reject in main as normal. * (it only returns a diff result if you do, otherwise it's a default error). * You can also choose to only handle errors in the parent - see the third param, isParentProcess. */ onError?: ErrorHandler; } type DataType = unknown[] | Record<string, unknown>; export type SQLInput = string | number | null; export interface ResultRow {[k: string]: SQLInput} export interface TransactionEnvironment { db: sqlite.Database; statements: Map<string, sqlite.Statement>; } type DatabaseQuery = { /** Prepare a statement - data is the statement. */ type: 'prepare', data: string, } | { /** Get all lines from a statement. Data is the params. */ type: 'all', data: DataType, statement: string, noPrepare?: boolean, } | { /** Execute raw SQL in the database. */ type: "exec", data: string, } | { /** Get one line from a prepared statement. */ type: 'get', data: DataType, statement: string, noPrepare?: boolean, } | { /** Run a prepared statement. */ type: 'run', data: DataType, statement: string, noPrepare?: boolean, } | { type: 'transaction', name: string, data: DataType, } | { type: 'start', options: SQLOptions, } | { type: 'load-extension', data: string, }; type ErrorHandler = (error: Error, data: DatabaseQuery, isParentProcess: boolean) => any; function getModule() { try { return require('better-sqlite3') as typeof sqlite.default; } catch { return null; } } export class Statement<R extends DataType = DataType, T = any> { private db: SQLDatabaseManager; private statement: string; constructor(statement: string, db: SQLDatabaseManager) { this.db = db; this.statement = statement; } run(data: R) { return this.db.run(this.statement, data); } all(data: R) { return this.db.all<T>(this.statement, data); } get(data: R) { return this.db.get<T>(this.statement, data); } toString() { return this.statement; } toJSON() { return this.statement; } } export class SQLDatabaseManager extends QueryProcessManager<DatabaseQuery, any> { options: SQLOptions; database: null | sqlite.Database = null; state: { transactions: Map<string, sqlite.Transaction>, statements: Map<string, sqlite.Statement>, }; private dbReady = false; constructor(module: NodeJS.Module, options: SQLOptions) { super(module, query => { if (!this.dbReady) { this.setupDatabase(); } try { switch (query.type) { case 'load-extension': { if (!this.database) return null; this.loadExtensionFile(query.data); return true; } case 'transaction': { const transaction = this.state.transactions.get(query.name); // !transaction covers db not existing, typically, but this is just to appease ts if (!transaction || !this.database) { return null; } const env: TransactionEnvironment = { db: this.database, statements: this.state.statements, }; return transaction(query.data, env) || null; } case 'exec': { if (!this.database) return {changes: 0}; this.database.exec(query.data); return true; } case 'get': { if (!this.database) { return null; } return this.extractStatement(query).get(query.data); } case 'run': { if (!this.database) { return null; } return this.extractStatement(query).run(query.data); } case 'all': { if (!this.database) { return null; } return this.extractStatement(query).all(query.data); } case 'prepare': if (!this.database) { return null; } this.state.statements.set(query.data, this.database.prepare(query.data)); return query.data; } } catch (error: any) { return this.onError(error, query); } }); this.options = options; this.state = { transactions: new Map(), statements: new Map(), }; if (!this.isParentProcess) this.setupDatabase(); } private onError(err: Error, query: DatabaseQuery) { if (this.options.onError) { const result = this.options.onError(err, query, false); if (result) return result; } return { queryError: { stack: err.stack, message: err.message, query, }, }; } private cacheStatement(source: string) { source = source.trim(); let statement = this.state.statements.get(source); if (!statement) { statement = this.database!.prepare(source); this.state.statements.set(source, statement); } return statement; } private extractStatement( query: DatabaseQuery & {statement: string, noPrepare?: boolean} ) { query.statement = query.statement.trim(); const statement = query.noPrepare ? this.state.statements.get(query.statement) : this.cacheStatement(query.statement); if (!statement) throw new Error(`Missing cached statement "${query.statement}" where required`); return statement; } setupDatabase() { if (this.dbReady) return; this.dbReady = true; const {file, extension} = this.options; const Database = getModule(); this.database = Database ? new Database(file) : null; if (extension) this.loadExtensionFile(extension); } loadExtensionFile(extension: string) { if (!this.database) return; const { functions, transactions: storedTransactions, statements: storedStatements, onDatabaseStart, // eslint-disable-next-line @typescript-eslint/no-var-requires } = require(`../${extension}`); if (functions) { for (const k in functions) { this.database.function(k, functions[k]); } } if (storedTransactions) { for (const t in storedTransactions) { const transaction = this.database.transaction(storedTransactions[t]); this.state.transactions.set(t, transaction); } } if (storedStatements) { for (const k in storedStatements) { const statement = this.database.prepare(storedStatements[k]); this.state.statements.set(statement.source, statement); } } if (onDatabaseStart) { onDatabaseStart(this.database); } } async query(input: DatabaseQuery) { const result = await super.query(input); if (result?.queryError) { const err = new Error(result.queryError.message); err.stack = result.queryError.stack; if (this.options.onError) { const errResult = this.options.onError(err, result.queryError.query, true); if (errResult) return errResult; } throw err; } return result; } all<T = any>( statement: string | Statement, data: DataType = [], noPrepare?: boolean ): Promise<T[]> { if (typeof statement !== 'string') statement = statement.toString(); return this.query({type: 'all', statement, data, noPrepare}); } get<T = any>( statement: string | Statement, data: DataType = [], noPrepare?: boolean ): Promise<T> { if (typeof statement !== 'string') statement = statement.toString(); return this.query({type: 'get', statement, data, noPrepare}); } run( statement: string | Statement, data: DataType = [], noPrepare?: boolean ): Promise<sqlite.RunResult> { if (typeof statement !== 'string') statement = statement.toString(); return this.query({type: 'run', statement, data, noPrepare}); } transaction<T = any>(name: string, data: DataType = []): Promise<T> { return this.query({type: 'transaction', name, data}); } async prepare(statement: string): Promise<Statement | null> { const source = await this.query({type: 'prepare', data: statement}); if (!source) return null; return new Statement(source, this); } exec(data: string): Promise<{changes: number}> { return this.query({type: 'exec', data}); } loadExtension(filepath: string) { return this.query({type: 'load-extension', data: filepath}); } async runFile(file: string) { const contents = await FS(file).read(); return this.query({type: 'exec', data: contents}); } } export const tables = new Map<string, DatabaseTable<any>>(); export class DatabaseTable<T> { database: SQLDatabaseManager; name: string; primaryKeyName: string; constructor( name: string, primaryKeyName: string, database: SQLDatabaseManager ) { this.name = name; this.database = database; this.primaryKeyName = primaryKeyName; tables.set(this.name, this); } async selectOne<R = T>( entries: string | string[], where?: SQLStatement ): Promise<R | null> { const query = where || SQL.SQL``; query.append(' LIMIT 1'); const rows = await this.selectAll<R>(entries, query); return rows?.[0] || null; } selectAll<R = T>( entries: string | string[], where?: SQLStatement ): Promise<R[]> { const query = SQL.SQL`SELECT `; if (typeof entries === 'string') { query.append(` ${entries} `); } else { for (let i = 0; i < entries.length; i++) { query.append(entries[i]); if (typeof entries[i + 1] !== 'undefined') query.append(', '); } query.append(' '); } query.append(`FROM ${this.name} `); if (where) { query.append(' WHERE '); query.append(where); } return this.all<R>(query); } get(entries: string | string[], keyId: SQLInput) { const query = SQL.SQL``; query.append(this.primaryKeyName); query.append(SQL.SQL` = ${keyId}`); return this.selectOne(entries, query); } updateAll(toParams: Partial<T>, where?: SQLStatement, limit?: number) { const to = Object.entries(toParams); const query = SQL.SQL`UPDATE `; query.append(this.name + ' SET '); for (let i = 0; i < to.length; i++) { const [k, v] = to[i]; query.append(`${k} = `); query.append(SQL.SQL`${v}`); if (typeof to[i + 1] !== 'undefined') { query.append(', '); } } if (where) { query.append(` WHERE `); query.append(where); } if (limit) query.append(SQL.SQL` LIMIT ${limit}`); return this.run(query); } updateOne(to: Partial<T>, where?: SQLStatement) { return this.updateAll(to, where, 1); } deleteAll(where?: SQLStatement, limit?: number) { const query = SQL.SQL`DELETE FROM `; query.append(this.name); if (where) { query.append(' WHERE '); query.append(where); } if (limit) { query.append(SQL.SQL` LIMIT ${limit}`); } return this.run(query); } delete(keyEntry: SQLInput) { const query = SQL.SQL``; query.append(this.primaryKeyName); query.append(SQL.SQL` = ${keyEntry}`); return this.deleteOne(query); } deleteOne(where: SQLStatement) { return this.deleteAll(where, 1); } insert(colMap: Partial<T>, rest?: SQLStatement, isReplace = false) { const query = SQL.SQL``; query.append(`${isReplace ? 'REPLACE' : 'INSERT'} INTO ${this.name} (`); const keys = Object.keys(colMap); for (let i = 0; i < keys.length; i++) { query.append(keys[i]); if (typeof keys[i + 1] !== 'undefined') query.append(', '); } query.append(') VALUES ('); for (let i = 0; i < keys.length; i++) { const key = keys[i]; query.append(SQL.SQL`${colMap[key as keyof T]}`); if (typeof keys[i + 1] !== 'undefined') query.append(', '); } query.append(') '); if (rest) query.append(rest); return this.database.run(query.sql, query.values); } replace(cols: Partial<T>, rest?: SQLStatement) { return this.insert(cols, rest, true); } update(primaryKey: SQLInput, data: Partial<T>) { const query = SQL.SQL``; query.append(this.primaryKeyName + ' = '); query.append(SQL.SQL`${primaryKey}`); return this.updateOne(data, query); } // catch-alls for "we can't fit this query into any of the wrapper functions" run(sql: SQLStatement) { return this.database.run(sql.sql, sql.values) as Promise<{changes: number}>; } all<R = T>(sql: SQLStatement) { return this.database.all<R>(sql.sql, sql.values); } } function getSQL( module: NodeJS.Module, input: SQLOptions & {processes?: number} ) { const {processes} = input; const PM = new SQLDatabaseManager(module, input); if (PM.isParentProcess) { if (processes) PM.spawn(processes); } return PM; } export const SQL = Object.assign(getSQL, { DatabaseTable, SQLDatabaseManager, tables, SQL: (() => { try { return require('sql-template-strings'); } catch { return () => { throw new Error("Using SQL-template-strings without it installed"); }; } })() as typeof import('sql-template-strings').SQL, }); export namespace SQL { export type DatabaseManager = import('./sql').SQLDatabaseManager; export type Statement = import('./sql').Statement; export type Options = import('./sql').SQLOptions; export type DatabaseTable<T> = import('./sql').DatabaseTable<T>; }
the_stack
import * as React from 'react'; interface Props { readonly includeList: boolean; } const nameMap = { 'AK-DanSullivan': { name: 'Dan Sullivan (R-AK)', party: 'R', state: 'AK' }, 'AK-LisaMurkowski': { name: 'Lisa Murkowski (R-AK)', party: 'R', state: 'AK' }, 'AL-DougJones': { name: 'Doug Jones (D-AL)', party: 'D', state: 'AL' }, 'AL-RichardCShelby': { name: 'Richard Shelby (R-AL)', party: 'R', state: 'AL' }, 'AR-JohnBoozman': { name: 'John Boozman (R-AR)', party: 'R', state: 'AR' }, 'AR-TomCotton': { name: 'Tom Cotton (R-AR)', party: 'R', state: 'AR' }, 'AZ-JeffFlake': { name: 'Jeff Flake (R-AZ)', party: 'R', state: 'AZ' }, 'AZ-JonKyl': { name: 'Jon Kyl (R-AZ)', party: 'R', state: 'AZ' }, 'CA-DianneFeinstein': { name: 'Dianne Feinstein (D-CA)', party: 'D', state: 'CA' }, 'CA-KamalaDHarris': { name: 'Kamala Harris (D-CA)', party: 'D', state: 'CA' }, 'CO-CoryGardner': { name: 'Cory Gardner (R-CO)', party: 'R', state: 'CO' }, 'CO-MichaelFBennet': { name: 'Michael Bennet (D-CO)', party: 'D', state: 'CO' }, 'CT-ChristopherMurphy': { name: 'Chris Murphy (D-CT)', party: 'D', state: 'CT' }, 'CT-RichardBlumenthal': { name: 'Richard Blumenthal (D-CT)', party: 'D', state: 'CT' }, 'DE-ChristopherACoons': { name: 'Chris Coons (D-DE)', party: 'D', state: 'DE' }, 'DE-ThomasRCarper': { name: 'Tom Carper (D-DE)', party: 'D', state: 'DE' }, 'FL-BillNelson': { name: 'Bill Nelson (D-FL)', party: 'D', state: 'FL' }, 'FL-MarcoRubio': { name: 'Marco Rubio (R-FL)', party: 'R', state: 'FL' }, 'GA-DavidPerdue': { name: 'David Perdue (R-GA)', party: 'R', state: 'GA' }, 'GA-JohnnyIsakson': { name: 'Johnny Isakson (R-GA)', party: 'R', state: 'GA' }, 'HI-BrianSchatz': { name: 'Brian Schatz (D-HI)', party: 'D', state: 'HI' }, 'HI-MazieKHirono': { name: 'Mazie Hirono (D-HI)', party: 'D', state: 'HI' }, 'IA-ChuckGrassley': { name: 'Chuck Grassley (R-IA)', party: 'R', state: 'IA' }, 'IA-JoniErnst': { name: 'Joni Ernst (R-IA)', party: 'R', state: 'IA' }, 'ID-JamesERisch': { name: 'James Risch (R-ID)', party: 'R', state: 'ID' }, 'ID-MikeCrapo': { name: 'Mike Crapo (R-ID)', party: 'R', state: 'ID' }, 'IL-RichardJDurbin': { name: 'Dick Durbin (D-IL)', party: 'D', state: 'IL' }, 'IL-TammyDuckworth': { name: 'Tammy Duckworth (D-IL)', party: 'D', state: 'IL' }, 'IN-JoeDonnelly': { name: 'Joe Donnelly (D-IN)', party: 'D', state: 'IN' }, 'IN-ToddYoung': { name: 'Todd Young (R-IN)', party: 'R', state: 'IN' }, 'KS-JerryMoran': { name: 'Jerry Moran (R-KS)', party: 'R', state: 'KS' }, 'KS-PatRoberts': { name: 'Pat Roberts (R-KS)', party: 'R', state: 'KS' }, 'KY-MitchMcConnell': { name: 'Mitch McConnell (R-KY)', party: 'R', state: 'KY' }, 'KY-RandPaul': { name: 'Rand Paul (R-KY)', party: 'R', state: 'KY' }, 'LA-BillCassidy': { name: 'Bill Cassidy (R-LA)', party: 'R', state: 'LA' }, 'LA-JohnKennedy': { name: 'John Kennedy (R-LA)', party: 'R', state: 'LA' }, 'MA-EdwardJMarkey': { name: 'Ed Markey (D-MA)', party: 'D', state: 'MA' }, 'MA-ElizabethWarren': { name: 'Liz Warren (D-MA)', party: 'D', state: 'MA' }, 'MD-BenjaminLCardin': { name: 'Ben Cardin (D-MD)', party: 'D', state: 'MD' }, 'MD-ChrisVanHollen': { name: 'Chris Van Hollen (D-MD)', party: 'D', state: 'MD' }, 'ME-AngusSKingJr': { name: 'Angus King (I-ME)', party: 'I', state: 'ME' }, 'ME-SusanCollins': { name: 'Susan Collins (R-ME)', party: 'R', state: 'ME' }, 'MI-DebbieStabenow': { name: 'Debbie Stabenow (D-MI)', party: 'D', state: 'MI' }, 'MI-GaryCPeters': { name: 'Gary Peters (D-MI)', party: 'D', state: 'MI' }, 'MN-TinaSmith': { name: 'Tina Smith (D-MN)', party: 'D', state: 'MN' }, 'MN-AmyKlobuchar': { name: 'Amy Klobuchar (D-MN)', party: 'D', state: 'MN' }, 'MO-ClaireMcCaskill': { name: 'Claire McCaskill (D-MO)', party: 'D', state: 'MO' }, 'MO-RoyBlunt': { name: 'Roy Blunt (R-MO)', party: 'R', state: 'MO' }, 'MS-RogerFWicker': { name: 'Roger Wicker (R-MS)', party: 'R', state: 'MS' }, 'MS-ThadCochran': { name: 'Thad Cochran (R-MS)', party: 'R', state: 'MS' }, 'MT-JonTester': { name: 'Jon Tester (D-MT)', party: 'D', state: 'MT' }, 'MT-SteveDaines': { name: 'Steve Daines (R-MT)', party: 'R', state: 'MT' }, 'NC-RichardBurr': { name: 'Richard Burr (R-NC)', party: 'R', state: 'NC' }, 'NC-ThomTillis': { name: 'Thom Tillis (R-NC)', party: 'R', state: 'NC' }, 'ND-HeidiHeitkamp': { name: 'Heidi Heitkamp (D-ND)', party: 'D', state: 'ND' }, 'ND-JohnHoeven': { name: 'John Hoeven (R-ND)', party: 'R', state: 'ND' }, 'NE-BenSasse': { name: 'Ben Sasse (R-NE)', party: 'R', state: 'NE' }, 'NE-DebFischer': { name: 'Deb Fischer (R-NE)', party: 'R', state: 'NE' }, 'NH-JeanneShaheen': { name: 'Jeanne Shaheen (D-NH)', party: 'D', state: 'NH' }, 'NH-MargaretWoodHassan': { name: 'Maggie Hassan (D-NH)', party: 'D', state: 'NH' }, 'NJ-CoryABooker': { name: 'Cory Booker (D-NJ)', party: 'D', state: 'NJ' }, 'NJ-RobertMenendez': { name: 'Bob Menendez (D-NJ)', party: 'D', state: 'NJ' }, 'NM-MartinHeinrich': { name: 'Martin Heinrich (D-NM)', party: 'D', state: 'NM' }, 'NM-TomUdall': { name: 'Tom Udall (D-NM)', party: 'D', state: 'NM' }, 'NV-CatherineCortezMasto': { name: 'Catherine Cortez Masto (D-NV)', party: 'D', state: 'NV' }, 'NV-DeanHeller': { name: 'Dean Heller (R-NV)', party: 'R', state: 'NV' }, 'NY-CharlesESchumer': { name: 'Chuck Schumer (D-NY)', party: 'D', state: 'NY' }, 'NY-KirstenEGillibrand': { name: 'Kirsten Gillibrand (D-NY)', party: 'D', state: 'NY' }, 'OH-RobPortman': { name: 'Rob Portman (R-OH)', party: 'R', state: 'OH' }, 'OH-SherrodBrown': { name: 'Sherrod Brown (D-OH)', party: 'D', state: 'OH' }, 'OK-JamesLankford': { name: 'James Lankford (R-OK)', party: 'R', state: 'OK' }, 'OK-JamesMInhofe': { name: 'Jim Inhofe (R-OK)', party: 'R', state: 'OK' }, 'OR-JeffMerkley': { name: 'Jeff Merkley (D-OR)', party: 'D', state: 'OR' }, 'OR-RonWyden': { name: 'Ron Wyden (D-OR)', party: 'D', state: 'OR' }, 'PA-PatrickJToomey': { name: 'Pat Toomey (R-PA)', party: 'R', state: 'PA' }, 'PA-RobertPCaseyJr': { name: 'Bob Casey (D-PA)', party: 'D', state: 'PA' }, 'RI-JackReed': { name: 'Jack Reed (D-RI)', party: 'D', state: 'RI' }, 'RI-SheldonWhitehouse': { name: 'Sheldon Whitehouse (D-RI)', party: 'D', state: 'RI' }, 'SC-LindseyGraham': { name: 'Lindsey Graham (R-SC)', party: 'R', state: 'SC' }, 'SC-TimScott': { name: 'Tim Scott (R-SC)', party: 'R', state: 'SC' }, 'SD-JohnThune': { name: 'John Thune (R-SD)', party: 'R', state: 'SD' }, 'SD-MikeRounds': { name: 'Mike Rounds (R-SD)', party: 'R', state: 'SD' }, 'TN-BobCorker': { name: 'Bob Corker (R-TN)', party: 'R', state: 'TN' }, 'TN-LamarAlexander': { name: 'Lamar Alexander (R-TN)', party: 'R', state: 'TN' }, 'TX-JohnCornyn': { name: 'John Cornyn (R-TX)', party: 'R', state: 'TX' }, 'TX-TedCruz': { name: 'Ted Cruz (R-TX)', party: 'R', state: 'TX' }, 'UT-MikeLee': { name: 'Mike Lee (R-UT)', party: 'R', state: 'UT' }, 'UT-OrrinGHatch': { name: 'Orrin Hatch (R-UT)', party: 'R', state: 'UT' }, 'VA-MarkRWarner': { name: 'Mark Warner (D-VA)', party: 'D', state: 'VA' }, 'VA-TimKaine': { name: 'Tim Kaine (D-VA)', party: 'D', state: 'VA' }, 'VT-BernardSanders': { name: 'Bernie Sanders (I-VT)', party: 'I', state: 'VT' }, 'VT-PatrickJLeahy': { name: 'Patrick Leahy (D-VT)', party: 'D', state: 'VT' }, 'WA-MariaCantwell': { name: 'Maria Cantwell (D-WA)', party: 'D', state: 'WA' }, 'WA-PattyMurray': { name: 'Patty Murray (D-WA)', party: 'D', state: 'WA' }, 'WI-RonJohnson': { name: 'Ron Johnson (R-WI)', party: 'R', state: 'WI' }, 'WI-TammyBaldwin': { name: 'Tammy Baldwin (D-WI)', party: 'D', state: 'WI' }, 'WV-JoeManchin': { name: 'Joe Manchin (D-WV)', party: 'D', state: 'WV' }, 'WV-ShelleyMooreCapito': { name: 'Shelley Moore Capito (R-WV)', party: 'R', state: 'WV' }, 'WY-JohnBarrasso': { name: 'John Barrasso (R-WY)', party: 'R', state: 'WY' }, 'WY-MichaelBEnzi': { name: 'Mike Enzi (R-WY)', party: 'R', state: 'WY' } }; function sortByParty(a: string, b: string) { if (nameMap[a].party > nameMap[b].party) { return -1; } if (nameMap[a].party < nameMap[b].party) { return 1; } if (nameMap[a].state < nameMap[b].state) { return -1; } if (nameMap[a].state > nameMap[b].state) { return 1; } return 0; } const noReps: string[] = []; const noVotes: string[] = noReps.sort(sortByParty); const yesReps: string[] = []; for (const senatorName in nameMap) { if (nameMap[senatorName].party === 'R') { yesReps.push(senatorName); } } const yesVotes: string[] = yesReps.sort(sortByParty); const unknownReps: string[] = []; const unknownVotes: string[] = unknownReps.sort(sortByParty); const definitelyNo: string[] = ['AK-LisaMurkowski']; for (const senatorName in nameMap) { if (nameMap[senatorName].party !== 'R') { definitelyNo.push(senatorName); } } definitelyNo.forEach(senator => { // add to hard list if (!(noVotes.indexOf(senator) > -1)) { noVotes.push(senator); } // remove from other lists if (yesVotes.indexOf(senator) > -1) { yesVotes.splice(yesVotes.indexOf(senator), 1); } if (unknownVotes.indexOf(senator) > -1) { unknownVotes.splice(unknownVotes.indexOf(senator), 1); } }); const definitelyYes: string[] = ['WV-JoeManchin']; definitelyYes.forEach(senator => { // add to hard list if (!(yesVotes.indexOf(senator) > -1)) { yesVotes.push(senator); } // remove from other lists if (noVotes.indexOf(senator) > -1) { noVotes.splice(noVotes.indexOf(senator), 1); } if (unknownVotes.indexOf(senator) > -1) { unknownVotes.splice(unknownVotes.indexOf(senator), 1); } }); const definitelyUnknown = []; definitelyUnknown.forEach(senator => { // add to hard list if (!(unknownVotes.indexOf(senator) > -1)) { unknownVotes.push(senator); } // remove from other lists if (noVotes.indexOf(senator) > -1) { noVotes.splice(noVotes.indexOf(senator), 1); } if (yesVotes.indexOf(senator) > -1) { yesVotes.splice(yesVotes.indexOf(senator), 1); } }); export const Tracker: React.StatelessComponent<Props> = (props: Props) => { return ( <div className="tracker"> <h3>Kavanaugh Confirmation Tracker</h3> <p className="tracker__required">50 Yes votes needed to confirm</p> <div className="tracker__votes"> <div className="tracker__votes__no" style={{ width: `${noVotes.length}%` }} > Opposes </div> <div className="tracker__votes__yes" style={{ width: `${yesVotes.length}%` }} > Supports </div> <div className="tracker__votes__pass" /> </div> {/* <h4>Help us track Senator positions by calling and reporting results</h4> */} {props.includeList && ( <div className="tracker__lists"> <ul className="tracker__lists__no"> <li className="header">No Votes {noVotes.length}</li> {noVotes.map(senator => ( <li key={nameMap[senator].name} className={`party_${nameMap[senator].party}`} > {nameMap[senator].name} </li> ))} </ul> <ul className="tracker__lists__yes"> <li className="header">Yes Votes {yesVotes.length}</li> {yesVotes.map(senator => ( <li key={nameMap[senator].name} className={`party_${nameMap[senator].party}`} > {nameMap[senator].name} </li> ))} </ul> <ul className="tracker__lists__undecided"> <li className="header">Undecided Votes {unknownVotes.length}</li> {unknownVotes.map(senator => ( <li key={nameMap[senator].name} className={`party_${nameMap[senator].party}`} > {nameMap[senator].name} </li> ))} </ul> </div> )} </div> ); };
the_stack
import type { ComponentDocument, Data, FetchMoreParams, NextFetchPolicyFunction, Variables, VariablesOf, } from '@apollo-elements/core/types'; import type * as C from '@apollo/client/core'; import { ApolloElement } from './apollo-element.js'; import { NetworkStatus } from '@apollo/client/core'; import { attr, nullableNumberConverter } from '@microsoft/fast-element'; import { hosted } from './decorators.js'; import { ApolloQueryBehavior } from '../apollo-query-behavior.js'; import { ApolloQueryControllerOptions } from '@apollo-elements/core/apollo-query-controller'; import { controlled } from '@apollo-elements/core/decorators'; /** * `ApolloQuery` * * 🚀 FASTElement base class that connects to your Apollo cache. * * @element * * See [`ApolloQueryInterface`](https://apolloelements.dev/api/core/interfaces/query) for more information on events * */ export class ApolloQuery<D = unknown, V = VariablesOf<D>> extends ApolloElement<D, V> { /** * Latest query data. */ declare data: Data<D> | null; /** * An object that maps from the name of a variable as used in the query GraphQL document to that variable's value. * * @summary Query variables. */ declare variables: Variables<D, V> | null; controller = new ApolloQueryBehavior<D, V>(this, null, { shouldSubscribe: options => this.readyToReceiveDocument && this.shouldSubscribe(options), onData: data => this.onData?.(data), onError: error => this.onError?.(error), /* c8 ignore next */ // covered }); /** * Determines whether the element should attempt to subscribe i.e. begin querying * Override to prevent subscribing unless your conditions are met */ shouldSubscribe( options?: Partial<C.SubscriptionOptions<Variables<D, V>, Data<D>>> ): boolean { return (void options, true); } /** @summary Flags an element that's ready and able to auto subscribe */ @hosted() @controlled({ readonly: true }) canAutoSubscribe = false; get options(): ApolloQueryControllerOptions<D, V> { return this.controller.options; } set options(v: ApolloQueryControllerOptions<D, V>) { const { onData, onError, shouldSubscribe } = this.controller.options; this.controller.options = { onData, onError, shouldSubscribe, ...v, }; } /** * `networkStatus` is useful if you want to display a different loading indicator (or no indicator at all) * depending on your network status as it provides a more detailed view into the state of a network request * on your component than `loading` does. `networkStatus` is an enum with different number values between 1 and 8. * These number values each represent a different network state. * * 1. `loading`: The query has never been run before and the request is now pending. A query will still have this network status even if a result was returned from the cache, but a query was dispatched anyway. * 2. `setVariables`: If a query’s variables change and a network request was fired then the network status will be setVariables until the result of that query comes back. React users will see this when options.variables changes on their queries. * 3. `fetchMore`: Indicates that fetchMore was called on this query and that the network request created is currently in flight. * 4. `refetch`: It means that refetch was called on a query and the refetch request is currently in flight. * 5. Unused. * 6. `poll`: Indicates that a polling query is currently in flight. So for example if you are polling a query every 10 seconds then the network status will switch to poll every 10 seconds whenever a poll request has been sent but not resolved. * 7. `ready`: No request is in flight for this query, and no errors happened. Everything is OK. * 8. `error`: No request is in flight for this query, but one or more errors were detected. * * If the network status is less then 7 then it is equivalent to `loading` being true. In fact you could * replace all of your `loading` checks with `networkStatus < 7` and you would not see a difference. * It is recommended that you use `loading`, however. */ @hosted() @controlled() @attr({ converter: nullableNumberConverter }) networkStatus: NetworkStatus = NetworkStatus.ready; /** * @summary A GraphQL document containing a single query. */ @hosted() @controlled() query: ComponentDocument<D, V> | null = null; /** * If data was read from the cache with missing fields, * partial will be true. Otherwise, partial will be falsy. * * @summary True when the query returned partial data. */ @hosted() @controlled() partial = false; /** * If true, perform a query refetch if the query result is marked as being partial, * and the returned data is reset to an empty Object by the Apollo Client QueryManager * (due to a cache miss). * * The default value is false for backwards-compatibility's sake, * but should be changed to true for most use-cases. * * @summary Set to retry any partial query results. */ @hosted({ path: 'options' }) @controlled({ path: 'options' }) @attr({ mode: 'boolean', attribute: 'partial-refetch' }) partialRefetch?: boolean; /** * @summary The time interval (in milliseconds) on which this query should be refetched from the server. */ @controlled({ path: 'options' }) @attr({ converter: nullableNumberConverter, attribute: 'poll-interval' }) pollInterval?: number; /** * Opt into receiving partial results from the cache for queries * that are not fully satisfied by the cache. */ @controlled({ path: 'options' }) @attr({ mode: 'boolean', attribute: 'return-partial-data' }) returnPartialData?: boolean; /** * When true, the component will not automatically subscribe to new data. * Call the `subscribe()` method to do so. * @attr no-auto-subscribe */ @hosted({ path: 'options' }) @controlled({ path: 'options' }) @attr({ attribute: 'no-auto-subscribe', mode: 'boolean' }) noAutoSubscribe = false; /** * @summary Whether or not updates to the network status should trigger next on the observer of this query. */ @controlled({ path: 'options' }) @attr({ mode: 'boolean', attribute: 'notify-on-network-status-change' }) notifyOnNetworkStatusChange?: boolean; /** * errorPolicy determines the level of events for errors in the execution result. The options are: * - `none` (default): any errors from the request are treated like runtime errors and the observable is stopped (XXX this is default to lower breaking changes going from AC 1.0 => 2.0) * - `ignore`: errors from the request do not stop the observable, but also don't call `next` * - `all`: errors are treated like data and will notify observables * @summary [Error Policy](https://www.apollographql.com/docs/react/api/core/ApolloClient/#ErrorPolicy) for the query. * @attr error-policy */ @hosted({ path: 'options' }) @controlled({ path: 'options' }) @attr({ attribute: 'error-policy' }) errorPolicy?: C.ErrorPolicy; /** * Determines where the client may return a result from. The options are: * * - `cache-first` (default): return result from cache, fetch from network if cached result is not available. * - `cache-and-network`: return result from cache first (if it exists), then return network result once it's available. * - `cache-only`: return result from cache if available, fail otherwise. * - `no-cache`: return result from network, fail if network call doesn't succeed, don't save to cache * - `network-only`: return result from network, fail if network call doesn't succeed, save to cache * - `standby`: only for queries that aren't actively watched, but should be available for refetch and updateQueries. * * @summary The [fetchPolicy](https://www.apollographql.com/docs/react/api/core/ApolloClient/#FetchPolicy) for the query. * @attr fetch-policy */ @hosted({ path: 'options' }) @controlled({ path: 'options' }) @attr({ attribute: 'fetch-policy' }) fetchPolicy?: C.WatchQueryFetchPolicy; /** * When someone chooses cache-and-network or network-only as their * initial FetchPolicy, they often do not want future cache updates to * trigger unconditional network requests, which is what repeatedly * applying the cache-and-network or network-only policies would seem * to imply. Instead, when the cache reports an update after the * initial network request, it may be desirable for subsequent network * requests to be triggered only if the cache result is incomplete. * The nextFetchPolicy option provides a way to update * options.fetchPolicy after the intial network request, without * having to set options. * * @summary Set to prevent subsequent network requests when the fetch policy is `cache-and-network` or `network-only`. * @attr next-fetch-policy */ @hosted({ path: 'options' }) @controlled({ path: 'options' }) @attr({ attribute: 'next-fetch-policy' }) nextFetchPolicy?: C.WatchQueryFetchPolicy | NextFetchPolicyFunction<D, V>; /** * Exposes the [`ObservableQuery#refetch`](https://www.apollographql.com/docs/react/api/apollo-client.html#ObservableQuery.refetch) method. * * @param variables The new set of variables. If there are missing variables, the previous values of those variables will be used.. */ public async refetch( variables?: Variables<D, V> ): Promise<C.ApolloQueryResult<Data<D>>> { return this.controller.refetch(variables); } /** * Resets the observableQuery and subscribes. * @param params options for controlling how the subscription subscribes */ public subscribe( params?: Partial<C.WatchQueryOptions<Variables<D, V>, Data<D>>> ): C.ObservableSubscription { return this.controller.subscribe(params); } /** * Lets you pass a GraphQL subscription and updateQuery function * to subscribe to more updates for your query. * * The `updateQuery` parameter is a function that takes the previous query data, * then a `{ subscriptionData: TSubscriptionResult }` object, * and returns an object with updated query data based on the new results. */ public subscribeToMore<TSubscriptionVariables, TSubscriptionData>( options: C.SubscribeToMoreOptions<Data<D>, TSubscriptionVariables, TSubscriptionData> ): (() => void) | void { return this.controller.subscribeToMore(options); } /** * Executes a Query once and updates the with the result */ public async executeQuery( params?: Partial<C.QueryOptions<Variables<D, V>, Data<D>>> ): Promise<C.ApolloQueryResult<Data<D>>> { return this.controller.executeQuery(params); } /** * Exposes the `ObservableQuery#fetchMore` method. * https://www.apollographql.com/docs/react/api/core/ObservableQuery/#ObservableQuery.fetchMore * * The optional `updateQuery` parameter is a function that takes the previous query data, * then a `{ subscriptionData: TSubscriptionResult }` object, * and returns an object with updated query data based on the new results. * * The optional `variables` parameter is an optional new variables object. */ public async fetchMore( params?: Partial<FetchMoreParams<D, V>> ): Promise<C.ApolloQueryResult<Data<D>>> { return this.controller.fetchMore(params); } public startPolling(ms: number): void { return this.controller.startPolling(ms); } public stopPolling(): void { return this.controller.stopPolling(); } /** * Optional callback for when a query is completed. */ onData?(data: Data<D>): void /** * Optional callback for when an error occurs. */ onError?(error: Error): void }
the_stack
import * as vscode from 'vscode'; import fs = require('fs-extra'); import * as path from 'path'; import { codeCovViewService, fcConnection, FCOauth, dxService, SObjectCategory, PXMLMember, notifications, getVSCodeSetting, commandViewService, } from '../services'; import { getToolingTypeFromExt, getAnyTTMetadataFromPath, outputToString } from '../parsers'; import { IWorkspaceMember, IMetadataObject, ICodeCoverage } from '../forceCode'; const mime = require('mime-types'); import * as compress from 'compressing'; import { parseString } from 'xml2js'; import { packageBuilder, FCCancellationToken, ForcecodeCommand, getMembers, getFolderContents, getAuraDefTypeFromDocument, } from '.'; import { XHROptions, xhr } from 'request-light'; import { toArray } from '../util'; export class Refresh extends ForcecodeCommand { constructor() { super(); this.commandName = 'ForceCode.refresh'; this.cancelable = true; this.name = 'Retrieving '; this.hidden = true; } public command(context: any, selectedResource?: any) { if (selectedResource instanceof Array) { return new Promise((resolve, reject) => { var files: PXMLMember[] = []; var proms: Promise<PXMLMember>[] = selectedResource.map(curRes => { if (curRes.fsPath.startsWith(vscode.window.forceCode.projectRoot + path.sep)) { return getAnyNameFromUri(curRes); } else { throw { message: "Only files/folders within the current org's src folder (" + vscode.window.forceCode.projectRoot + ') can be retrieved/refreshed.', }; } }); Promise.all(proms) .then(theNames => { theNames.forEach(curName => { var index: number = getTTIndex(curName.name, files); if (index >= 0) { // file deepcode ignore ComparisonArrayLiteral: <please specify a reason of ignoring this> if (curName.members === ['*']) { files[index].members = ['*']; } else { files[index].members.push(...curName.members); } } else { files.push(curName); } }); resolve(retrieve({ types: files }, this.cancellationToken)); }) .catch(reject); }); } if (context) { return retrieve(context, this.cancellationToken); } if (!vscode.window.activeTextEditor) { return undefined; } return retrieve(vscode.window.activeTextEditor.document.uri, this.cancellationToken); function getTTIndex(toolType: string, arr: ToolingType[]): number { return arr.findIndex(cur => { return cur.name === toolType && cur.members !== ['*']; }); } } } export class RetrieveBundle extends ForcecodeCommand { constructor() { super(); this.commandName = 'ForceCode.retrievePackage'; this.cancelable = true; this.name = 'Retrieving package'; this.hidden = false; this.description = 'Retrieve metadata to your src directory.'; this.detail = 'You can choose to retrieve by your package.xml, retrieve all metadata, or choose which types to retrieve.'; this.icon = 'cloud-download'; this.label = 'Retrieve Package/Metadata'; } public command(context: vscode.Uri | ToolingTypes | undefined) { return retrieve(context, this.cancellationToken); } } export interface ToolingType { name: string; members: string[]; } interface ToolingTypes { types: ToolingType[]; } export function retrieve( resource: vscode.Uri | ToolingTypes | undefined, cancellationToken: FCCancellationToken ) { let option: any; var newWSMembers: IWorkspaceMember[] = []; var toolTypes: Array<{}> = []; var typeNames: Array<string> = []; var packageName: string | undefined; return Promise.resolve(vscode.window.forceCode) .then(showPackageOptions) .then(getPackage) .then(processResult) .then(finished); // ======================================================================================================================================= // ======================================================================================================================================= // ======================================================================================================================================= function getPackages(): Promise<any> { if (!fcConnection.currentConnection) { return Promise.reject('No current connection'); } var orgInfo: FCOauth = fcConnection.currentConnection.orgInfo; var requestUrl: string = orgInfo.instanceUrl + '/_ui/common/apex/debug/ApexCSIAPI'; const foptions: XHROptions = { type: 'POST', url: requestUrl, headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', Cookie: 'sid=' + orgInfo.accessToken, }, data: 'action=EXTENT&extent=PACKAGES', }; return xhr(foptions) .then(response => { if (response.status === 200) { return response.responseText; } else { return JSON.stringify({ PACKAGES: { packages: [] } }); } }) .then((json: string) => { if (json.trim().startsWith('<')) { return []; } else { return JSON.parse(json.replace('while(1);\n', '')).PACKAGES.packages; } }) .catch(() => { return []; }); } function showPackageOptions(): Promise<any> { if (resource !== undefined) { return Promise.resolve(); } return getPackages().then(packages => { let options: vscode.QuickPickItem[] = packages.map((pkg: any) => { return { label: `$(briefcase) ${pkg.Name}`, detail: `Package ${pkg.Id}`, description: pkg.Name, }; }); options.push({ label: '$(package) Retrieve by package.xml', detail: `Packaged (Retrieve metadata defined in Package.xml)`, description: 'packaged', }); options.push({ label: '$(check) Choose types...', detail: `Choose which metadata types to retrieve`, description: 'user-choice', }); options.push({ label: '$(cloud-download) Get All Files from org', detail: `All Unpackaged`, description: 'unpackaged', }); options.push({ label: '$(cloud-download) Get All Apex Classes from org', detail: `All Apex Classes`, description: 'apexclasses', }); options.push({ label: '$(cloud-download) Get All Apex Pages from org', detail: `All Apex Pages`, description: 'apexpages', }); options.push({ label: '$(cloud-download) Get All Aura Components from org', detail: `All Aura Bundles`, description: 'aurabundles', }); options.push({ label: '$(cloud-download) Get All Standard Objects from org', detail: `All Standard Objects`, description: 'standardobj', }); options.push({ label: '$(cloud-download) Get All Custom Objects from org', detail: `All Custom Objects`, description: 'customobj', }); let config: {} = { matchOnDescription: true, matchOnDetail: true, placeHolder: 'Retrieve Package', }; return vscode.window.showQuickPick(options, config).then(res => { if (!res) { return Promise.reject(cancellationToken.cancel()); } return res; }); }); } // ======================================================================================================================================= function getPackage(opt: vscode.QuickPickItem): Promise<any> { option = opt; vscode.window.forceCode.conn.metadata.pollTimeout = (vscode.window.forceCode.config.pollTimeout || 600) * 1000; if (opt) { return new Promise(pack); } else if (resource) { return new Promise(function(resolve, reject) { // Get the Metadata Object type if (resource instanceof vscode.Uri) { getAnyNameFromUri(resource) .then(names => { retrieveComponents(resolve, reject, { types: [names] }); }) .catch(reject); } else { retrieveComponents(resolve, reject, resource); } }); } throw new Error(); function retrieveComponents(resolve: any, reject: any, retrieveTypes: ToolingTypes) { // count the number of types. if it's more than 10,000 the retrieve will fail var totalTypes: number = 0; retrieveTypes.types.forEach(type => { totalTypes += type.members.length; }); if (totalTypes > 10000) { reject({ message: 'Cannot retrieve more than 10,000 files at a time. Please select "Choose Types..." from the retrieve menu and try to download without Reports selected first.', }); } if (cancellationToken.isCanceled()) { reject(); } var theStream = vscode.window.forceCode.conn.metadata.retrieve({ unpackaged: retrieveTypes, apiVersion: vscode.window.forceCode.config.apiVersion || getVSCodeSetting('defaultApiVersion'), }); theStream.on('error', error => { reject( error || { message: 'Cannot retrieve more than 10,000 files at a time. Please select "Choose Types..." from the retrieve menu and try to download without Reports selected first.', } ); }); resolve(theStream.stream()); } function pack(resolve: any, reject: any) { if (option.description === 'unpackaged') { all(); } else if (option.description === 'packaged') { unpackaged(); } else if (option.description === 'apexclasses') { getSpecificTypeMetadata('ApexClass'); } else if (option.description === 'apexpages') { getSpecificTypeMetadata('ApexPage'); } else if (option.description === 'aurabundles') { getSpecificTypeMetadata('AuraDefinitionBundle'); } else if (option.description === 'customobj') { getObjects(SObjectCategory.CUSTOM); } else if (option.description === 'standardobj') { getObjects(SObjectCategory.STANDARD); } else if (option.description === 'user-choice') { builder(); } else { packageName = option.description; if (packageName) { packaged(); } else { reject(); } } function packaged() { // option.description is the package name if (cancellationToken.isCanceled()) { reject(); } var theStream = vscode.window.forceCode.conn.metadata.retrieve({ packageNames: [option.description], apiVersion: vscode.window.forceCode.config.apiVersion || getVSCodeSetting('defaultApiVersion'), }); theStream.on('error', error => { reject( error || { message: 'There was an error retrieving ' + option.description, } ); }); resolve(theStream.stream()).catch(reject); } function builder() { packageBuilder() .then(mappedTypes => { retrieveComponents(resolve, reject, { types: mappedTypes }); }) .catch(reject); } function all() { getMembers(['*'], true) .then(mappedTypes => { retrieveComponents(resolve, reject, { types: mappedTypes }); }) .catch(reject); } function getSpecificTypeMetadata(metadataType: string) { if (!vscode.window.forceCode.describe) { return reject( 'Metadata describe error. Please try logging out of and back into the org.' ); } var types: any[] = vscode.window.forceCode.describe.metadataObjects .filter(o => o.xmlName === metadataType) .map(r => { return { name: r.xmlName, members: '*' }; }); retrieveComponents(resolve, reject, { types: types }); } function unpackaged() { var xmlFilePath: string = `${vscode.window.forceCode.projectRoot}${path.sep}package.xml`; var data: any = fs.readFileSync(xmlFilePath); parseString(data, { explicitArray: false }, function(err, dom) { if (err) { reject(err); } else { delete dom.Package.$; if (!dom.Package.types) { reject({ message: 'No types element found to retrieve in the package.xml file.' }); } if (!dom.Package.version) { reject({ message: 'No version element found in package.xml file.' }); } const typeWithoutMembersOrName = toArray(dom.Package.types).find(curType => { return !curType.members || !curType.name; }); if (typeWithoutMembersOrName) { if (typeWithoutMembersOrName.name) { reject({ message: typeWithoutMembersOrName.name + ' element has no members element defined to retrieve in package.xml file.', }); } else { reject({ message: 'package.xml file contains a type element without a name element', }); } } if (cancellationToken.isCanceled()) { reject(); } try { resolve( vscode.window.forceCode.conn.metadata .retrieve({ unpackaged: dom.Package, }) .stream() ); } catch (e) { reject(e); } } }); } function getObjects(type: SObjectCategory) { dxService.describeGlobal(type).then(objs => { retrieveComponents(resolve, reject, { types: [{ name: 'CustomObject', members: objs }] }); }); } } } function processResult(stream: fs.ReadStream): Promise<any> { return new Promise(function(resolve, reject) { cancellationToken.cancellationEmitter.on('cancelled', function() { stream.pause(); reject(stream.emit('end')); }); var resBundleNames: string[] = []; const destDir: string = vscode.window.forceCode.projectRoot; new compress.zip.UncompressStream({ source: stream }) .on('error', function(err: any) { reject(err || { message: 'package not found' }); }) .on('entry', function(header: any, stream: any, next: any) { stream.on('end', next); var name = path.normalize(header.name).replace('unpackaged' + path.sep, ''); name = packageName ? name.replace(packageName + path.sep, '') : name; if (header.type === 'file') { const tType: string | undefined = getToolingTypeFromExt(name); const fullName = name.split(path.sep).pop(); if (tType && fullName) { // add to ws members var wsMem: IWorkspaceMember = { name: fullName.split('.')[0], path: `${vscode.window.forceCode.projectRoot}${path.sep}${name}`, id: '', //metadataFileProperties.id, type: tType, coverage: new Map<string, ICodeCoverage>(), }; newWSMembers.push(wsMem); if (!typeNames.includes(tType)) { typeNames.push(tType); toolTypes.push({ type: tType }); } } if (name.endsWith('.resource-meta.xml')) { resBundleNames.push(name); } if (name !== 'package.xml' || vscode.window.forceCode.config.overwritePackageXML) { if (!fs.existsSync(path.dirname(path.join(destDir, name)))) { fs.mkdirpSync(path.dirname(path.join(destDir, name))); } stream.pipe(fs.createWriteStream(path.join(destDir, name))); } else { next(); } } else { // directory fs.mkdirpSync(path.join(destDir, header.name)); stream.resume(); } }) .on('finish', () => { resBundleNames.forEach(metaName => { const data: string = fs.readFileSync(path.join(destDir, metaName)).toString(); // unzip the resource parseString(data, { explicitArray: false }, function(err, dom) { if (!err) { var actualResData = fs.readFileSync( path.join(destDir, metaName).split('-meta.xml')[0] ); var ContentType: string = dom.StaticResource.contentType; var ctFolderName = ContentType.split('/').join('.'); const resFN: string = metaName.slice(metaName.indexOf(path.sep) + 1).split('.')[0]; var zipFilePath: string = path.join( destDir, 'resource-bundles', resFN + '.resource.' + ctFolderName ); if (ContentType.includes('gzip')) { compress.gzip.uncompress(actualResData, zipFilePath); } else if (ContentType.includes('zip')) { compress.zip.uncompress(actualResData, zipFilePath); } else { // this will work for most other things... var theData: any; if (ContentType.includes('image') || ContentType.includes('shockwave-flash')) { theData = Buffer.from(actualResData.toString('base64'), 'base64'); } else { theData = actualResData.toString(mime.charset(ContentType) || 'UTF-8'); } var ext = mime.extension(ContentType); var filePath: string = path.join( destDir, 'resource-bundles', resFN + '.resource.' + ctFolderName, resFN + '.' + ext ); fs.outputFileSync(filePath, theData); } } }); }); resolve({ success: true }); }); }); } // ======================================================================================================================================= // ======================================================================================================================================= // ======================================================================================================================================= function finished(res: any): Promise<any> { if (res.success) { notifications.writeLog('Done retrieving files'); // check the metadata and add the new members return updateWSMems().then(() => { if (option) { notifications.showStatus(`Retrieve ${option.description} $(thumbsup)`); } else { notifications.showStatus(`Retrieve $(thumbsup)`); } return Promise.resolve(res); }); function updateWSMems(): Promise<any> { if (toolTypes.length > 0) { var theTypes: { [key: string]: Array<any> } = {}; theTypes['type0'] = toolTypes; if (theTypes['type0'].length > 3) { for (var i = 1; theTypes['type0'].length > 3; i++) { theTypes['type' + i] = theTypes['type0'].splice(0, 3); } } let proms = Object.keys(theTypes).map(curTypes => { const shouldGetCoverage = theTypes[curTypes].find(cur => { return cur.type === 'ApexClass' || cur.type === 'ApexTrigger'; }); if (shouldGetCoverage) { commandViewService.enqueueCodeCoverage(); } return vscode.window.forceCode.conn.metadata.list(theTypes[curTypes]); }); return Promise.all(proms).then(rets => { return parseRecords(rets); }); } else { return Promise.resolve(); } } function parseRecords(recs: any[]): Thenable<any> { notifications.writeLog('Done retrieving metadata records'); recs.some(curSet => { return toArray(curSet).some(key => { if (key && newWSMembers.length > 0) { var index: number = newWSMembers.findIndex(curMem => { return curMem.name === key.fullName && curMem.type === key.type; }); if (index >= 0) { newWSMembers[index].id = key.id; codeCovViewService.addClass(newWSMembers.splice(index, 1)[0]); } return false; } else { return true; } }); }); notifications.writeLog('Done updating/adding metadata'); return Promise.resolve(); } } else { notifications.showError('Retrieve Errors'); } notifications.writeLog( outputToString(res) .replace(/{/g, '') .replace(/}/g, '') ); return Promise.resolve(res); } // ======================================================================================================================================= } export function getAnyNameFromUri(uri: vscode.Uri, getDefType?: boolean): Promise<PXMLMember> { return new Promise(async (resolve, reject) => { const projRoot: string = vscode.window.forceCode.projectRoot + path.sep; if (uri.fsPath.indexOf(projRoot) === -1) { return reject( 'The file you are attempting to save/retrieve/delete (' + uri.fsPath + ') is outside of ' + vscode.window.forceCode.projectRoot ); } const ffNameParts: string[] = uri.fsPath.split(projRoot)[1].split(path.sep); var baseDirectoryName: string = path.parse(uri.fsPath).name; const isAura: boolean = ffNameParts[0] === 'aura'; const isLWC: boolean = ffNameParts[0] === 'lwc'; const isDir: boolean = fs.lstatSync(uri.fsPath).isDirectory(); const tType: IMetadataObject | undefined = getAnyTTMetadataFromPath(uri.fsPath); const isResource: boolean = ffNameParts[0] === 'resource-bundles'; if (isResource) { if (ffNameParts.length === 1) { // refresh all bundles return resolve({ name: 'StaticResource', members: ['*'] }); } else { // refresh specific bundle const members: string = ffNameParts[1].split('.resource').shift() || '*'; return resolve({ name: 'StaticResource', members: [members] }); } } if (!tType) { return reject( "Either the file/metadata type doesn't exist in the current org or you're trying to save/retrieve/delete outside of " + vscode.window.forceCode.projectRoot ); } var folderedName: string; if (tType.inFolder && ffNameParts.length > 2) { // we have foldered metadata ffNameParts.shift(); folderedName = ffNameParts.join('/').split('.')[0]; return resolve({ name: tType.xmlName, members: [folderedName] }); } else if (isDir) { if (isAura || isLWC) { if (baseDirectoryName === 'aura' || baseDirectoryName === 'lwc') { baseDirectoryName = '*'; } return resolve({ name: tType.xmlName, members: [baseDirectoryName] }); } else if (tType.inFolder && ffNameParts.length > 1) { return getFolderContents(tType.xmlName, ffNameParts[1]).then(contents => { return resolve({ name: tType.xmlName, members: contents }); }); } else { return getMembers([tType.xmlName], true).then(members => { return resolve(members[0]); }); } } else { var defType: string | undefined; const retObj: PXMLMember = { name: tType.xmlName, members: [] }; if (isAura && getDefType) { defType = getAuraDefTypeFromDocument(await vscode.workspace.openTextDocument(uri.fsPath)); if ( defType === 'COMPONENT' || defType === 'APPLICATION' || defType === 'EVENT' || defType === 'INTERFACE' || defType === 'Metadata' ) { // used for deleting. we can't delete just the component or the metadata defType = undefined; } if (defType === 'CONTROLLER' || defType === 'HELPER' || defType === 'RENDERER') { baseDirectoryName = baseDirectoryName.substring( 0, baseDirectoryName.toUpperCase().lastIndexOf(defType) ); } retObj.defType = defType; } baseDirectoryName = baseDirectoryName.split('.')[0]; retObj.members = [baseDirectoryName]; return resolve(retObj); } }); }
the_stack
var conversationServer = angular.module("webim.conversation.server", []); conversationServer.factory("conversationServer", ["$q", "mainDataServer", "mainServer", "RongIMSDKServer", function($q: any, mainDataServer: mainDataServer, mainServer: mainServer, RongIMSDKServer: RongIMSDKServer) { var conversationServer = <any>{}; conversationServer.atMessagesCache = <any>{}; conversationServer.historyMessagesCache = <any>{}; conversationServer.conversationMessageList = <any>[]; conversationServer.conversationMessageListShow = <any>[]; conversationServer.pullMessageTime = null; conversationServer.remainMessageCount = 5; conversationServer.withDrawMessagesCache = <any>{}; function asyncConverGroupNotifition(msgsdk: any, item: any) { var detail = <any>msgsdk.content var comment = "", members = <any>[] var isself = detail.operatorUserId == mainDataServer.loginUser.id ? true : false; switch (detail.operation) { case "Add": if(isself){ comment = '你邀请' +detail.data.data.targetUserDisplayNames.join('、') + "加入了群组"; }else{ comment = detail.data.data.operatorNickname + '邀请' +detail.data.data.targetUserDisplayNames.join('、') + "加入了群组"; } members = detail.data.data.targetUserIds; break; case "Quit": comment = detail.data.data.targetUserDisplayNames.join('、') + "退出了群组" members = detail.data.data.targetUserIds; break; case "Kicked": if(isself){ comment = '你将' + detail.data.data.targetUserDisplayNames.join('、') + " 移出了群组"; }else{ comment = detail.data.data.operatorNickname + '将' + detail.data.data.targetUserDisplayNames.join('、') + " 移出了群组"; } members = detail.data.data.targetUserIds; break; case "Rename": if(isself){ comment = "你修改名称为" + detail.data.data.targetGroupName; // + detail.data.data.targetGroupName; }else{ comment = detail.data.data.operatorNickname + "修改群名称为" + detail.data.data.targetGroupName; } break; case "Create": if(detail.operatorUserId == mainDataServer.loginUser.id){ comment = "你创建了群组"; }else{ comment = detail.data.data.operatorNickname + "创建了群组"; } break; case "Dismiss": comment = detail.data.data.operatorNickname + "解散了群组"; break; default: console.log("未知群组通知"); } item.content = comment; // for (var i = 0, len = members.length; i < len; i++) { // mainServer.user.getInfo(members[i]).success(function(rep) { // if (item.content === comment) { // item.content = rep.result.nickname + item.content ; // } else { // item.content = rep.result.nickname + "、" + item.content ; // } // }) // } } function asyncConverDiscussionNotifition(msgsdk: any, item: any) { var detail = <any>msgsdk var comment = "", members = <any>[] switch (detail.content.type) { case 1: comment = " 加入讨论组"; members = detail.content.extension.split(','); break; case 2: comment = " 退出讨论组" members = detail.content.extension.split(','); break; case 4: comment = " 被踢出讨论组"; members = detail.content.extension.split(','); break; case 3: comment = " 讨论组更名"; break; default: console.log("未知讨论组通知"); } item.content = comment; mainServer.user.getBatchInfo(members).then(function (repmem) { var lists = repmem.data.result; var membersName:string[] = []; for (var j = 0, len = lists.length; j < len; j++) { membersName.push(lists[j].nickname); } if(membersName){ item.content = membersName.join('、') + item.content; } }); // for (var i = 0, len = members.length; i < len; i++) { // mainServer.user.getInfo(members[i]).success(function(rep) { // if (item.content === comment) { // item.content = rep.result.nickname + item.content ; // } else { // item.content = rep.result.nickname + "、" + item.content ; // } // }) // } } function getHistory(id: string, type: string, lastTime: number, count: number) { var d = $q.defer(); var conver = type; var currentConversationTargetId = id; if (!conversationServer.historyMessagesCache[conver + "_" + currentConversationTargetId]) { conversationServer.historyMessagesCache[conver + "_" + currentConversationTargetId] = []; } try { RongIMSDKServer.getHistoryMessages(+conver, currentConversationTargetId, lastTime, count).then(function(data) { var has = data.has, list = <RongIMLib.Message[]>data.data; var msglen = list.length; if(msglen > 0){ conversationServer.pullMessageTime = list[msglen - 1].sentTime; } var _withDrawMsg = conversationServer.withDrawMessagesCache[conver + "_" + currentConversationTargetId]; while (msglen--) { var msgsdk = list[msglen]; if(_withDrawMsg && _withDrawMsg.indexOf(msgsdk.messageUId) > -1){ continue; } msgsdk = webimmodel.Message.formatGIFMsg(msgsdk); switch (msgsdk.messageType) { case webimmodel.MessageType.ContactNotificationMessage: //历史邀请消息不做处理 break; case webimmodel.MessageType.TextMessage: case webimmodel.MessageType.VoiceMessage: case webimmodel.MessageType.LocationMessage: case webimmodel.MessageType.ImageMessage: case webimmodel.MessageType.RichContentMessage: case webimmodel.MessageType.FileMessage: var item = webimmodel.Message.convertMsg(msgsdk); if (item) { unshiftHistoryMessages(currentConversationTargetId, conver, item); } break; case webimmodel.MessageType.GroupNotificationMessage: if (msgsdk.objectName == "ST:GrpNtf") { var item = webimmodel.Message.convertMsg(msgsdk); if (item) { conversationServer.asyncConverGroupNotifition(msgsdk, item); unshiftHistoryMessages(currentConversationTargetId, conver, item); } } break; case webimmodel.MessageType.UnknownMessage: if (msgsdk.objectName == "ST:GrpNtf") { var item = webimmodel.Message.convertMsg(msgsdk); if (item) { conversationServer.asyncConverGroupNotifition(msgsdk, item); unshiftHistoryMessages(currentConversationTargetId, conver, item); } } break; case webimmodel.MessageType.RecallCommandMessage: if (msgsdk.objectName == "RC:RcCmd") { var item = webimmodel.Message.convertMsg(msgsdk); if (item) { conversationServer.delWithDrawMessage(item.senderUserId, item.conversationType, msgsdk.messageUId); unshiftHistoryMessages(currentConversationTargetId, conver, item); } conversationServer.addWithDrawMessageCache(item.senderUserId, item.conversationType, msgsdk.messageUId); } break; case webimmodel.MessageType.InformationNotificationMessage: var item = webimmodel.Message.convertMsg(msgsdk); if (item) { unshiftHistoryMessages(currentConversationTargetId, conver, item); } break; case webimmodel.MessageType.DiscussionNotificationMessage: if (msgsdk.objectName == "RC:DizNtf") { } break; default: console.log("此消息类型未处理:" + msgsdk.messageType); break; } } var addtime = conversationServer.historyMessagesCache[conver + "_" + currentConversationTargetId][0]; if (addtime && addtime.panelType != webimmodel.PanelType.Time) { unshiftHistoryMessages(currentConversationTargetId, conver, new webimmodel.TimePanl(conversationServer.historyMessagesCache[conver + "_" + currentConversationTargetId][0].sentTime)); } //遍历缓存,过滤撤回消息 // var _withDrawMsg = conversationServer.withDrawMessagesCache[conver + "_" + currentConversationTargetId]; // if(_withDrawMsg){ // for(var i = 0;i < _withDrawMsg.length;i++){ // delWithDrawMessage(currentConversationTargetId, conver, _withDrawMsg[i]); // } // } d.resolve(has); }, function(err: any) { d.reject(err); console.log('获取历史消息失败'); }); } catch (err) { console.log("SDK error" + err); } return d.promise; } function unshiftHistoryMessages(id: string, type: string, item: any) { var arr = conversationServer.historyMessagesCache[type + "_" + id] || []; if (arr[0] && item.messageUId && item.messageUId === arr[0].messageUId) { return; } if (arr[0] && arr[0].sentTime && arr[0].panelType != webimmodel.PanelType.Time && item.sentTime) { if (compareDateIsAddSpan(arr[0].sentTime, item.sentTime)) { arr.unshift(new webimmodel.TimePanl(arr[0].sentTime)); } } messageAddUserInfo(item); arr.unshift(item); } // 定时清理消息缓存 function clearHistoryMessages(id: string, type: string) { var currenthis = conversationServer.historyMessagesCache[type + "_" + id]; var counter = 0,counterAll = 0; for(var i = currenthis.length - 1; i > -1; i--){ if (currenthis[i].panelType == webimmodel.PanelType.Message) { counter++; } if (counter >= conversationServer.remainMessageCount && currenthis[i].panelType == webimmodel.PanelType.Time) { currenthis.splice(0, i); conversationServer.unshiftHistoryMessages(id, type, new webimmodel.GetMoreMessagePanel()); break; } } } function getLastMessageTime(id: string, type: string){ var currenthis = conversationServer.historyMessagesCache[type + "_" + id]; var sentTime = 0; for (var i = 0; i < currenthis.length; i++) { if (currenthis[i].panelType == webimmodel.PanelType.Message) { sentTime = (new Date(currenthis[i].sentTime)).getTime(); break; } } return sentTime; } function delWithDrawMessage(id: string, type: string, uid: string){ var currenthis = conversationServer.historyMessagesCache[type + "_" + id]; if(currenthis){ for (var i = 0; i < currenthis.length; i++) { if (currenthis[i].panelType == webimmodel.PanelType.Message && currenthis[i].messageUId == uid) { if(i > 0 && i < currenthis.length - 1 && currenthis[i - 1].panelType == webimmodel.PanelType.Time && currenthis[i + 1].panelType == webimmodel.PanelType.Time || i == currenthis.length - 1 && currenthis[i - 1].panelType == webimmodel.PanelType.Time ){ currenthis.splice(i-1, 2); } else{ currenthis.splice(i, 1); } break; } } } // function dealWithDrawMessage(id: string, type: string, uid: string){ // var currenthis = conversationServer.historyMessagesCache[type + "_" + id]; // if(currenthis){ // for (var i = 0; i < currenthis.length; i++) { // if (currenthis[i].panelType == webimmodel.PanelType.Message && currenthis[i].messageUId == uid) { // if(i > 0 && i < currenthis.length - 1 && currenthis[i - 1].panelType == webimmodel.PanelType.Time && currenthis[i + 1].panelType == webimmodel.PanelType.Time // || i == currenthis.length - 1 && currenthis[i - 1].panelType == webimmodel.PanelType.Time // ){ // currenthis.splice(i-1, 2); // } // else{ // currenthis.splice(i, 1); // } // break; // } // } // } currenthis = conversationServer.conversationMessageList; if(currenthis){ for (var i = 0; i < currenthis.length; i++) { if (currenthis[i].panelType == webimmodel.PanelType.Message && currenthis[i].messageUId == uid) { if(i > 0 && i < currenthis.length - 1 && currenthis[i - 1].panelType == webimmodel.PanelType.Time && currenthis[i + 1].panelType == webimmodel.PanelType.Time || i == currenthis.length - 1 && currenthis[i - 1].panelType == webimmodel.PanelType.Time ){ currenthis.splice(i-1, 2); } else{ currenthis.splice(i, 1); } break; } } } currenthis = conversationServer.conversationMessageListShow; if(currenthis){ for (var i = 0; i < currenthis.length; i++) { if (currenthis[i].panelType == webimmodel.PanelType.Message && currenthis[i].messageUId == uid) { if(i > 0 && i < currenthis.length - 1 && currenthis[i - 1].panelType == webimmodel.PanelType.Time && currenthis[i + 1].panelType == webimmodel.PanelType.Time || i == currenthis.length - 1 && currenthis[i - 1].panelType == webimmodel.PanelType.Time ){ currenthis.splice(i-1, 2); } else{ currenthis.splice(i, 1); } break; } } } } function compareDateIsAddSpan(first: Date, second: Date) { if (Object.prototype.toString.call(first) == "[object Date]" && Object.prototype.toString.call(second) == "[object Date]") { var pre = first.toString(); var cur = second.toString(); return pre.substring(0, pre.lastIndexOf(":")) != cur.substring(0, cur.lastIndexOf(":")) } else { return false; } } function addHistoryMessages(id: string, type: string, item: webimmodel.Message) { var arr = conversationServer.historyMessagesCache[type + "_" + id] || []; var exist = false; // if(item.senderUserId != mainDataServer.loginUser.id){ exist = checkMessageExist(id, type, item.messageUId); if (exist) { console.log('exist离线消息有重复'); return; } // } if (arr[arr.length - 1] && arr[arr.length - 1].panelType != webimmodel.PanelType.Time && arr[arr.length - 1].sentTime && item.sentTime) { if (compareDateIsAddSpan(arr[arr.length - 1].sentTime, item.sentTime)) { arr.push(new webimmodel.TimePanl(item.sentTime)); //判断如果是当前会话的消息则加入 if (type == mainDataServer.conversation.currentConversation.targetType && id == mainDataServer.conversation.currentConversation.targetId) { conversationServer.conversationMessageListShow.push(new webimmodel.TimePanl(item.sentTime)); } } } messageAddUserInfo(item); arr.push(item); //判断如果是当前会话的消息则加入 if (type == mainDataServer.conversation.currentConversation.targetType && id == mainDataServer.conversation.currentConversation.targetId) { conversationServer.conversationMessageListShow.push(item); } } function addAtMessage(id: string, type: string, item: webimmodel.Message){ if (!conversationServer.atMessagesCache[type + "_" + id]) { conversationServer.atMessagesCache[type + "_" + id] = []; } var atMsg = { "messageUId": item.messageUId, "mentionedInfo": item.mentionedInfo }; conversationServer.atMessagesCache[type + "_" + id].push(atMsg); } function addWithDrawMessageCache(id: string, type: string, msgUid: string){ if (!conversationServer.withDrawMessagesCache[type + "_" + id]) { conversationServer.withDrawMessagesCache[type + "_" + id] = []; } conversationServer.withDrawMessagesCache[type + "_" + id].push(msgUid); } //消息里没有用户信息,要去本地的好友列表里查找 function messageAddUserInfo(item: webimmodel.Message) { if (!item.senderUserId) { return item; } var user: webimmodel.Contact; if (item.messageDirection == 1) { item.senderUserName = mainDataServer.loginUser.nickName; item.imgSrc = mainDataServer.loginUser.portraitUri; item.senderUserImgSrc = mainDataServer.loginUser.firstchar; } else { switch (item.conversationType) { case webimmodel.conversationType.Private: user = mainDataServer.contactsList.getFriendById(item.senderUserId); if(!user){ user = mainDataServer.contactsList.getNonFriendById(item.senderUserId); } break; case webimmodel.conversationType.Group: user = mainDataServer.contactsList.getGroupMember(item.targetId, item.senderUserId); break; case webimmodel.conversationType.Discussion: user = mainDataServer.contactsList.getDiscussionMember(item.targetId, item.senderUserId); break; case webimmodel.conversationType.System: // user = mainDataServer.contactsList.getFriendById(item.senderUserId); // if (user) { user = new webimmodel.Contact(); user.name = "系统消息"; // } break; default: console.log("暂不支持此会话类型"); } if (user) { item.senderUserName = user.displayName || user.name; item.senderUserImgSrc = user.firstchar; item.imgSrc = user.imgSrc } else { if(item.senderUserId == '__system__') { return; } mainServer.user.getInfo(item.senderUserId).success(function(rep) { if (rep.code == 200) { item.senderUserName = rep.result.nickname; item.senderUserImgSrc = webimutil.ChineseCharacter.getPortraitChar(rep.result.nickname); item.imgSrc = rep.result.portraitUri; var _friend = new webimmodel.Friend({ id: item.senderUserId, name: item.senderUserName + '(非好友)', imgSrc: item.imgSrc }); _friend.firstchar = item.senderUserImgSrc; mainDataServer.contactsList.addNonFriend(_friend); } }).error(function() { //之前可能清过库没有这个用户TODO:删掉 console.log("无此用户:" + item.senderUserId); }); } } return item; } function updateHistoryMessagesCache(id: string, type: string, name: string, portrait: string){ var currenthis = conversationServer.historyMessagesCache[type + "_" + id]; angular.forEach(currenthis, function(value, key){ if (value.panelType == webimmodel.PanelType.Message && value.senderUserId == id){ value.senderUserName = name; value.imgSrc = portrait; //TODO 重新计算头像 // senderUserImgSrc } }); } function checkMessageExist(id: string, type: string, messageuid: string){ var currenthis = conversationServer.historyMessagesCache[type + "_" + id]; var keepGoing = true; if(!messageuid){ return false; } angular.forEach(currenthis, function (value, key) { if(keepGoing){ if (value.panelType == webimmodel.PanelType.Message && value.messageUId == messageuid) { keepGoing = false; } } }); return !keepGoing; } function updateSendMessage(id: string, type: string, msg: webimmodel.Message){ var currenthis = conversationServer.historyMessagesCache[type + "_" + id]; for(var i = currenthis.length - 1; i > -1; i--){ if (currenthis[i].panelType == webimmodel.PanelType.Message && currenthis[i].messageUId == undefined && currenthis[i].messageDirection == webimmodel.MessageDirection.SEND && currenthis[i].messageId == msg.messageId ) { currenthis[i].messageUId = msg.messageUId; currenthis[i].sentStatus = webimmodel.SentStatus.SENT; currenthis.splice(i, 1, msg); break; } } } function getMessageById(id: string, type: string, messageuid: string){ var currenthis = conversationServer.historyMessagesCache[type + "_" + id]; var keepGoing = true; var msg:webimmodel.Message = null; angular.forEach(currenthis, function (value, key) { if(keepGoing){ if (value.panelType == webimmodel.PanelType.Message && value.messageUId == messageuid) { keepGoing = false; msg = value; } } }); return msg; } function sendReadReceiptMessage(id: string, type: number, messageuid: string, sendtime: number){ var messageUId = messageuid; var lastMessageSendTime = sendtime; // if(targetType != webimmodel.conversationType.Private && targetType != webimmodel.conversationType.Group){ if(type != webimmodel.conversationType.Private){ return; } var msg = RongIMLib.ReadReceiptMessage.obtain(messageUId, lastMessageSendTime, 1); RongIMSDKServer.sendMessage(type, id, msg).then(function() { }, function(error) { console.log('sendReadReceiptMessage error', error.errorCode); }); } function sendSyncReadStatusMessage(id: string, type: number, sendtime: number){ var lastMessageSendTime = sendtime; if(type != webimmodel.conversationType.Group){ return; } var msg = new RongIMLib.SyncReadStatusMessage({lastMessageSendTime: sendtime}); RongIMSDKServer.sendMessage(type, id, msg).then(function() { }, function(error) { console.log('sendSyncReadStatusMessage error', error.errorCode); }); } conversationServer.getHistory = getHistory; conversationServer.addHistoryMessages = addHistoryMessages; conversationServer.messageAddUserInfo = messageAddUserInfo; conversationServer.unshiftHistoryMessages = unshiftHistoryMessages; conversationServer.asyncConverGroupNotifition = asyncConverGroupNotifition; conversationServer.asyncConverDiscussionNotifition = asyncConverDiscussionNotifition; conversationServer.updateHistoryMessagesCache = updateHistoryMessagesCache; conversationServer.checkMessageExist = checkMessageExist; conversationServer.addAtMessage = addAtMessage; conversationServer.clearHistoryMessages = clearHistoryMessages; conversationServer.getLastMessageTime = getLastMessageTime; conversationServer.getMessageById = getMessageById; conversationServer.updateSendMessage = updateSendMessage; conversationServer.delWithDrawMessage = delWithDrawMessage; conversationServer.addWithDrawMessageCache = addWithDrawMessageCache; conversationServer.sendReadReceiptMessage = sendReadReceiptMessage; conversationServer.sendSyncReadStatusMessage = sendSyncReadStatusMessage; return conversationServer; }]) interface conversationServer { atMessagesCache: any withDrawMessagesCache: any pullMessageTime: number historyMessagesCache: any conversationMessageList: any[] conversationMessageListShow: any[] getHistory(id: string, type: number, lasttime: number, count: number): angular.IPromise<any> addHistoryMessages(id: string, type: number, item: webimmodel.Message): void messageAddUserInfo(item: webimmodel.Message): void unshiftHistoryMessages(id: string, type: number, item: any): void asyncConverGroupNotifition(msgsdk: any, item: any): void asyncConverDiscussionNotifition(msgsdk: any, item: any): void uploadFileToken: string initUpload(): void updateHistoryMessagesCache(id: string, type:number, name: string, portrait: string): void checkMessageExist(id: string, type:number, messageuid: string): boolean addAtMessage(id: string, type: number, item: webimmodel.Message): void getMessageById(id: string, type:number, messageuid: string): webimmodel.Message clearHistoryMessages(id: string, type: number): void getLastMessageTime(id: string, type: number): number updateSendMessage(id: string, type: number, message: webimmodel.Message): void delWithDrawMessage(id: string, type:number, messageuid: string): void addWithDrawMessageCache(id: string, type:number, messageuid: string): void sendReadReceiptMessage(id: string, type:number, messageuid: string, sendtime: number): void sendSyncReadStatusMessage(id: string, type:number, sendtime: number): void }
the_stack
import type { Configuration, Compiler, RuleSetRule, Stats } from 'webpack'; import { join, dirname } from 'path'; import { mergeWith, flatten, zip } from 'lodash'; import { writeFileSync, realpathSync } from 'fs'; import { compile, registerHelper } from 'handlebars'; import jsStringEscape from 'js-string-escape'; import { BundleDependencies, ResolvedTemplateImport } from './splitter'; import { BuildResult, Bundler, BundlerOptions } from './bundler'; import type { InputNode } from 'broccoli-node-api'; import Plugin from 'broccoli-plugin'; import { babelFilter, packageName } from '@embroider/shared-internals'; import { Options } from './package'; import { PackageCache } from '@embroider/shared-internals'; import { Memoize } from 'typescript-memoize'; import makeDebug from 'debug'; import { ensureDirSync, symlinkSync, existsSync } from 'fs-extra'; const debug = makeDebug('ember-auto-import:webpack'); registerHelper('js-string-escape', jsStringEscape); registerHelper('join', function (list, connector) { return list.join(connector); }); const entryTemplate = compile(` module.exports = (function(){ var d = _eai_d; var r = _eai_r; window.emberAutoImportDynamic = function(specifier) { if (arguments.length === 1) { return r('_eai_dyn_' + specifier); } else { return r('_eai_dynt_' + specifier)(Array.prototype.slice.call(arguments, 1)) } }; window.emberAutoImportSync = function(specifier) { {{! this is only used for synchronous importSync() using a template string }} return r('_eai_sync_' + specifier)(Array.prototype.slice.call(arguments, 1)) }; {{#each staticImports as |module|}} d('{{js-string-escape module.specifier}}', [], function() { return require('{{js-string-escape module.specifier}}'); }); {{/each}} {{#each dynamicImports as |module|}} d('_eai_dyn_{{js-string-escape module.specifier}}', [], function() { return import('{{js-string-escape module.specifier}}'); }); {{/each}} {{#each staticTemplateImports as |module|}} d('_eai_sync_{{js-string-escape module.key}}', [], function() { return function({{module.args}}) { return require({{{module.template}}}); } }); {{/each}} {{#each dynamicTemplateImports as |module|}} d('_eai_dynt_{{js-string-escape module.key}}', [], function() { return function({{module.args}}) { return import({{{module.template}}}); } }); {{/each}} })(); `) as (args: { staticImports: { specifier: string }[]; dynamicImports: { specifier: string }[]; staticTemplateImports: { key: string; args: string; template: string }[]; dynamicTemplateImports: { key: string; args: string; template: string }[]; publicAssetURL: string | undefined; }) => string; // this goes in a file by itself so we can tell webpack not to parse it. That // allows us to grab the "require" and "define" from our enclosing scope without // webpack messing with them. // // It's important that we're using our enclosing scope and not jumping directly // to window.require (which would be easier), because the entire Ember app may be // inside a closure with a "require" that isn't the same as "window.require". const loader = ` window._eai_r = require; window._eai_d = define; `; export default class WebpackBundler extends Plugin implements Bundler { private state: | { webpack: Compiler; stagingDir: string; } | undefined; private lastBuildResult: BuildResult | undefined; constructor(priorTrees: InputNode[], private opts: BundlerOptions) { super(priorTrees, { persistentOutput: true, needsCache: true, annotation: 'ember-auto-import-webpack', }); } get buildResult() { if (!this.lastBuildResult) { throw new Error(`bug: no buildResult available yet`); } return this.lastBuildResult; } private get webpack() { return this.setup().webpack; } private get stagingDir() { return this.setup().stagingDir; } private setup() { if (this.state) { return this.state; } // resolve the real path, because we're going to do path comparisons later // that could fail if this is not canonical. // // cast is ok because we passed needsCache to super let stagingDir = realpathSync(this.cachePath!); let entry: { [name: string]: string[] } = {}; this.opts.bundles.names.forEach(bundle => { entry[bundle] = [join(stagingDir, 'l.js'), join(stagingDir, `${bundle}.js`)]; }); let config: Configuration = { mode: this.opts.environment === 'production' ? 'production' : 'development', entry, performance: { hints: false, }, // this controls webpack's own runtime code generation. You still need // preset-env to preprocess the libraries themselves (which is already // part of this.opts.babelConfig) target: `browserslist:${this.opts.browserslist}`, output: { path: join(this.outputPath, 'assets'), publicPath: this.opts.publicAssetURL, filename: `chunk.[id].[chunkhash].js`, chunkFilename: `chunk.[id].[chunkhash].js`, libraryTarget: 'var', library: '__ember_auto_import__', }, optimization: { splitChunks: { chunks: 'all', }, }, resolveLoader: { alias: { // these loaders are our dependencies, not the app's dependencies. I'm // not overriding the default loader resolution rules in case the app also // wants to control those. 'babel-loader-8': require.resolve('babel-loader'), 'eai-style-loader': require.resolve('style-loader'), 'eai-css-loader': require.resolve('css-loader'), }, }, resolve: { extensions: ['.js', '.ts', '.json'], mainFields: ['browser', 'module', 'main'], alias: Object.assign({}, ...[...this.opts.packages].map(pkg => pkg.aliases).filter(Boolean)), }, module: { noParse: (file: string) => file === join(stagingDir, 'l.js'), rules: [ this.babelRule(stagingDir), { test: /\.css$/i, use: [ { loader: 'eai-style-loader', options: [...this.opts.packages].find(pkg => pkg.styleLoaderOptions)?.styleLoaderOptions, }, { loader: 'eai-css-loader', options: [...this.opts.packages].find(pkg => pkg.cssLoaderOptions)?.cssLoaderOptions, }, ], }, ], }, node: false, externals: this.externalsHandler, }; mergeConfig(config, ...[...this.opts.packages].map(pkg => pkg.webpackConfig)); if ([...this.opts.packages].find(pkg => pkg.forbidsEval)) { config.devtool = 'source-map'; } debug('webpackConfig %j', config); this.state = { webpack: this.opts.webpack(config), stagingDir }; return this.state; } private skipBabel(): Required<Options>['skipBabel'] { let output: Required<Options>['skipBabel'] = []; for (let pkg of this.opts.packages) { let skip = pkg.skipBabel; if (skip) { output = output.concat(skip); } } return output; } private babelRule(stagingDir: string): RuleSetRule { let shouldTranspile = babelFilter(this.skipBabel()); return { test(filename: string) { // We don't apply babel to our own stagingDir (it contains only our own // entrypoints that we wrote, and it can use `import()`, which we want // to leave directly for webpack). // // And we otherwise defer to the `skipBabel` setting as implemented by // `@embroider/shared-internals`. return dirname(filename) !== stagingDir && shouldTranspile(filename); }, use: { loader: 'babel-loader-8', options: this.opts.babelConfig, }, }; } @Memoize() private get externalsHandler(): Configuration['externals'] { let packageCache = PackageCache.shared('ember-auto-import'); return function (params, callback) { let { context, request } = params; if (!context || !request) { return callback(); } if (request.startsWith('!')) { return callback(); } let name = packageName(request); if (!name) { // we're only interested in handling inter-package resolutions return callback(); } let pkg = packageCache.ownerOfFile(context); if (!pkg?.isV2Addon()) { // we're only interested in imports that appear inside v2 addons return callback(); } try { let found = packageCache.resolve(name, pkg); if (!found.isEmberPackage() || found.isV2Addon()) { // if we're importing a non-ember package or a v2 addon, we don't // externalize. Those are all "normal" looking packages that should be // resolvable statically. return callback(); } else { // the package exists but it is a v1 ember addon, so it's not // resolvable at build time, so we externalize it. return callback(undefined, 'commonjs ' + request); } } catch (err) { if (err.code !== 'MODULE_NOT_FOUND') { throw err; } // real package doesn't exist, so externalize it return callback(undefined, 'commonjs ' + request); } }; } async build(): Promise<void> { let bundleDeps = await this.opts.splitter.deps(); for (let [bundle, deps] of bundleDeps.entries()) { this.writeEntryFile(bundle, deps); } this.writeLoaderFile(); this.linkDeps(bundleDeps); let stats = await this.runWebpack(); this.lastBuildResult = this.summarizeStats(stats, bundleDeps); } private summarizeStats(_stats: Required<Stats>, bundleDeps: Map<string, BundleDependencies>): BuildResult { let { entrypoints, assets } = _stats.toJson(); // webpack's types are written rather loosely, implying that these two // properties may not be present. They really always are, as far as I can // tell, but we need to check here anyway to satisfy the type checker. if (!entrypoints) { throw new Error(`unexpected webpack output: no entrypoints`); } if (!assets) { throw new Error(`unexpected webpack output: no assets`); } let output: BuildResult = { entrypoints: new Map(), lazyAssets: [] as string[], }; let nonLazyAssets: Set<string> = new Set(); for (let id of Object.keys(entrypoints!)) { let { assets: entrypointAssets } = entrypoints![id]; if (!entrypointAssets) { throw new Error(`unexpected webpack output: no entrypoint.assets`); } // our built-in bundles can be "empty" while still existing because we put // setup code in them, so they get a special check for non-emptiness. // Whereas any other bundle that was manually configured by the user // should always be emitted. if (!this.opts.bundles.isBuiltInBundleName(id) || nonEmptyBundle(id, bundleDeps)) { output.entrypoints.set( id, entrypointAssets.map(a => 'assets/' + a.name) ); } entrypointAssets.forEach(asset => nonLazyAssets.add(asset.name)); } for (let asset of assets!) { if (!nonLazyAssets.has(asset.name)) { output.lazyAssets.push('assets/' + asset.name); } } return output; } private writeEntryFile(name: string, deps: BundleDependencies) { writeFileSync( join(this.stagingDir, `${name}.js`), entryTemplate({ staticImports: deps.staticImports, dynamicImports: deps.dynamicImports, dynamicTemplateImports: deps.dynamicTemplateImports.map(mapTemplateImports), staticTemplateImports: deps.staticTemplateImports.map(mapTemplateImports), publicAssetURL: this.opts.publicAssetURL, }) ); } private writeLoaderFile() { writeFileSync(join(this.stagingDir, `l.js`), loader); } private linkDeps(bundleDeps: Map<string, BundleDependencies>) { for (let deps of bundleDeps.values()) { for (let resolved of deps.staticImports) { this.ensureLinked(resolved); } for (let resolved of deps.dynamicImports) { this.ensureLinked(resolved); } for (let resolved of deps.staticTemplateImports) { this.ensureLinked(resolved); } for (let resolved of deps.dynamicTemplateImports) { this.ensureLinked(resolved); } } } private ensureLinked({ packageName, packageRoot }: { packageName: string; packageRoot: string }): void { ensureDirSync(dirname(join(this.stagingDir, 'node_modules', packageName))); if (!existsSync(join(this.stagingDir, 'node_modules', packageName))) { symlinkSync(packageRoot, join(this.stagingDir, 'node_modules', packageName), 'junction'); } } private async runWebpack(): Promise<Required<Stats>> { return new Promise((resolve, reject) => { this.webpack.run((err, stats) => { const statsString = stats ? stats.toString() : ''; if (err) { this.opts.consoleWrite(statsString); reject(err); return; } if (stats?.hasErrors()) { this.opts.consoleWrite(statsString); reject(new Error('webpack returned errors to ember-auto-import')); return; } if (stats?.hasWarnings() || process.env.AUTO_IMPORT_VERBOSE) { this.opts.consoleWrite(statsString); } // this cast is justified because we already checked hasErrors above resolve(stats as Required<Stats>); }); }) as Promise<Required<Stats>>; } } export function mergeConfig(dest: Configuration, ...srcs: Configuration[]) { return mergeWith(dest, ...srcs, combine); } function combine(objValue: any, srcValue: any, key: string) { if (key === 'noParse') { return eitherPattern(objValue, srcValue); } // arrays concat if (Array.isArray(objValue)) { return objValue.concat(srcValue); } } // webpack configs have several places where they accept: // - RegExp // - [RegExp] // - (resource: string) => boolean // - string // - [string] // This function combines any of these with a logical OR. function eitherPattern(...patterns: any[]): (resource: string) => boolean { let flatPatterns = flatten(patterns); return function (resource) { for (let pattern of flatPatterns) { if (pattern instanceof RegExp) { if (pattern.test(resource)) { return true; } } else if (typeof pattern === 'string') { if (pattern === resource) { return true; } } else if (typeof pattern === 'function') { if (pattern(resource)) { return true; } } } return false; }; } function mapTemplateImports(imp: ResolvedTemplateImport) { return { key: imp.importedBy[0].cookedQuasis.join('${e}'), args: imp.expressionNameHints.join(','), template: '`' + zip(imp.cookedQuasis, imp.expressionNameHints) .map(([q, e]) => q + (e ? '${' + e + '}' : '')) .join('') + '`', }; } function nonEmptyBundle(name: string, bundleDeps: Map<string, BundleDependencies>): boolean { let deps = bundleDeps.get(name); if (!deps) { return false; } return ( deps.staticImports.length > 0 || deps.staticTemplateImports.length > 0 || deps.dynamicImports.length > 0 || deps.dynamicTemplateImports.length > 0 ); }
the_stack
import {Event, Evented} from '../../util/evented'; import DOM from '../../util/dom'; import {extend, bindAll, warnOnce} from '../../util/util'; import assert from 'assert'; import LngLat from '../../geo/lng_lat'; import Marker from '../marker'; import type Map from '../map'; import type {AnimationOptions, CameraOptions} from '../camera'; import type {IControl} from './control'; type Options = { positionOptions?: PositionOptions; fitBoundsOptions?: AnimationOptions & CameraOptions; trackUserLocation?: boolean; showAccuracyCircle?: boolean; showUserLocation?: boolean; }; const defaultOptions: Options = { positionOptions: { enableHighAccuracy: false, maximumAge: 0, timeout: 6000 /* 6 sec */ }, fitBoundsOptions: { maxZoom: 15 }, trackUserLocation: false, showAccuracyCircle: true, showUserLocation: true }; let supportsGeolocation; function checkGeolocationSupport(callback) { if (supportsGeolocation !== undefined) { callback(supportsGeolocation); } else if (window.navigator.permissions !== undefined) { // navigator.permissions has incomplete browser support // http://caniuse.com/#feat=permissions-api // Test for the case where a browser disables Geolocation because of an // insecure origin window.navigator.permissions.query({name: 'geolocation'}).then((p) => { supportsGeolocation = p.state !== 'denied'; callback(supportsGeolocation); }); } else { supportsGeolocation = !!window.navigator.geolocation; callback(supportsGeolocation); } } let numberOfWatches = 0; let noTimeout = false; /** * A `GeolocateControl` control provides a button that uses the browser's geolocation * API to locate the user on the map. * * Not all browsers support geolocation, * and some users may disable the feature. Geolocation support for modern * browsers including Chrome requires sites to be served over HTTPS. If * geolocation support is not available, the GeolocateControl will show * as disabled. * * The zoom level applied will depend on the accuracy of the geolocation provided by the device. * * The GeolocateControl has two modes. If `trackUserLocation` is `false` (default) the control acts as a button, which when pressed will set the map's camera to target the user location. If the user moves, the map won't update. This is most suited for the desktop. If `trackUserLocation` is `true` the control acts as a toggle button that when active the user's location is actively monitored for changes. In this mode the GeolocateControl has three interaction states: * * active - the map's camera automatically updates as the user's location changes, keeping the location dot in the center. Initial state and upon clicking the `GeolocateControl` button. * * passive - the user's location dot automatically updates, but the map's camera does not. Occurs upon the user initiating a map movement. * * disabled - occurs if Geolocation is not available, disabled or denied. * * These interaction states can't be controlled programmatically, rather they are set based on user interactions. * * @implements {IControl} * @param {Object} [options] * @param {Object} [options.positionOptions={enableHighAccuracy: false, timeout: 6000}] A Geolocation API [PositionOptions](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions) object. * @param {Object} [options.fitBoundsOptions={maxZoom: 15}] A {@link Map#fitBounds} options object to use when the map is panned and zoomed to the user's location. The default is to use a `maxZoom` of 15 to limit how far the map will zoom in for very accurate locations. * @param {Object} [options.trackUserLocation=false] If `true` the Geolocate Control becomes a toggle button and when active the map will receive updates to the user's location as it changes. * @param {Object} [options.showAccuracyCircle=true] By default, if showUserLocation is `true`, a transparent circle will be drawn around the user location indicating the accuracy (95% confidence level) of the user's location. Set to `false` to disable. Always disabled when showUserLocation is `false`. * @param {Object} [options.showUserLocation=true] By default a dot will be shown on the map at the user's location. Set to `false` to disable. * * @example * map.addControl(new maplibregl.GeolocateControl({ * positionOptions: { * enableHighAccuracy: true * }, * trackUserLocation: true * })); * @see [Locate the user](https://maplibre.org/maplibre-gl-js-docs/example/locate-user/) */ class GeolocateControl extends Evented implements IControl { _map: Map; options: Options; _container: HTMLElement; _dotElement: HTMLElement; _circleElement: HTMLElement; _geolocateButton: HTMLButtonElement; _geolocationWatchID: number; _timeoutId: ReturnType<typeof setTimeout>; _watchState: 'OFF' | 'ACTIVE_LOCK' | 'WAITING_ACTIVE' | 'ACTIVE_ERROR' | 'BACKGROUND' | 'BACKGROUND_ERROR'; _lastKnownPosition: any; _userLocationDotMarker: Marker; _accuracyCircleMarker: Marker; _accuracy: number; _setup: boolean; // set to true once the control has been setup constructor(options: Options) { super(); this.options = extend({}, defaultOptions, options); bindAll([ '_onSuccess', '_onError', '_onZoom', '_finish', '_setupUI', '_updateCamera', '_updateMarker' ], this); } onAdd(map: Map) { this._map = map; this._container = DOM.create('div', 'maplibregl-ctrl maplibregl-ctrl-group mapboxgl-ctrl mapboxgl-ctrl-group'); checkGeolocationSupport(this._setupUI); return this._container; } onRemove() { // clear the geolocation watch if exists if (this._geolocationWatchID !== undefined) { window.navigator.geolocation.clearWatch(this._geolocationWatchID); this._geolocationWatchID = undefined; } // clear the markers from the map if (this.options.showUserLocation && this._userLocationDotMarker) { this._userLocationDotMarker.remove(); } if (this.options.showAccuracyCircle && this._accuracyCircleMarker) { this._accuracyCircleMarker.remove(); } DOM.remove(this._container); this._map.off('zoom', this._onZoom); this._map = undefined; numberOfWatches = 0; noTimeout = false; } /** * Check if the Geolocation API Position is outside the map's maxbounds. * * @param {Position} position the Geolocation API Position * @returns {boolean} Returns `true` if position is outside the map's maxbounds, otherwise returns `false`. * @private */ _isOutOfMapMaxBounds(position: GeolocationPosition) { const bounds = this._map.getMaxBounds(); const coordinates = position.coords; return bounds && ( coordinates.longitude < bounds.getWest() || coordinates.longitude > bounds.getEast() || coordinates.latitude < bounds.getSouth() || coordinates.latitude > bounds.getNorth() ); } _setErrorState() { switch (this._watchState) { case 'WAITING_ACTIVE': this._watchState = 'ACTIVE_ERROR'; this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active', 'mapboxgl-ctrl-geolocate-active'); this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active-error', 'mapboxgl-ctrl-geolocate-active-error'); break; case 'ACTIVE_LOCK': this._watchState = 'ACTIVE_ERROR'; this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active', 'mapboxgl-ctrl-geolocate-active'); this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active-error', 'mapboxgl-ctrl-geolocate-active-error'); this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting', 'mapboxgl-ctrl-geolocate-waiting'); // turn marker grey break; case 'BACKGROUND': this._watchState = 'BACKGROUND_ERROR'; this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background', 'mapboxgl-ctrl-geolocate-background'); this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background-error', 'mapboxgl-ctrl-geolocate-background-error'); this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting', 'mapboxgl-ctrl-geolocate-waiting'); // turn marker grey break; case 'ACTIVE_ERROR': break; default: assert(false, `Unexpected watchState ${this._watchState}`); } } /** * When the Geolocation API returns a new location, update the GeolocateControl. * * @param {Position} position the Geolocation API Position * @private */ _onSuccess(position: GeolocationPosition) { if (!this._map) { // control has since been removed return; } if (this._isOutOfMapMaxBounds(position)) { this._setErrorState(); this.fire(new Event('outofmaxbounds', position)); this._updateMarker(); this._finish(); return; } if (this.options.trackUserLocation) { // keep a record of the position so that if the state is BACKGROUND and the user // clicks the button, we can move to ACTIVE_LOCK immediately without waiting for // watchPosition to trigger _onSuccess this._lastKnownPosition = position; switch (this._watchState) { case 'WAITING_ACTIVE': case 'ACTIVE_LOCK': case 'ACTIVE_ERROR': this._watchState = 'ACTIVE_LOCK'; this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting', 'mapboxgl-ctrl-geolocate-waiting'); this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active-error', 'mapboxgl-ctrl-geolocate-active-error'); this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active', 'mapboxgl-ctrl-geolocate-active'); break; case 'BACKGROUND': case 'BACKGROUND_ERROR': this._watchState = 'BACKGROUND'; this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting', 'mapboxgl-ctrl-geolocate-waiting'); this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background-error', 'mapboxgl-ctrl-geolocate-background-error'); this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background', 'mapboxgl-ctrl-geolocate-background'); break; default: assert(false, `Unexpected watchState ${this._watchState}`); } } // if showUserLocation and the watch state isn't off then update the marker location if (this.options.showUserLocation && this._watchState !== 'OFF') { this._updateMarker(position); } // if in normal mode (not watch mode), or if in watch mode and the state is active watch // then update the camera if (!this.options.trackUserLocation || this._watchState === 'ACTIVE_LOCK') { this._updateCamera(position); } if (this.options.showUserLocation) { this._dotElement.classList.remove('maplibregl-user-location-dot-stale', 'mapboxgl-user-location-dot-stale'); } this.fire(new Event('geolocate', position)); this._finish(); } /** * Update the camera location to center on the current position * * @param {Position} position the Geolocation API Position * @private */ _updateCamera(position: GeolocationPosition) { const center = new LngLat(position.coords.longitude, position.coords.latitude); const radius = position.coords.accuracy; const bearing = this._map.getBearing(); const options = extend({bearing}, this.options.fitBoundsOptions); this._map.fitBounds(center.toBounds(radius), options, { geolocateSource: true // tag this camera change so it won't cause the control to change to background state }); } /** * Update the user location dot Marker to the current position * * @param {Position} [position] the Geolocation API Position * @private */ _updateMarker(position?: GeolocationPosition | null) { if (position) { const center = new LngLat(position.coords.longitude, position.coords.latitude); this._accuracyCircleMarker.setLngLat(center).addTo(this._map); this._userLocationDotMarker.setLngLat(center).addTo(this._map); this._accuracy = position.coords.accuracy; if (this.options.showUserLocation && this.options.showAccuracyCircle) { this._updateCircleRadius(); } } else { this._userLocationDotMarker.remove(); this._accuracyCircleMarker.remove(); } } _updateCircleRadius() { assert(this._circleElement); const y = this._map._container.clientHeight / 2; const a = this._map.unproject([0, y]); const b = this._map.unproject([1, y]); const metersPerPixel = a.distanceTo(b); const circleDiameter = Math.ceil(2.0 * this._accuracy / metersPerPixel); this._circleElement.style.width = `${circleDiameter}px`; this._circleElement.style.height = `${circleDiameter}px`; } _onZoom() { if (this.options.showUserLocation && this.options.showAccuracyCircle) { this._updateCircleRadius(); } } _onError(error: GeolocationPositionError) { if (!this._map) { // control has since been removed return; } if (this.options.trackUserLocation) { if (error.code === 1) { // PERMISSION_DENIED this._watchState = 'OFF'; this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting', 'mapboxgl-ctrl-geolocate-waiting'); this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active', 'mapboxgl-ctrl-geolocate-active'); this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active-error', 'mapboxgl-ctrl-geolocate-active-error'); this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background', 'mapboxgl-ctrl-geolocate-background'); this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background-error', 'mapboxgl-ctrl-geolocate-background-error'); this._geolocateButton.disabled = true; const title = this._map._getUIString('GeolocateControl.LocationNotAvailable'); this._geolocateButton.title = title; this._geolocateButton.setAttribute('aria-label', title); if (this._geolocationWatchID !== undefined) { this._clearWatch(); } } else if (error.code === 3 && noTimeout) { // this represents a forced error state // this was triggered to force immediate geolocation when a watch is already present // see https://github.com/mapbox/mapbox-gl-js/issues/8214 // and https://w3c.github.io/geolocation-api/#example-5-forcing-the-user-agent-to-return-a-fresh-cached-position return; } else { this._setErrorState(); } } if (this._watchState !== 'OFF' && this.options.showUserLocation) { this._dotElement.classList.add('maplibregl-user-location-dot-stale', 'mapboxgl-user-location-dot-stale'); } this.fire(new Event('error', error)); this._finish(); } _finish() { if (this._timeoutId) { clearTimeout(this._timeoutId); } this._timeoutId = undefined; } _setupUI(supported: boolean) { this._container.addEventListener('contextmenu', (e: MouseEvent) => e.preventDefault()); this._geolocateButton = DOM.create('button', 'maplibregl-ctrl-geolocate mapboxgl-ctrl-geolocate', this._container); DOM.create('span', 'maplibregl-ctrl-icon mapboxgl-ctrl-icon', this._geolocateButton).setAttribute('aria-hidden', 'true'); this._geolocateButton.type = 'button'; if (supported === false) { warnOnce('Geolocation support is not available so the GeolocateControl will be disabled.'); const title = this._map._getUIString('GeolocateControl.LocationNotAvailable'); this._geolocateButton.disabled = true; this._geolocateButton.title = title; this._geolocateButton.setAttribute('aria-label', title); } else { const title = this._map._getUIString('GeolocateControl.FindMyLocation'); this._geolocateButton.title = title; this._geolocateButton.setAttribute('aria-label', title); } if (this.options.trackUserLocation) { this._geolocateButton.setAttribute('aria-pressed', 'false'); this._watchState = 'OFF'; } // when showUserLocation is enabled, keep the Geolocate button disabled until the device location marker is setup on the map if (this.options.showUserLocation) { this._dotElement = DOM.create('div', 'maplibregl-user-location-dot mapboxgl-user-location-dot'); this._userLocationDotMarker = new Marker(this._dotElement); this._circleElement = DOM.create('div', 'maplibregl-user-location-accuracy-circle mapboxgl-user-location-accuracy-circle'); this._accuracyCircleMarker = new Marker({element: this._circleElement, pitchAlignment: 'map'}); if (this.options.trackUserLocation) this._watchState = 'OFF'; this._map.on('zoom', this._onZoom); } this._geolocateButton.addEventListener('click', this.trigger.bind(this)); this._setup = true; // when the camera is changed (and it's not as a result of the Geolocation Control) change // the watch mode to background watch, so that the marker is updated but not the camera. if (this.options.trackUserLocation) { this._map.on('movestart', (event) => { const fromResize = event.originalEvent && event.originalEvent.type === 'resize'; if (!event.geolocateSource && this._watchState === 'ACTIVE_LOCK' && !fromResize) { this._watchState = 'BACKGROUND'; this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-background', 'mapboxgl-ctrl-geolocate-background'); this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active', 'mapboxgl-ctrl-geolocate-active'); this.fire(new Event('trackuserlocationend')); } }); } } /** * Programmatically request and move the map to the user's location. * * @returns {boolean} Returns `false` if called before control was added to a map, otherwise returns `true`. * @example * // Initialize the geolocate control. * var geolocate = new maplibregl.GeolocateControl({ * positionOptions: { * enableHighAccuracy: true * }, * trackUserLocation: true * }); * // Add the control to the map. * map.addControl(geolocate); * map.on('load', function() { * geolocate.trigger(); * }); */ trigger() { if (!this._setup) { warnOnce('Geolocate control triggered before added to a map'); return false; } if (this.options.trackUserLocation) { // update watchState and do any outgoing state cleanup switch (this._watchState) { case 'OFF': // turn on the Geolocate Control this._watchState = 'WAITING_ACTIVE'; this.fire(new Event('trackuserlocationstart')); break; case 'WAITING_ACTIVE': case 'ACTIVE_LOCK': case 'ACTIVE_ERROR': case 'BACKGROUND_ERROR': // turn off the Geolocate Control numberOfWatches--; noTimeout = false; this._watchState = 'OFF'; this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting', 'mapboxgl-ctrl-geolocate-waiting'); this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active', 'mapboxgl-ctrl-geolocate-active'); this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-active-error', 'mapboxgl-ctrl-geolocate-active-error'); this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background', 'mapboxgl-ctrl-geolocate-background'); this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background-error', 'mapboxgl-ctrl-geolocate-background-error'); this.fire(new Event('trackuserlocationend')); break; case 'BACKGROUND': this._watchState = 'ACTIVE_LOCK'; this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-background', 'mapboxgl-ctrl-geolocate-background'); // set camera to last known location if (this._lastKnownPosition) this._updateCamera(this._lastKnownPosition); this.fire(new Event('trackuserlocationstart')); break; default: assert(false, `Unexpected watchState ${this._watchState}`); } // incoming state setup switch (this._watchState) { case 'WAITING_ACTIVE': this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting', 'mapboxgl-ctrl-geolocate-waiting'); this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active', 'mapboxgl-ctrl-geolocate-active'); break; case 'ACTIVE_LOCK': this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-active', 'mapboxgl-ctrl-geolocate-active'); break; case 'OFF': break; default: assert(false, `Unexpected watchState ${this._watchState}`); } // manage geolocation.watchPosition / geolocation.clearWatch if (this._watchState === 'OFF' && this._geolocationWatchID !== undefined) { // clear watchPosition as we've changed to an OFF state this._clearWatch(); } else if (this._geolocationWatchID === undefined) { // enable watchPosition since watchState is not OFF and there is no watchPosition already running this._geolocateButton.classList.add('maplibregl-ctrl-geolocate-waiting', 'mapboxgl-ctrl-geolocate-waiting'); this._geolocateButton.setAttribute('aria-pressed', 'true'); numberOfWatches++; let positionOptions; if (numberOfWatches > 1) { positionOptions = {maximumAge:600000, timeout:0}; noTimeout = true; } else { positionOptions = this.options.positionOptions; noTimeout = false; } this._geolocationWatchID = window.navigator.geolocation.watchPosition( this._onSuccess, this._onError, positionOptions); } } else { window.navigator.geolocation.getCurrentPosition( this._onSuccess, this._onError, this.options.positionOptions); // This timeout ensures that we still call finish() even if // the user declines to share their location in Firefox this._timeoutId = setTimeout(this._finish, 10000 /* 10sec */); } return true; } _clearWatch() { window.navigator.geolocation.clearWatch(this._geolocationWatchID); this._geolocationWatchID = undefined; this._geolocateButton.classList.remove('maplibregl-ctrl-geolocate-waiting', 'mapboxgl-ctrl-geolocate-waiting'); this._geolocateButton.setAttribute('aria-pressed', 'false'); if (this.options.showUserLocation) { this._updateMarker(null); } } } export default GeolocateControl; /* Geolocate Control Watch States * This is the private state of the control. * * OFF * off/inactive * WAITING_ACTIVE * Geolocate Control was clicked but still waiting for Geolocation API response with user location * ACTIVE_LOCK * Showing the user location as a dot AND tracking the camera to be fixed to their location. If their location changes the map moves to follow. * ACTIVE_ERROR * There was en error from the Geolocation API while trying to show and track the user location. * BACKGROUND * Showing the user location as a dot but the camera doesn't follow their location as it changes. * BACKGROUND_ERROR * There was an error from the Geolocation API while trying to show (but not track) the user location. */ /** * Fired on each Geolocation API position update which returned as success. * * @event geolocate * @memberof GeolocateControl * @instance * @property {Position} data The returned [Position](https://developer.mozilla.org/en-US/docs/Web/API/Position) object from the callback in [Geolocation.getCurrentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) or [Geolocation.watchPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition). * @example * // Initialize the geolocate control. * var geolocate = new maplibregl.GeolocateControl({ * positionOptions: { * enableHighAccuracy: true * }, * trackUserLocation: true * }); * // Add the control to the map. * map.addControl(geolocate); * // Set an event listener that fires * // when a geolocate event occurs. * geolocate.on('geolocate', function() { * console.log('A geolocate event has occurred.') * }); * */ /** * Fired on each Geolocation API position update which returned as an error. * * @event error * @memberof GeolocateControl * @instance * @property {PositionError} data The returned [PositionError](https://developer.mozilla.org/en-US/docs/Web/API/PositionError) object from the callback in [Geolocation.getCurrentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) or [Geolocation.watchPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition). * @example * // Initialize the geolocate control. * var geolocate = new maplibregl.GeolocateControl({ * positionOptions: { * enableHighAccuracy: true * }, * trackUserLocation: true * }); * // Add the control to the map. * map.addControl(geolocate); * // Set an event listener that fires * // when an error event occurs. * geolocate.on('error', function() { * console.log('An error event has occurred.') * }); * */ /** * Fired on each Geolocation API position update which returned as success but user position is out of map maxBounds. * * @event outofmaxbounds * @memberof GeolocateControl * @instance * @property {Position} data The returned [Position](https://developer.mozilla.org/en-US/docs/Web/API/Position) object from the callback in [Geolocation.getCurrentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) or [Geolocation.watchPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition). * @example * // Initialize the geolocate control. * var geolocate = new maplibregl.GeolocateControl({ * positionOptions: { * enableHighAccuracy: true * }, * trackUserLocation: true * }); * // Add the control to the map. * map.addControl(geolocate); * // Set an event listener that fires * // when an outofmaxbounds event occurs. * geolocate.on('outofmaxbounds', function() { * console.log('An outofmaxbounds event has occurred.') * }); * */ /** * Fired when the Geolocate Control changes to the active lock state, which happens either upon first obtaining a successful Geolocation API position for the user (a geolocate event will follow), or the user clicks the geolocate button when in the background state which uses the last known position to recenter the map and enter active lock state (no geolocate event will follow unless the users's location changes). * * @event trackuserlocationstart * @memberof GeolocateControl * @instance * @example * // Initialize the geolocate control. * var geolocate = new maplibregl.GeolocateControl({ * positionOptions: { * enableHighAccuracy: true * }, * trackUserLocation: true * }); * // Add the control to the map. * map.addControl(geolocate); * // Set an event listener that fires * // when a trackuserlocationstart event occurs. * geolocate.on('trackuserlocationstart', function() { * console.log('A trackuserlocationstart event has occurred.') * }); * */ /** * Fired when the Geolocate Control changes to the background state, which happens when a user changes the camera during an active position lock. This only applies when trackUserLocation is true. In the background state, the dot on the map will update with location updates but the camera will not. * * @event trackuserlocationend * @memberof GeolocateControl * @instance * @example * // Initialize the geolocate control. * var geolocate = new maplibregl.GeolocateControl({ * positionOptions: { * enableHighAccuracy: true * }, * trackUserLocation: true * }); * // Add the control to the map. * map.addControl(geolocate); * // Set an event listener that fires * // when a trackuserlocationend event occurs. * geolocate.on('trackuserlocationend', function() { * console.log('A trackuserlocationend event has occurred.') * }); * */
the_stack
import {Component,Input} from '@angular/core'; import { HttpClient, HttpResponse } from '@angular/common/http' import {trigger, animate, style, group, animateChild, query, stagger, transition, state} from '@angular/animations'; import { Location } from '@angular/common' import { DataService } from '../../services/data.service' import { HubService } from '../../services/hub.service' import { Router } from '@angular/router' import { Category } from './category' import { ImageItem } from '../items/image.item' import { TextItem } from '../items/text.item' import { AudioItem } from '../items/audio.item' import { AppInsightsService } from '../../services/app-insights.service' @Component({ selector: 'app-categories', templateUrl: './category.component.html', styleUrls: ['./category.component.css'], animations:[ trigger('fadeshow', [ transition(':enter', [ style({ opacity: 0 }), animate('1000ms ease-in', style({ opacity: 1 })) ]), transition(':leave', [ style({ opacity: 1 }), animate('1000ms ease-in', style({ opacity: 0 })) ]) ]) ] }) export class CategoryComponent { injectedUserId: string add : boolean categoryName : string updatedCategoryName : string category_post_url : string cr_created_success: boolean addDisabled: boolean nrOfTags : number synonyms : Array<string> location : Location categoriesList : Array<Category> loaded: boolean=false displayUserId: string errorMessage : string constructor(private router: Router,private data: DataService, private hub : HubService, private appInsightsService: AppInsightsService, private http: HttpClient) { this.cr_created_success = false this.addDisabled = false this.categoriesList = new Array<Category>() this.appInsightsService.logPageView('Categories Page'); } ngOnInit(){ this.data.currentUser.subscribe(injectedUserId =>{ this.injectedUserId = injectedUserId }) this.category_post_url = location.origin + "/api/Category?userId=" + this.injectedUserId; } ngAfterContentInit() { this.displayUserId = this.injectedUserId.split("@")[0] this.listenToEvents() this.getAllCategories(); } listenToEvents(){ this.hub.getHubConnection().on('onCategorySynonymsUpdated', (categoryId:string,eventData: any) => { let category : Category = this.fetchCategoryObject(categoryId) category.setSynonyms(eventData.synonyms) this.appInsightsService.logEvent("Category Synonyms Updated",{category : categoryId}) }) this.hub.getHubConnection().on('onCategoryImageUpdated', (categoryId: string, eventData:any) => { let category : Category = this.fetchCategoryObject(categoryId) category.setImage(eventData.imageUrl) this.appInsightsService.logEvent("Category Image Updated",{category : categoryId}) }) this.hub.getHubConnection().on('onCategoryItemsUpdated', (categoryId: string, eventData:any) => { let category : Category = this.fetchCategoryObject(categoryId) category.notifications += 1 category.showNotification = true; this.appInsightsService.logEvent("Category Items Updated",{category : categoryId}) }) this.hub.getHubConnection().on('onCategoryCreated', (categoryId: string, eventData:any) => { //** Add event handling code for category creation here */ this.appInsightsService.logEvent("Category Created",{category : categoryId}) }) this.hub.getHubConnection().on('onCategoryDeleted', (categoryId: string, eventData:any) => { //** Add event handling code for category deletion here */ this.appInsightsService.logEvent("Category Deleted",{category : categoryId}) }) this.hub.getHubConnection().on('onCategoryNameUpdated', (categoryId: string, eventData:any) => { //** Add event handling code for category updation here */ this.appInsightsService.logEvent("Category Name Updated",{category : categoryId}) }) } getAllCategories(){ const req = this.http.get(this.category_post_url) type CategoryType = { id:string, name:string } req.subscribe((data: any) => { var catListData = JSON.parse(data) var catList = Object.keys(catListData).map( function (key) { let obj1:CategoryType = {} as CategoryType; obj1.id=key; obj1.name = catListData[key].name; return obj1 }); for (let category of catList){ let newCategory:Category = new Category(category.id,category.name) this.categoriesList.push(newCategory) } this.loaded = true for (let category of catList){ var category_get_url = location.origin + "/api/Category/"+ category.id + "/?userId=" + this.injectedUserId; const catReq = this.http.get(category_get_url) catReq.subscribe((data:any) => { var currentCategory = JSON.parse(data) let fetchedCategory: Category = this.fetchCategoryObject(currentCategory.id) fetchedCategory.setImage(currentCategory.imageUrl) fetchedCategory.setSynonyms(currentCategory.synonyms) for(let item of currentCategory.items){ if(item.type === "Image"){ let c_img:ImageItem = new ImageItem(item.id) c_img.setPreviewUrl(item.preview) fetchedCategory.addItemImages(c_img) } if(item.type === "Text"){ let c_txt:TextItem = new TextItem(item.id) c_txt.setText(item.preview) fetchedCategory.addItemText(c_txt) } if(item.type === "Audio"){ let c_audio:AudioItem = new AudioItem(item.id) c_audio.setTranscript(item.preview) fetchedCategory.addItemAudio(c_audio) } } fetchedCategory.showCategory = true }) } }) } fetchCategoryObject(categoryId : string){ for (let category of this.categoriesList){ if (category.getId() == categoryId){ return category } } } catIndexOf(categoryId:string){ for (var i = 0; i < this.categoriesList.length; i++) { if (this.categoriesList[i].id === categoryId){ return i; } } } onClickAddCategory(){ if (this.categoryName === "") { this.errorMessage = "Provide a valid category name. Words are good" return; } this.errorMessage = "" this.addDisabled = true const req = this.http.post(this.category_post_url,{name: this.categoryName}) req.subscribe( (res: any) => { var catId = JSON.parse((res)) let newCategory:Category = new Category(catId.id,this.categoryName) this.categoriesList.push(newCategory) this.cr_created_success = true this.addDisabled = false }, err => { console.log("Received error response") } ) } onClickUpdateCategory(categoryId:string){ var category_update_url = location.origin + "/api/Category/"+ categoryId + "/?userId=" + this.injectedUserId; const req = this.http.patch(category_update_url,{name: this.updatedCategoryName}) req.subscribe( (res: any) => { let category:Category = this.fetchCategoryObject(categoryId) category.setName(this.updatedCategoryName) category.editMode = false }, err => { console.log("Received error response") } ) } onClickDeleteCategory(categoryId:string){ var category_delete_url = location.origin + "/api/Category/"+ categoryId + "/?userId=" + this.injectedUserId; const req = this.http.delete(category_delete_url) req.subscribe( (res: any) => { var index = this.catIndexOf(categoryId) if(index >-1){ this.categoriesList.splice(index,1) } }, err => { console.log("Received error response") } ) } onClickViewCategory(categoryId:string){ this.data.setCurrentCategory(categoryId) let currentCategory:Category = this.fetchCategoryObject(categoryId) this.data.setCurrentCategoryName(currentCategory.getName()) this.data.clearImages() this.data.clearText() this.data.clearAudio() for(let item of currentCategory.getItemImages()){ this.data.addImage(item) } for(let item of currentCategory.getItemText()){ this.data.addText(item) } for(let item of currentCategory.getItemAudio()){ this.data.addAudio(item) } this.router.navigateByUrl('items') } onClickClearNotifications(categoryId: string){ let currentCategory:Category = this.fetchCategoryObject(categoryId) currentCategory.showNotification = false currentCategory.clearNotifications() } logout(){ // Disconnect user from signalR hub this.hub.getHubConnection().stop().then( () => { console.log("Connection stopped successfully") this.data.setCurrentUser("default") this.router.navigateByUrl('') }).catch(err => console.log("Error while establishing connection")); } }
the_stack
import { create, act } from "react-test-renderer"; import { createStore, connect } from "../../.."; import { Provider } from "@frontity/connect"; import useFills from "../use-fills"; import { toJson, toJsonArray } from "./slot.tests"; let store; // Spy on the console.warn calls const warn = jest.spyOn(global.console, "warn"); const FillComponent = ({ name, number }) => ( <div id="test-fill" data-number={number} data-name={name}> Im a Fill </div> ); beforeEach(() => { warn.mockClear(); store = createStore({ actions: { fillActions: { setNumber: ({ state }) => (number: number) => { state.fills.namespace1["test fill 1"].props.number = number; }, }, }, state: { fills: { namespace1: { "test fill 1": { slot: "slot 1", library: "namespace1.FillComponent", props: { number: 1, }, }, "test fill 2": { slot: "slot 2", library: "namespace1.FillComponent", }, }, namespace2: { "test fill 3": { slot: "slot 3", library: "namespace2.FillComponent", priority: 1, props: { number: 3, }, }, }, }, }, libraries: { fills: { namespace1: { FillComponent, }, namespace2: { FillComponent, }, }, }, }); }); describe("useFills", () => { it("should work in the most basic case", () => { const Comp = connect(() => { const fills = useFills("slot 1"); return ( <> {fills.map(({ Fill, props, key }) => ( <Fill key={key} name={key} {...props} /> ))} </> ); }); const app = create( <Provider value={store}> <Comp /> </Provider> ); expect(toJson(app).props).toEqual({ id: "test-fill", "data-number": 1, "data-name": "namespace1 - test fill 1", }); expect(toJson(app).children[0]).toEqual("Im a Fill"); expect(toJson(app)).toMatchSnapshot(); }); it("should work when the slot does not exist", () => { const Comp = connect(() => { const fills = useFills("slot that does not exist"); expect(fills).toEqual([]); return ( <> {fills.map(({ Fill, props, key }) => ( <Fill key={key} name={key} {...props} /> ))} </> ); }); const app = create( <Provider value={store}> <Comp /> </Provider> ); expect(toJson(app)).toEqual(null); expect(toJson(app)).toMatchSnapshot(); }); it("should remind to specify the slot name if called without arguments", () => { const warn = jest.spyOn(global.console, "warn"); const Comp = connect(() => { // This is just to trick typescript to allow us to call // useFills without any arguments const useFills2: any = useFills; const fills = useFills2(); expect(fills).toEqual([]); return ( <> {fills.map(({ Fill, props, key }) => ( <Fill key={key} name={key} {...props} /> ))} </> ); }); const app = create( <Provider value={store}> <Comp /> </Provider> ); expect(warn.mock.calls[0][0]).toMatch( "You should pass the name of the slot that you would like to fill!" ); expect(toJson(app)).toEqual(null); expect(toJson(app)).toMatchSnapshot(); }); it("should warn when the Fill component is not found in libraries", () => { const warn = jest.spyOn(global.console, "warn"); const Comp = connect(() => { // This is just to trick typescript to allow us to call // useFills without any arguments const useFills2: any = useFills; const fills = useFills2(); expect(fills).toEqual([]); return ( <> {fills.map(({ Fill, props, key }) => ( <Fill key={key} name={key} {...props} /> ))} </> ); }); const app = create( <Provider value={store}> <Comp /> </Provider> ); expect(warn.mock.calls[0][0]).toMatch( "You should pass the name of the slot that you would like to fill!" ); expect(toJson(app)).toEqual(null); expect(toJson(app)).toMatchSnapshot(); }); it("should not return the fill when library is not specified", () => { delete store.state.fills.namespace1["test fill 1"].library; const Comp = connect(() => { const fills = useFills("slot 1"); expect(fills).toEqual([]); return ( <> {fills.map(({ Fill, props, key }) => ( <Fill key={key} name={key} {...props} /> ))} </> ); }); const app = create( <Provider value={store}> <Comp /> </Provider> ); expect(toJson(app)).toEqual(null); expect(toJson(app)).toMatchSnapshot(); }); it("should not return the fill when library doesn't match a component in libraries", () => { store.state.fills.namespace1["test fill 1"].library = "FillComponent"; const Comp = connect(() => { const fills = useFills("slot 1"); expect(fills).toEqual([]); return ( <> {fills.map(({ Fill, props, key }) => ( <Fill key={key} name={key} {...props} /> ))} </> ); }); const app = create( <Provider value={store}> <Comp /> </Provider> ); expect(toJson(app)).toEqual(null); expect(toJson(app)).toMatchSnapshot(); }); it("should not return the fill when the slot is not specified", () => { delete store.state.fills.namespace1["test fill 1"].slot; const Comp = connect(() => { const fills = useFills("slot 1"); expect(fills).toEqual([]); return ( <> {fills.map(({ Fill, props, key }) => ( <Fill key={key} name={key} {...props} /> ))} </> ); }); const app = create( <Provider value={store}> <Comp /> </Provider> ); expect(toJson(app)).toEqual(null); expect(toJson(app)).toMatchSnapshot(); }); it("should work when `state.fills` is missing", () => { delete store.state.fills; const Comp = connect(() => { const fills = useFills("slot 1"); expect(fills).toEqual([]); return ( <> {fills.map(({ Fill, props, key }) => ( <Fill key={key} name={key} {...props} /> ))} </> ); }); const app = create( <Provider value={store}> <Comp /> </Provider> ); expect(toJson(app)).toEqual(null); expect(toJson(app)).toMatchSnapshot(); }); it("should work when `state.fills` doesn't contain any fills", () => { store.state.fills = {}; const Comp = connect(() => { const fills = useFills("slot 1"); expect(fills).toEqual([]); return ( <> {fills.map(({ Fill, props, key }) => ( <Fill key={key} name={key} {...props} /> ))} </> ); }); const app = create( <Provider value={store}> <Comp /> </Provider> ); expect(toJson(app)).toEqual(null); expect(toJson(app)).toMatchSnapshot(); }); it("should re-render the fill when updating the props", () => { const Comp = connect(() => { const fills = useFills("slot 1"); return ( <> {fills.map(({ Fill, props, key }) => ( <Fill key={key} name={key} {...props} /> ))} </> ); }); const app = create( <Provider value={store}> <Comp /> </Provider> ); act(() => { store.actions.fillActions.setNumber(43); }); expect(toJson(app).props).toEqual({ id: "test-fill", "data-number": 43, "data-name": "namespace1 - test fill 1", }); expect(toJson(app).children[0]).toEqual("Im a Fill"); expect(toJson(app)).toMatchSnapshot(); }); it("should render the fills in the order of priority", () => { store.state.fills.namespace2["test fill 3"].slot = "slot 1"; const Comp = connect(() => { const fills = useFills("slot 1"); return ( <> {fills.map(({ Fill, props, key }) => ( <Fill key={key} name={key} {...props} /> ))} </> ); }); const app = create( <Provider value={store}> <Comp /> </Provider> ); // This fill should come first expect(toJsonArray(app)[0].props).toEqual({ id: "test-fill", "data-number": 3, "data-name": "namespace2 - test fill 3", }); // This fill should come second expect(toJsonArray(app)[1].props).toEqual({ id: "test-fill", "data-number": 1, "data-name": "namespace1 - test fill 1", }); expect(toJsonArray(app)).toMatchSnapshot(); }); it("should skip rendering the fills with value `false`", () => { store.state.fills.namespace2["test fill 3"].slot = "slot 1"; store.state.fills.namespace1["test fill 1"] = false; const Comp = connect(() => { const fills = useFills("slot 1"); return ( <> {fills.map(({ Fill, props, key }) => ( <Fill key={key} name={key} {...props} /> ))} </> ); }); const app = create( <Provider value={store}> <Comp /> </Provider> ); // We should only render 1 component. expect(toJson(app).props).toEqual({ id: "test-fill", "data-number": 3, "data-name": "namespace2 - test fill 3", }); expect(toJson(app)).toMatchSnapshot(); }); it("should render the debug slots when `state.frontity.debug` is true", () => { store.state.frontity = { debug: true }; const Comp = connect(() => { const fills = useFills("slot 1"); return ( <> {fills.map(({ Fill, props, key }) => ( <Fill key={key} name={key} {...props} /> ))} </> ); }); const app = create( <Provider value={store}> <Comp /> </Provider> ); // We should only render 1 component. expect(toJson(app).props["data-slot-name"]).toBe("slot 1"); expect(toJson(app)).toMatchSnapshot(); }); });
the_stack
import FS = require("fs"); import Path = require("path"); import { resolve } from "url"; import { Stats } from "fs"; import { encode } from "punycode"; var charset = "utf-8"; /** * 保存数据到指定文件 * @param path 文件完整路径名 * @param data 要保存的数据 */ export function save(path: string, data: any): void { if (exists(path)) { remove(path); } path = escapePath(path); textTemp[path] = data; createDirectory(Path.dirname(path)); FS.writeFileSync(path, data, { encoding: charset }); } export function writeFileAsync(path: string, content: string, charset: string): Promise<boolean> { return new Promise((resolve, reject) => { FS.writeFile(path, content, { encoding: charset }, (err) => { if (err) { reject(err); } else { resolve(true); } }); }); } /** * 创建文件夹 */ export function createDirectory(path: string, mode?: any): void { path = escapePath(path); if (mode === undefined) { mode = 511 & (~process.umask()); } if (typeof mode === 'string') mode = parseInt(mode, 8); path = Path.resolve(path); try { FS.mkdirSync(path, mode); } catch (err0) { switch (err0.code) { case 'ENOENT': createDirectory(Path.dirname(path), mode); createDirectory(path, mode); break; default: var stat; try { stat = FS.statSync(path); } catch (err1) { throw err0; } if (!stat.isDirectory()) throw err0; break; } } } var textTemp = {}; /** * 读取文本文件,返回打开文本的字符串内容,若失败,返回"". * @param path 要打开的文件路径 */ export function read(path: string, ignoreCache = false): string { path = escapePath(path); var text = textTemp[path]; if (text && !ignoreCache) { return text; } try { text = FS.readFileSync(path, charset); text = text.replace(/^\uFEFF/, ''); } catch (err0) { return ""; } if (text) { var ext = getExtension(path).toLowerCase(); if (ext == "ts" || ext == "exml") { textTemp[path] = text; } } return text; } export function readFileAsync(path: string, charset: string): Promise<string> { return new Promise((resolve, reject) => { FS.readFile(path, charset, (err, data) => { if (err) { reject(err); } else { resolve(data); } }); }); } /** * 读取字节流文件,返回字节流,若失败,返回null. * @param path 要打开的文件路径 */ export function readBinary(path: string): any { path = escapePath(path); try { var binary = FS.readFileSync(path); } catch (e) { return null; } return binary; } /** * 复制文件或目录 * @param source 文件源路径 * @param dest 文件要复制到的目标路径 */ export function copy(source: string, dest: string): void { source = escapePath(source); dest = escapePath(dest); var stat = FS.lstatSync(source); if (stat.isDirectory()) { _copy_dir(source, dest); } else { _copy_file(source, dest); } } export function isDirectory(path: string): boolean { path = escapePath(path); try { var stat = FS.statSync(path); } catch (e) { return false; } return stat.isDirectory(); } export function isSymbolicLink(path: string): boolean { path = escapePath(path); try { var stat = FS.statSync(path); } catch (e) { return false; } return stat.isSymbolicLink(); } export function isFile(path: string): boolean { path = escapePath(path); try { var stat = FS.statSync(path); } catch (e) { return false; } return stat.isFile(); } function _copy_file(source_file, output_file) { createDirectory(Path.dirname(output_file)) var byteArray = FS.readFileSync(source_file); FS.writeFileSync(output_file, byteArray); } function _copy_dir(sourceDir, outputDir) { createDirectory(outputDir); var list = readdirSync(sourceDir); list.forEach(function (fileName) { copy(Path.join(sourceDir, fileName), Path.join(outputDir, fileName)); }); } /** * 删除文件或目录 * @param path 要删除的文件源路径 */ export function remove(path: string): void { path = escapePath(path); try { FS.lstatSync(path).isDirectory() ? rmdir(path) : FS.unlinkSync(path); getDirectoryListing(path); } catch (e) { } } function rmdir(path) { var files = []; if (FS.existsSync(path)) { files = readdirSync(path); files.forEach(function (file) { var curPath = path + "/" + file; if (FS.statSync(curPath).isDirectory()) { rmdir(curPath); } else { FS.unlinkSync(curPath); } }); FS.rmdirSync(path); } } export function rename(oldPath, newPath) { if (isDirectory(oldPath)) { FS.renameSync(oldPath, newPath); } } /** * 返回指定文件的父级文件夹路径,返回字符串的结尾已包含分隔符。 */ export function getDirectory(path: string): string { path = escapePath(path); return Path.dirname(path) + "/"; } /** * 获得路径的扩展名,不包含点字符。 */ export function getExtension(path: string): string { path = escapePath(path); var index = path.lastIndexOf("."); if (index == -1) return ""; var i = path.lastIndexOf("/"); if (i > index) return ""; return path.substring(index + 1); } /** * 获取路径的文件名(不含扩展名)或文件夹名 */ export function getFileName(path: string): string { if (!path) return ""; path = escapePath(path); var startIndex = path.lastIndexOf("/"); var endIndex; if (startIndex > 0 && startIndex == path.length - 1) { path = path.substring(0, path.length - 1); startIndex = path.lastIndexOf("/"); endIndex = path.length; return path.substring(startIndex + 1, endIndex); } endIndex = path.lastIndexOf("."); if (endIndex == -1 || isDirectory(path)) endIndex = path.length; return path.substring(startIndex + 1, endIndex); } /** * 获取指定文件夹下的文件或文件夹列表,不包含子文件夹内的文件。 * @param path 要搜索的文件夹 * @param relative 是否返回相对路径,若不传入或传入false,都返回绝对路径。 */ export function getDirectoryListing(path: string, relative: boolean = false): string[] { path = escapePath(path); try { var list = readdirSync(path); } catch (e) { return []; } var length = list.length; if (!relative) { for (var i = length - 1; i >= 0; i--) { if (list[i].charAt(0) == ".") { list.splice(i, 1); } else { list[i] = joinPath(path, list[i]); } } } else { for (i = length - 1; i >= 0; i--) { if (list[i].charAt(0) == ".") { list.splice(i, 1); } } } return list; } /** * 获取指定文件夹下全部的文件列表,包括子文件夹 * @param path * @returns {any} */ export function getDirectoryAllListing(path: string): string[] { var list = []; if (isDirectory(path)) { var fileList = getDirectoryListing(path); for (var key in fileList) { list = list.concat(getDirectoryAllListing(fileList[key])); } return list; } return [path]; } /** * 使用指定扩展名搜索文件夹及其子文件夹下所有的文件 * @param dir 要搜索的文件夹 * @param extension 要搜索的文件扩展名,不包含点字符,例如:"png"。不设置表示获取所有类型文件。 */ export function search(dir: string, extension?: string): string[] { var list = []; try { var stat = FS.statSync(dir); } catch (e) { return list; } if (stat.isDirectory()) { findFiles(dir, list, extension, null); } return list; } /** * 使用过滤函数搜索文件夹及其子文件夹下所有的文件 * @param dir 要搜索的文件夹 * @param filterFunc 过滤函数:filterFunc(file:File):Boolean,参数为遍历过程中的每一个文件,返回true则加入结果列表 */ export function searchByFunction(dir: string, filterFunc: Function, checkDir?: boolean): string[] { var list = []; try { var stat = FS.statSync(dir); } catch (e) { return list; } if (stat.isDirectory()) { findFiles(dir, list, "", filterFunc, checkDir); } return list; } function readdirSync(filePath: string) { var files = FS.readdirSync(filePath); files.sort(); return files; } function findFiles(filePath: string, list: string[], extension: string, filterFunc?: Function, checkDir?: boolean) { var files = readdirSync(filePath); var length = files.length; for (var i = 0; i < length; i++) { if (files[i].charAt(0) == ".") { continue; } var path = joinPath(filePath, files[i]); let exists = FS.existsSync(path); if (!exists) { continue; } var stat = FS.statSync(path); if (stat.isDirectory()) { if (checkDir) { if (!filterFunc(path)) { continue; } } findFiles(path, list, extension, filterFunc); } else if (filterFunc != null) { if (filterFunc(path)) { list.push(path); } } else if (extension) { var len = extension.length; if (path.charAt(path.length - len - 1) == "." && path.substr(path.length - len, len).toLowerCase() == extension) { list.push(path); } } else { list.push(path); } } } /** * 指定路径的文件或文件夹是否存在 */ export function exists(path: string): boolean { path = escapePath(path); return FS.existsSync(path); } /** * 转换本机路径为Unix风格路径。 */ export function escapePath(path: string): string { if (!path) return ""; return path.split("\\").join("/"); } /** * 连接路径,支持传入多于两个的参数。也支持"../"相对路径解析。返回的分隔符为Unix风格。 */ export function joinPath(dir: string, ...filename: string[]): string { var path = Path.join.apply(null, arguments); path = escapePath(path); return path; } export function getRelativePath(dir: string, filename: string) { var relative = Path.relative(dir, filename); return escapePath(relative);; } export function basename(p: string, ext?: string): string { var path = Path.basename.apply(null, arguments); path = escapePath(path); return path; } //获取相对路径 to相对于from的路径 export function relative(from: string, to: string) { var path = Path.relative.apply(null, arguments); path = escapePath(path); return path; } export function getAbsolutePath(path: string) { if (Path.isAbsolute(path)) { return escapePath(path); } return joinPath(egret.args.projectDir, path); } export function searchPath(searchPaths: string[]): string | null { for (let searchPath of searchPaths) { if (exists(searchPath)) { return searchPath; } } return null; } export function moveAsync(oldPath: string, newPath: string): Promise<void> { return new Promise<void>((resolve, reject) => { copy(oldPath, newPath); remove(oldPath); return resolve(); }); } export function existsSync(path: string): boolean { return FS.existsSync(path); } export function existsAsync(path: string): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { FS.exists(path, isExist => { return resolve(isExist); }) }); } export function copyAsync(src: string, dest: string): Promise<void> { return new Promise<void>((resolve, reject) => { copy(src, dest); return resolve(); }); } export function removeAsync(dir: string): Promise<void> { return new Promise<void>((resolve, reject) => { remove(dir); return resolve(); }); } export function readFileSync(filename: string, encoding: string): string { return FS.readFileSync(filename, encoding); } export function readJSONAsync(file: string, options?: { encoding: string; flag?: string; }): Promise<any> { return new Promise<any>((resolve, reject) => { FS.readFile(file, options, (err, data: string) => { if (err) { return reject(err); } else { try { let retObj = JSON.parse(data); return resolve(retObj); } catch (err) { return reject(err); } } }); }); } export function readJSONSync(file: string) { let content = readFileSync(file, 'utf-8') return JSON.parse(content); } export function statSync(path: string): Stats { return FS.statSync(path); } export function writeJSONAsync(file: string, object: any): Promise<void> { return new Promise<void>((resolve, reject) => { try { let retObj: string = JSON.stringify(object, null, 4); FS.writeFile(file, retObj, { encoding: "utf-8" }, err => { if (err) { reject(err); } else { resolve(); } }); } catch (err) { return reject(err); } }); }
the_stack
import { Svg, Path, Command } from '@svg-drawing/core' import { convertRGBAImage } from './utils/convertRGBAImage' import type { Rgba } from './palette' import type { PathObject } from '@svg-drawing/core' type ColorQuantization = number[][] // Edge node types ( ▓: this layer or 1; ░: not this layer or 0 ) // 12 ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ // 48 ░░ ░░ ░░ ░░ ░▓ ░▓ ░▓ ░▓ ▓░ ▓░ ▓░ ▓░ ▓▓ ▓▓ ▓▓ ▓▓ // Type 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 type EdgeType = | -1 // Empty | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 type EdgeLayer = EdgeType[][] interface PathInfo { commands: Command[] holeCommands: Command[] holechildren: number[] isholepath: boolean } interface PointInfo { points: Point[] boundingbox: [number, number, number, number] holechildren: number[] isholepath: boolean } type DirectionValue = typeof DIRECTION_TYPE[keyof typeof DIRECTION_TYPE] const DIRECTION_TYPE = { RIGHT: 0, RIGHT_BOTTOM: 1, BOTTOM: 2, LEFT_BOTTOM: 3, LEFT: 4, LEFT_TOP: 5, TOP: 6, RIGHT_TOP: 7, CENTER: 8, EMPTY: -1, } as const interface Point { x: number y: number direction: DirectionValue } export interface ImgTraceOption { // Tracing ltres?: number qtres?: number rightangleenhance?: boolean // filter pathOmit?: number commandOmit?: number // override path element attribute pathAttrs?: PathObject palettes?: Rgba[] } const pathscanCombinedLookup: EdgeType[][][] = [ [ [-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], ], // arr[py][px]===0 is invalid [ [0, 1, 0, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], [0, 2, -1, 0], ], [ [-1, -1, -1, -1], [-1, -1, -1, -1], [0, 1, 0, -1], [0, 0, 1, 0], ], [ [0, 0, 1, 0], [-1, -1, -1, -1], [0, 2, -1, 0], [-1, -1, -1, -1], ], [ [-1, -1, -1, -1], [0, 0, 1, 0], [0, 3, 0, 1], [-1, -1, -1, -1], ], [ [13, 3, 0, 1], [13, 2, -1, 0], [7, 1, 0, -1], [7, 0, 1, 0], ], [ [-1, -1, -1, -1], [0, 1, 0, -1], [-1, -1, -1, -1], [0, 3, 0, 1], ], [ [0, 3, 0, 1], [0, 2, -1, 0], [-1, -1, -1, -1], [-1, -1, -1, -1], ], [ [0, 3, 0, 1], [0, 2, -1, 0], [-1, -1, -1, -1], [-1, -1, -1, -1], ], [ [-1, -1, -1, -1], [0, 1, 0, -1], [-1, -1, -1, -1], [0, 3, 0, 1], ], [ [11, 1, 0, -1], [14, 0, 1, 0], [14, 3, 0, 1], [11, 2, -1, 0], ], [ [-1, -1, -1, -1], [0, 0, 1, 0], [0, 3, 0, 1], [-1, -1, -1, -1], ], [ [0, 0, 1, 0], [-1, -1, -1, -1], [0, 2, -1, 0], [-1, -1, -1, -1], ], [ [-1, -1, -1, -1], [-1, -1, -1, -1], [0, 1, 0, -1], [0, 0, 1, 0], ], [ [0, 1, 0, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], [0, 2, -1, 0], ], [ [-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], ], // arr[py][px]===15 is invalid ] const DEFAULT_PALETTES = [ { r: 0, g: 0, b: 0, a: 255 }, { r: 50, g: 50, b: 50, a: 255 }, { r: 100, g: 100, b: 100, a: 255 }, { r: 150, g: 150, b: 150, a: 255 }, { r: 200, g: 200, b: 200, a: 255 }, ] export class ImgTrace { // Tracing public ltres: number public qtres: number public rightangleenhance: boolean // Filter public pathOmit: number public commandOmit: number // Path element attribute public pathAttrs: PathObject // Palettes public palettes: Rgba[] // creating options object, setting defaults for missing values constructor(opts: ImgTraceOption = {}) { // Tracing this.ltres = opts.ltres ?? 1 this.qtres = opts.qtres ?? 1 this.rightangleenhance = opts.rightangleenhance ?? true // Filter this.pathOmit = opts.pathOmit ?? 8 this.commandOmit = opts.commandOmit ?? 0 // SVG rendering this.pathAttrs = { strokeWidth: '1', ...(opts.pathAttrs || {}) } // Palette this.palettes = opts.palettes || DEFAULT_PALETTES } public load(argImgd: ImageData): Svg { const imgd = convertRGBAImage(argImgd) const cq = this._colorQuantization(imgd) const pathLayer: PathInfo[][] = [] for (let paletteId = 0; paletteId < this.palettes.length; paletteId++) { const edge = this._edgeDetection(cq, paletteId) const path = this._pathScan(edge) const interporation = this._interpolation(path) const tracedpath = interporation.map(this._tracePath.bind(this)) pathLayer.push(tracedpath) } const paths = this._createPaths(pathLayer) return new Svg({ width: cq[0].length - 2, height: cq.length - 2, }).addPath(paths) } private _colorQuantization(imgd: ImageData): ColorQuantization { return Array.from({ length: imgd.height + 2 }, (_h, j) => Array.from({ length: imgd.width + 2 }, (_w, i) => { if ( i === 0 || i === imgd.width + 1 || j === 0 || j === imgd.height + 1 ) { return -1 } // pixel index const h = j - 1 const w = i - 1 const idx = (h * imgd.width + w) * 4 return this._findPaletteIndex({ r: imgd.data[idx], g: imgd.data[idx + 1], b: imgd.data[idx + 2], a: imgd.data[idx + 3], }) }) ) } /** * Find similar color from palette and return ID * * @param {Rgba} color Pixel color */ private _findPaletteIndex({ r, g, b, a }: Rgba): number { let cdl = 1024 // 4 * 256 is the maximum RGBA distance return this.palettes.reduce((findId, pal, id) => { const cd = Math.abs(pal.r - r) + Math.abs(pal.g - g) + Math.abs(pal.b - b) + Math.abs(pal.a - a) if (cd < cdl) { cdl = cd return id } return findId }, 0) } private _edgeDetection(cq: ColorQuantization, palId: number): EdgeLayer { const res: EdgeLayer = [] const ah = cq.length const aw = cq[0].length for (let h = 0; h < ah; h++) { res[h] = [] for (let w = 0; w < aw; w++) { res[h][w] = h === 0 || w === 0 ? 0 : (((cq[h - 1][w - 1] === palId ? 1 : 0) + (cq[h - 1][w] === palId ? 2 : 0) + (cq[h][w - 1] === palId ? 8 : 0) + (cq[h][w] === palId ? 4 : 0)) as EdgeType) } } return res } private _pointpoly(p: Point, pa: Point[]): boolean { let isin = false for (let i = 0, j = pa.length - 1; i < pa.length; j = i++) { isin = pa[i].y > p.y !== pa[j].y > p.y && p.x < ((pa[j].x - pa[i].x) * (p.y - pa[i].y)) / (pa[j].y - pa[i].y) + pa[i].x ? !isin : isin } return isin } private _pathScan(edge: EdgeLayer): PointInfo[] { const width = edge[0].length const height = edge.length const paths: PointInfo[] = [] let pacnt = 0 for (let h = 0; h < height; h++) { for (let w = 0; w < width; w++) { // Related for edgeDetection methods const edgeType = edge[h][w] if (edgeType !== 4 && edgeType !== 11) { continue } let px = w let py = h let dir = 1 let pcnt = 0 let pathfinished = false paths[pacnt] = { points: [], boundingbox: [px, py, px, py], holechildren: [], isholepath: false, } while (!pathfinished) { paths[pacnt].points[pcnt] = { x: px - 1, y: py - 1, direction: DIRECTION_TYPE.EMPTY, } if (px - 1 < paths[pacnt].boundingbox[0]) { paths[pacnt].boundingbox[0] = px - 1 } if (px - 1 > paths[pacnt].boundingbox[2]) { paths[pacnt].boundingbox[2] = px - 1 } if (py - 1 < paths[pacnt].boundingbox[1]) { paths[pacnt].boundingbox[1] = py - 1 } if (py - 1 > paths[pacnt].boundingbox[3]) { paths[pacnt].boundingbox[3] = py - 1 } const lookuprow = pathscanCombinedLookup[edge[py][px]][dir] edge[py][px] = lookuprow[0] dir = lookuprow[1] px += lookuprow[2] py += lookuprow[3] // Close path if ( px - 1 === paths[pacnt].points[0].x && py - 1 === paths[pacnt].points[0].y ) { pathfinished = true if (paths[pacnt].points.length < this.pathOmit) { paths.pop() } else { if (edgeType === 11) { paths[pacnt].isholepath = true let parentidx = 0 let parentbbox = [-1, -1, width + 1, height + 1] for (let parentcnt = 0; parentcnt < pacnt; parentcnt++) { if ( !paths[parentcnt].isholepath && this._boundingboxincludes( paths[parentcnt].boundingbox, paths[pacnt].boundingbox ) && this._boundingboxincludes( parentbbox, paths[parentcnt].boundingbox ) && this._pointpoly( paths[pacnt].points[0], paths[parentcnt].points ) ) { parentidx = parentcnt parentbbox = paths[parentcnt].boundingbox } } paths[parentidx].holechildren.push(pacnt) } pacnt++ } } pcnt++ } } } return paths } private _boundingboxincludes( parentbbox: number[], childbbox: number[] ): boolean { return ( parentbbox[0] < childbbox[0] && parentbbox[1] < childbbox[1] && parentbbox[2] > childbbox[2] && parentbbox[3] > childbbox[3] ) } private _interpolation(paths: PointInfo[]): PointInfo[] { const ins: PointInfo[] = [] let nextidx = 0 let nextidx2 = 0 let previdx = 0 let previdx2 = 0 for (let pacnt = 0; pacnt < paths.length; pacnt++) { ins[pacnt] = { points: [], boundingbox: paths[pacnt].boundingbox, holechildren: paths[pacnt].holechildren, isholepath: paths[pacnt].isholepath, } const palen = paths[pacnt].points.length for (let pcnt = 0; pcnt < palen; pcnt++) { nextidx = (pcnt + 1) % palen nextidx2 = (pcnt + 2) % palen previdx = (pcnt - 1 + palen) % palen previdx2 = (pcnt - 2 + palen) % palen if ( this.rightangleenhance && this._testrightangle( paths[pacnt], previdx2, previdx, pcnt, nextidx, nextidx2 ) ) { if (ins[pacnt].points.length > 0) { ins[pacnt].points[ins[pacnt].points.length - 1].direction = this._getdirection( ins[pacnt].points[ins[pacnt].points.length - 1].x, ins[pacnt].points[ins[pacnt].points.length - 1].y, paths[pacnt].points[pcnt].x, paths[pacnt].points[pcnt].y ) } ins[pacnt].points.push({ x: paths[pacnt].points[pcnt].x, y: paths[pacnt].points[pcnt].y, direction: this._getdirection( paths[pacnt].points[pcnt].x, paths[pacnt].points[pcnt].y, (paths[pacnt].points[pcnt].x + paths[pacnt].points[nextidx].x) / 2, (paths[pacnt].points[pcnt].y + paths[pacnt].points[nextidx].y) / 2 ), }) } ins[pacnt].points.push({ x: (paths[pacnt].points[pcnt].x + paths[pacnt].points[nextidx].x) / 2, y: (paths[pacnt].points[pcnt].y + paths[pacnt].points[nextidx].y) / 2, direction: this._getdirection( paths[pacnt].points[pcnt].x + paths[pacnt].points[nextidx].x, paths[pacnt].points[pcnt].y + paths[pacnt].points[nextidx].y, paths[pacnt].points[nextidx].x + paths[pacnt].points[nextidx2].x, paths[pacnt].points[nextidx].y + paths[pacnt].points[nextidx2].y ), }) } } return ins } private _testrightangle( path: PointInfo, idx1: number, idx2: number, idx3: number, idx4: number, idx5: number ): boolean { return ( (path.points[idx3].x === path.points[idx1].x && path.points[idx3].x === path.points[idx2].x && path.points[idx3].y === path.points[idx4].y && path.points[idx3].y === path.points[idx5].y) || (path.points[idx3].y === path.points[idx1].y && path.points[idx3].y === path.points[idx2].y && path.points[idx3].x === path.points[idx4].x && path.points[idx3].x === path.points[idx5].x) ) } private _getdirection( x1: number, y1: number, x2: number, y2: number ): DirectionValue { if (x1 < x2) { if (y1 < y2) { return DIRECTION_TYPE.RIGHT_BOTTOM } if (y1 > y2) { return DIRECTION_TYPE.RIGHT_TOP } return DIRECTION_TYPE.RIGHT_TOP } if (x1 > x2) { if (y1 < y2) { return DIRECTION_TYPE.LEFT_BOTTOM } if (y1 > y2) { return DIRECTION_TYPE.LEFT_TOP } return DIRECTION_TYPE.LEFT } if (y1 < y2) { return DIRECTION_TYPE.BOTTOM } if (y1 > y2) { return DIRECTION_TYPE.TOP } return DIRECTION_TYPE.CENTER } private _tracePath(path: PointInfo): PathInfo { let pcnt = 0 const comms: Command[] = [] const holes: Command[] = [] while (pcnt < path.points.length) { // 5.1. Find sequences of points with only 2 segment types const segtype1: DirectionValue = path.points[pcnt].direction let segtype2: DirectionValue = DIRECTION_TYPE.EMPTY let seqend = pcnt + 1 while ( (path.points[seqend].direction === segtype1 || path.points[seqend].direction === segtype2 || segtype2 === -1) && seqend < path.points.length - 1 ) { if ( path.points[seqend].direction !== segtype1 && segtype2 === DIRECTION_TYPE.EMPTY ) { segtype2 = path.points[seqend].direction || DIRECTION_TYPE.RIGHT } seqend++ } if (seqend === path.points.length - 1) { comms.push(...this._fitseq(path, pcnt, 0)) holes.push(...this._fitseq(path, pcnt, 0, true)) pcnt = path.points.length } else { comms.push(...this._fitseq(path, pcnt, seqend)) holes.push(...this._fitseq(path, pcnt, seqend, true)) pcnt = seqend } } const commands = [ new Command('M', [path.points[0].x, path.points[0].y]), ...comms, new Command('Z'), ] holes.reverse() const holeCommands = [ new Command('M', holes[holes.length - 1].value.slice(0, 2)), ...holes, new Command('Z'), ] return { commands, holeCommands, holechildren: path.holechildren, isholepath: path.isholepath, } } private _fitseq( path: PointInfo, seqstart: number, seqend: number, isHolePath?: boolean ): Command[] { const ltres = this.ltres const qtres = this.qtres if (seqend > path.points.length || seqend < 0) { return [] } let errorpoint = seqstart let errorval = 0 let curvepass = true let px let py let dist2 let tl = seqend - seqstart if (tl < 0) { tl += path.points.length } const vx = (path.points[seqend].x - path.points[seqstart].x) / tl const vy = (path.points[seqend].y - path.points[seqstart].y) / tl let pcnt = (seqstart + 1) % path.points.length while (pcnt != seqend) { let pl = pcnt - seqstart if (pl < 0) { pl += path.points.length } px = path.points[seqstart].x + vx * pl py = path.points[seqstart].y + vy * pl dist2 = (path.points[pcnt].x - px) * (path.points[pcnt].x - px) + (path.points[pcnt].y - py) * (path.points[pcnt].y - py) if (dist2 > ltres) { curvepass = false } if (dist2 > errorval) { errorpoint = pcnt errorval = dist2 } pcnt = (pcnt + 1) % path.points.length } if (curvepass) { return [ new Command( 'L', isHolePath ? [path.points[seqstart].x, path.points[seqstart].y] : [path.points[seqend].x, path.points[seqend].y] ), ] } const fitpoint = errorpoint curvepass = true errorval = 0 let t = (fitpoint - seqstart) / tl let t1 = (1 - t) * (1 - t) let t2 = 2 * (1 - t) * t let t3 = t * t const cpx = (t1 * path.points[seqstart].x + t3 * path.points[seqend].x - path.points[fitpoint].x) / -t2 const cpy = (t1 * path.points[seqstart].y + t3 * path.points[seqend].y - path.points[fitpoint].y) / -t2 pcnt = seqstart + 1 while (pcnt != seqend) { t = (pcnt - seqstart) / tl t1 = (1 - t) * (1 - t) t2 = 2 * (1 - t) * t t3 = t * t px = t1 * path.points[seqstart].x + t2 * cpx + t3 * path.points[seqend].x py = t1 * path.points[seqstart].y + t2 * cpy + t3 * path.points[seqend].y dist2 = (path.points[pcnt].x - px) * (path.points[pcnt].x - px) + (path.points[pcnt].y - py) * (path.points[pcnt].y - py) if (dist2 > qtres) { curvepass = false } if (dist2 > errorval) { errorpoint = pcnt errorval = dist2 } pcnt = (pcnt + 1) % path.points.length } if (curvepass) { return [ new Command('Q', [ cpx, cpy, path.points[seqend].x, path.points[seqend].y, ]), ] } const splitpoint = fitpoint return this._fitseq(path, seqstart, splitpoint, isHolePath).concat( this._fitseq(path, splitpoint, seqend, isHolePath) ) } private _complementCommand(info: PathInfo[], layerIndex: number): Command[] { const p = info[layerIndex] const complement = [] for (let hcnt = 0; hcnt < p.holechildren.length; hcnt++) { complement.push(...info[p.holechildren[hcnt]].holeCommands) } return complement } private _createPaths(pathLayer: PathInfo[][]): Path[] { const result: Path[] = [] for (let lcnt = 0; lcnt < pathLayer.length; lcnt++) { for (let pcnt = 0; pcnt < pathLayer[lcnt].length; pcnt++) { const layer = pathLayer[lcnt] const smp = layer[pcnt] if (smp.isholepath || smp.commands.length < this.commandOmit) continue const rgba = this.palettes[lcnt] const color = `rgb(${rgba.r}, ${rgba.g}, ${rgba.b})` const path = new Path({ ...this.pathAttrs, stroke: color, fill: color, opacity: String(rgba.a / 255.0), }) path.addCommand([ ...smp.commands, ...this._complementCommand(layer, pcnt), ]) result.push(path) } } return result } }
the_stack
import {assert} from 'chrome://resources/js/assert.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {PromiseResolver} from 'chrome://resources/js/promise_resolver.m.js'; import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {BackgroundGraphicsModeRestriction, ColorModeRestriction, DuplexModeRestriction, PinModeRestriction, Policies} from '../native_layer.js'; import {CapabilityWithReset, Cdd, CddCapabilities, ColorOption, DpiOption, DuplexOption, MediaSizeOption, VendorCapability} from './cdd.js'; import {Destination, DestinationOrigin, DestinationType, GooglePromotedDestinationId, RecentDestination} from './destination.js'; import {getPrinterTypeForDestination, PrinterType} from './destination_match.js'; import {DocumentSettings} from './document_info.js'; import {CustomMarginsOrientation, Margins, MarginsSetting, MarginsType} from './margins.js'; import {ScalingType} from './scaling.js'; import {Size} from './size.js'; /** * |key| is the field in the serialized settings state that corresponds to the * setting, or an empty string if the setting should not be saved in the * serialized state. */ export type Setting = { value: any, unavailableValue: any, valid: boolean, available: boolean, setByPolicy: boolean, setFromUi: boolean, key: string, updatesPreview: boolean, }; export type Settings = { pages: Setting, copies: Setting, collate: Setting, layout: Setting, color: Setting, customMargins: Setting, mediaSize: Setting, margins: Setting, dpi: Setting, scaling: Setting, scalingType: Setting, scalingTypePdf: Setting, duplex: Setting, duplexShortEdge: Setting, cssBackground: Setting, selectionOnly: Setting, headerFooter: Setting, rasterize: Setting, vendorItems: Setting, otherOptions: Setting, ranges: Setting, pagesPerSheet: Setting, pin?: Setting, pinValue?: Setting, }; export type SerializedSettings = { version: number, recentDestinations?: RecentDestination[], dpi?: DpiOption, mediaSize?: MediaSizeOption, marginsType?: MarginsType, customMargins?: MarginsSetting, isColorEnabled?: boolean, isDuplexEnabled?: boolean, isHeaderFooterEnabled?: boolean, isLandscapeEnabled?: boolean, isCollateEnabled?: boolean, isCssBackgroundEnabled?: boolean, scaling?: string, scalingType?: ScalingType, scalingTypePdf?: ScalingType, vendor_options?: object, isPinEnabled?: boolean, pinValue?: string, }; export type PolicyEntry = { value: any, managed: boolean, applyOnDestinationUpdate: boolean, }; export type PolicySettings = { headerFooter?: PolicyEntry, cssBackground?: PolicyEntry, mediaSize?: PolicyEntry, sheets?: PolicyEntry, color?: PolicyEntry, duplex?: PolicyEntry, pin?: PolicyEntry, printPdfAsImageAvailability?: PolicyEntry, printPdfAsImage?: PolicyEntry, }; type CloudJobTicketPrint = { page_orientation?: object, dpi?: object, vendor_ticket_item?: object[], copies?: object, media_size?: object, duplex?: object, color?: {vendor_id?: string, type?: string}, collate?: object, } type CloudJobTicket = { version: string, print: CloudJobTicketPrint, }; export type MediaSizeValue = { width_microns: number; height_microns: number; }; export type Ticket = { collate: boolean, color: number, copies: number, deviceName: string, dpiHorizontal: number, dpiVertical: number, duplex: DuplexMode, headerFooterEnabled: boolean, landscape: boolean, marginsType: MarginsType, mediaSize: MediaSizeValue, pagesPerSheet: number, previewModifiable: boolean, printerType: PrinterType, rasterizePDF: boolean, scaleFactor: number, scalingType: ScalingType, shouldPrintBackgrounds: boolean, shouldPrintSelectionOnly: boolean, advancedSettings?: object, capabilities?: string, cloudPrintID?: string, marginsCustom?: MarginsSetting, openPDFInPreview?: boolean, pinValue?: string, ticket?: string, }; type PrintTicket = Ticket&{ dpiDefault: boolean, pageCount: number, pageHeight: number, pageWidth: number, printToGoogleDrive: boolean, showSystemDialog: boolean, }; /** * Constant values matching printing::DuplexMode enum. */ export enum DuplexMode { SIMPLEX = 0, LONG_EDGE = 1, SHORT_EDGE = 2, UNKNOWN_DUPLEX_MODE = -1, } /** * Values matching the types of duplex in a CDD. */ export enum DuplexType { NO_DUPLEX = 'NO_DUPLEX', LONG_EDGE = 'LONG_EDGE', SHORT_EDGE = 'SHORT_EDGE', } let instance: PrintPreviewModelElement|null = null; let whenReadyResolver: PromiseResolver<void> = new PromiseResolver(); export function getInstance(): PrintPreviewModelElement { return assert(instance!); } export function whenReady(): Promise<void> { return whenReadyResolver.promise; } /** * Sticky setting names in alphabetical order. */ const STICKY_SETTING_NAMES: string[] = [ 'recentDestinations', 'collate', 'color', 'cssBackground', 'customMargins', 'dpi', 'duplex', 'duplexShortEdge', 'headerFooter', 'layout', 'margins', 'mediaSize', 'scaling', 'scalingType', 'scalingTypePdf', 'vendorItems', ]; // <if expr="chromeos or lacros"> STICKY_SETTING_NAMES.push('pin', 'pinValue'); // </if> /** * Minimum height of page in microns to allow headers and footers. Should * match the value for min_size_printer_units in printing/print_settings.cc * so that we do not request header/footer for margins that will be zero. */ const MINIMUM_HEIGHT_MICRONS: number = 25400; export class PrintPreviewModelElement extends PolymerElement { static get is() { return 'print-preview-model'; } static get template() { return null; } static get properties() { return { /** * Object containing current settings of Print Preview, for use by Polymer * controls. * Initialize all settings to available so that more settings always stays * in a collapsed state during startup, when document information and * printer capabilities may arrive at slightly different times. */ settings: { type: Object, notify: true, value() { return { pages: { value: [1], unavailableValue: [], valid: true, available: true, setByPolicy: false, setFromUi: false, key: '', updatesPreview: false, }, copies: { value: 1, unavailableValue: 1, valid: true, available: true, setByPolicy: false, setFromUi: false, key: '', updatesPreview: false, }, collate: { value: true, unavailableValue: false, valid: true, available: true, setByPolicy: false, setFromUi: false, key: 'isCollateEnabled', updatesPreview: false, }, layout: { value: false, /* portrait */ unavailableValue: false, valid: true, available: true, setByPolicy: false, setFromUi: false, key: 'isLandscapeEnabled', updatesPreview: true, }, color: { value: true, /* color */ unavailableValue: false, valid: true, available: true, setByPolicy: false, setFromUi: false, key: 'isColorEnabled', updatesPreview: true, }, mediaSize: { value: {}, unavailableValue: { width_microns: 215900, height_microns: 279400, }, valid: true, available: true, setByPolicy: false, setFromUi: false, key: 'mediaSize', updatesPreview: true, }, margins: { value: MarginsType.DEFAULT, unavailableValue: MarginsType.DEFAULT, valid: true, available: true, setByPolicy: false, setFromUi: false, key: 'marginsType', updatesPreview: true, }, customMargins: { value: {}, unavailableValue: {}, valid: true, available: true, setByPolicy: false, setFromUi: false, key: 'customMargins', updatesPreview: true, }, dpi: { value: {}, unavailableValue: {}, valid: true, available: true, setByPolicy: false, setFromUi: false, key: 'dpi', updatesPreview: false, }, scaling: { value: '100', unavailableValue: '100', valid: true, available: true, setByPolicy: false, setFromUi: false, key: 'scaling', updatesPreview: true, }, scalingType: { value: ScalingType.DEFAULT, unavailableValue: ScalingType.DEFAULT, valid: true, available: true, setByPolicy: false, setFromUi: false, key: 'scalingType', updatesPreview: true, }, scalingTypePdf: { value: ScalingType.DEFAULT, unavailableValue: ScalingType.DEFAULT, valid: true, available: true, setByPolicy: false, setFromUi: false, key: 'scalingTypePdf', updatesPreview: true, }, duplex: { value: true, unavailableValue: false, valid: true, available: true, setByPolicy: false, setFromUi: false, key: 'isDuplexEnabled', updatesPreview: false, }, duplexShortEdge: { value: false, unavailableValue: false, valid: true, available: true, setByPolicy: false, setFromUi: false, key: 'isDuplexShortEdge', updatesPreview: false, }, cssBackground: { value: false, unavailableValue: false, valid: true, available: true, setByPolicy: false, setFromUi: false, key: 'isCssBackgroundEnabled', updatesPreview: true, }, selectionOnly: { value: false, unavailableValue: false, valid: true, available: true, setByPolicy: false, setFromUi: false, key: '', updatesPreview: true, }, headerFooter: { value: true, unavailableValue: false, valid: true, available: true, setByPolicy: false, setFromUi: false, key: 'isHeaderFooterEnabled', updatesPreview: true, }, rasterize: { value: false, unavailableValue: false, valid: true, available: true, setByPolicy: false, setFromUi: false, key: '', updatesPreview: true, }, vendorItems: { value: {}, unavailableValue: {}, valid: true, available: true, setByPolicy: false, setFromUi: false, key: 'vendorOptions', updatesPreview: false, }, pagesPerSheet: { value: 1, unavailableValue: 1, valid: true, available: true, setByPolicy: false, setFromUi: false, key: '', updatesPreview: true, }, // This does not represent a real setting value, and is used only to // expose the availability of the other options settings section. otherOptions: { value: null, unavailableValue: null, valid: true, available: true, setByPolicy: false, setFromUi: false, key: '', updatesPreview: false, }, // This does not represent a real settings value, but is used to // propagate the correctly formatted ranges for print tickets. ranges: { value: [], unavailableValue: [], valid: true, available: true, setByPolicy: false, setFromUi: false, key: '', updatesPreview: true, }, recentDestinations: { value: [], unavailableValue: [], valid: true, available: true, setByPolicy: false, setFromUi: false, key: 'recentDestinations', updatesPreview: false, }, // <if expr="chromeos or lacros"> pin: { value: false, unavailableValue: false, valid: true, available: true, setByPolicy: false, setFromUi: false, key: 'isPinEnabled', updatesPreview: false, }, pinValue: { value: '', unavailableValue: '', valid: true, available: true, setByPolicy: false, setFromUi: false, key: 'pinValue', updatesPreview: false, }, // </if> }; }, }, settingsManaged: { type: Boolean, notify: true, value: false, }, destination: Object, documentSettings: Object, margins: Object, pageSize: Object, maxSheets: { type: Number, value: 0, notify: true, } }; } static get observers() { return [ 'updateSettingsFromDestination_(destination.capabilities)', 'updateSettingsAvailabilityFromDocumentSettings_(' + 'documentSettings.isModifiable, documentSettings.isFromArc,' + 'documentSettings.hasCssMediaStyles, documentSettings.hasSelection)', 'updateHeaderFooterAvailable_(' + 'margins, settings.margins.value, settings.mediaSize.value)', ]; } settings: Settings; settingsManaged: boolean; destination: Destination; documentSettings: DocumentSettings; margins: Margins; pageSize: Size; maxSheets: number; private initialized_: boolean = false; private stickySettings_: SerializedSettings|null = null; private policySettings_: PolicySettings|null = null; private lastDestinationCapabilities_: Cdd|null = null; connectedCallback() { super.connectedCallback(); assert(!instance); instance = this; whenReadyResolver.resolve(); } disconnectedCallback() { super.disconnectedCallback(); instance = null; whenReadyResolver = new PromiseResolver(); } private fire_(eventName: string, detail?: any) { this.dispatchEvent( new CustomEvent(eventName, {bubbles: true, composed: true, detail})); } getSetting(settingName: string): Setting { const setting = (this.get(settingName, this.settings) as Setting); assert(setting, 'Setting is missing: ' + settingName); return setting; } /** * @param settingName Name of the setting to get the value for. * @return The value of the setting, accounting for availability. */ getSettingValue(settingName: string): any { const setting = this.getSetting(settingName); return setting.available ? setting.value : setting.unavailableValue; } /** * Updates settings.settingPath to |value|. Fires a preview-setting-changed * event if the modification results in a change to the value returned by * getSettingValue(). */ private setSettingPath_(settingPath: string, value: any) { const settingName = settingPath.split('.')[0]; const setting = this.getSetting(settingName); const oldValue = this.getSettingValue(settingName); this.set(`settings.${settingPath}`, value); const newValue = this.getSettingValue(settingName); if (newValue !== oldValue && setting.updatesPreview) { this.fire_('preview-setting-changed'); } } /** * Sets settings.settingName.value to |value|, unless updating the setting is * disallowed by enterprise policy. Fires preview-setting-changed and * sticky-setting-changed events if the update impacts the preview or requires * an update to sticky settings. Used for setting settings from UI elements. * @param settingName Name of the setting to set * @param value The value to set the setting to. * @param noSticky Whether to avoid stickying the setting. Defaults to false. */ setSetting(settingName: string, value: any, noSticky?: boolean) { const setting = this.getSetting(settingName); if (setting.setByPolicy) { return; } const fireStickyEvent = !noSticky && setting.value !== value && setting.key; this.setSettingPath_(`${settingName}.value`, value); if (!noSticky) { this.setSettingPath_(`${settingName}.setFromUi`, true); } if (fireStickyEvent && this.initialized_) { this.fire_('sticky-setting-changed', this.getStickySettings_()); } } /** * @param settingName Name of the setting to set * @param start * @param end * @param newValue The value to add (if any). * @param noSticky Whether to avoid stickying the setting. Defaults to false. */ setSettingSplice( settingName: string, start: number, end: number, newValue: any, noSticky?: boolean) { const setting = this.getSetting(settingName); if (setting.setByPolicy) { return; } if (newValue) { this.splice(`settings.${settingName}.value`, start, end, newValue); } else { this.splice(`settings.${settingName}.value`, start, end); } if (!noSticky) { this.setSettingPath_(`${settingName}.setFromUi`, true); } if (!noSticky && setting.key && this.initialized_) { this.fire_('sticky-setting-changed', this.getStickySettings_()); } } /** * Sets the validity of |settingName| to |valid|. If the validity is changed, * fires a setting-valid-changed event. * @param settingName Name of the setting to set * @param valid Whether the setting value is currently valid. */ setSettingValid(settingName: string, valid: boolean) { const setting = this.getSetting(settingName); // Should not set the setting to invalid if it is not available, as there // is no way for the user to change the value in this case. if (!valid) { assert(setting.available, 'Setting is not available: ' + settingName); } const shouldFireEvent = valid !== setting.valid; this.set(`settings.${settingName}.valid`, valid); if (shouldFireEvent) { this.fire_('setting-valid-changed', valid); } } /** * Updates the availability of the settings sections and values of dpi and * media size settings based on the destination capabilities. */ private updateSettingsFromDestination_() { if (!this.destination || !this.settings) { return; } if (this.destination.capabilities === this.lastDestinationCapabilities_) { return; } this.lastDestinationCapabilities_ = this.destination.capabilities; const caps = this.destination.capabilities ? this.destination.capabilities.printer : null; this.updateSettingsAvailabilityFromDestination_(caps); if (!caps) { return; } this.updateSettingsValues_(caps); this.applyPersistentCddDefaults_(); } private updateSettingsAvailabilityFromDestination_(caps: CddCapabilities| null) { this.setSettingPath_( 'copies.available', this.destination.hasCopiesCapability); this.setSettingPath_('collate.available', !!caps && !!caps.collate); this.setSettingPath_( 'color.available', this.destination.hasColorCapability); const capsHasDuplex = !!caps && !!caps.duplex && !!caps.duplex.option; const capsHasLongEdge = capsHasDuplex && caps!.duplex!.option.some(o => o.type === DuplexType.LONG_EDGE); const capsHasShortEdge = capsHasDuplex && caps!.duplex!.option.some(o => o.type === DuplexType.SHORT_EDGE); this.setSettingPath_( 'duplexShortEdge.available', capsHasLongEdge && capsHasShortEdge); this.setSettingPath_( 'duplex.available', (capsHasLongEdge || capsHasShortEdge) && caps!.duplex!.option.some(o => o.type === DuplexType.NO_DUPLEX)); this.setSettingPath_( 'vendorItems.available', !!caps && !!caps.vendor_capability); // <if expr="chromeos or lacros"> const pinSupported = !!caps && !!caps.pin && !!caps.pin.supported && loadTimeData.getBoolean('isEnterpriseManaged'); this.set('settings.pin.available', pinSupported); this.set('settings.pinValue.available', pinSupported); // </if> if (this.documentSettings) { this.updateSettingsAvailabilityFromDestinationAndDocumentSettings_(); } } private updateSettingsAvailabilityFromDestinationAndDocumentSettings_() { const isSaveAsPDF = getPrinterTypeForDestination(this.destination) === PrinterType.PDF_PRINTER; const knownSizeToSaveAsPdf = isSaveAsPDF && (!this.documentSettings.isModifiable || this.documentSettings.hasCssMediaStyles); const scalingAvailable = !knownSizeToSaveAsPdf && !this.documentSettings.isFromArc; this.setSettingPath_('scaling.available', scalingAvailable); this.setSettingPath_( 'scalingType.available', scalingAvailable && this.documentSettings.isModifiable); this.setSettingPath_( 'scalingTypePdf.available', scalingAvailable && !this.documentSettings.isModifiable); const caps = this.destination && this.destination.capabilities ? this.destination.capabilities.printer : null; this.setSettingPath_( 'mediaSize.available', !!caps && !!caps.media_size && !knownSizeToSaveAsPdf); this.setSettingPath_( 'dpi.available', !this.documentSettings.isFromArc && !!caps && !!caps.dpi && !!caps.dpi.option && caps.dpi.option.length > 1); this.setSettingPath_('layout.available', this.isLayoutAvailable_(caps)); } private updateSettingsAvailabilityFromDocumentSettings_() { if (!this.settings) { return; } this.setSettingPath_( 'pagesPerSheet.available', !this.documentSettings.isFromArc); this.setSettingPath_( 'margins.available', !this.documentSettings.isFromArc && this.documentSettings.isModifiable); this.setSettingPath_( 'customMargins.available', !this.documentSettings.isFromArc && this.documentSettings.isModifiable); this.setSettingPath_( 'cssBackground.available', !this.documentSettings.isFromArc && this.documentSettings.isModifiable); this.setSettingPath_( 'selectionOnly.available', !this.documentSettings.isFromArc && this.documentSettings.isModifiable && this.documentSettings.hasSelection); this.setSettingPath_( 'headerFooter.available', !this.documentSettings.isFromArc && this.isHeaderFooterAvailable_()); this.setSettingPath_( 'rasterize.available', !this.documentSettings.isFromArc && this.isRasterizeAvailable_()); this.setSettingPath_( 'otherOptions.available', this.settings.cssBackground.available || this.settings.selectionOnly.available || this.settings.headerFooter.available || this.settings.rasterize.available); if (this.destination) { this.updateSettingsAvailabilityFromDestinationAndDocumentSettings_(); } } private updateHeaderFooterAvailable_() { if (this.documentSettings === undefined) { return; } this.setSettingPath_( 'headerFooter.available', this.isHeaderFooterAvailable_()); } /** * @return Whether the header/footer setting should be available. */ private isHeaderFooterAvailable_(): boolean { // Always unavailable for PDFs. if (!this.documentSettings.isModifiable) { return false; } // Always unavailable for small paper sizes. const microns = this.getSettingValue('layout') ? this.getSettingValue('mediaSize').width_microns : this.getSettingValue('mediaSize').height_microns; if (microns < MINIMUM_HEIGHT_MICRONS) { return false; } // Otherwise, availability depends on the margins. const marginsType = this.getSettingValue('margins') as MarginsType; if (marginsType === MarginsType.NO_MARGINS) { return false; } if (marginsType === MarginsType.MINIMUM) { return true; } return !this.margins || this.margins.get(CustomMarginsOrientation.TOP) > 0 || this.margins.get(CustomMarginsOrientation.BOTTOM) > 0; } private updateRasterizeAvailable_() { // Need document settings to know if source is PDF. if (this.documentSettings === undefined) { return; } this.setSettingPath_('rasterize.available', this.isRasterizeAvailable_()); } /** * @return Whether the rasterization setting should be available. */ private isRasterizeAvailable_(): boolean { // Only a possibility for PDFs. Always available for PDFs on Linux and // ChromeOS. crbug.com/675798 let available = !!this.documentSettings && !this.documentSettings.isModifiable; // <if expr="is_win or is_macosx"> // Availability on Windows or macOS depends upon policy. if (!available || !this.policySettings_) { return false; } const policy = this.policySettings_['printPdfAsImageAvailability']; available = policy !== undefined && policy.value; // </if> return available; } private isLayoutAvailable_(caps: CddCapabilities|null): boolean { if (!caps || !caps.page_orientation || !caps.page_orientation.option || (!this.documentSettings.isModifiable && !this.documentSettings.isFromArc) || this.documentSettings.hasCssMediaStyles) { return false; } let hasAutoOrPortraitOption = false; let hasLandscapeOption = false; caps.page_orientation.option.forEach(option => { hasAutoOrPortraitOption = hasAutoOrPortraitOption || option.type === 'AUTO' || option.type === 'PORTRAIT'; hasLandscapeOption = hasLandscapeOption || option.type === 'LANDSCAPE'; }); return hasLandscapeOption && hasAutoOrPortraitOption; } private updateSettingsValues_(caps: CddCapabilities|null) { if (this.settings.mediaSize.available) { const defaultOption = caps!.media_size!.option.find(o => !!o.is_default) || caps!.media_size!.option[0]; let matchingOption = null; // If the setting does not have a valid value, the UI has just started so // do not try to get a matching value; just set the printer default in // case the user doesn't have sticky settings. if (this.settings.mediaSize.setFromUi) { const currentMediaSize = this.getSettingValue('mediaSize'); matchingOption = caps!.media_size!.option.find(o => { return o.height_microns === currentMediaSize.height_microns && o.width_microns === currentMediaSize.width_microns; }); } this.setSetting('mediaSize', matchingOption || defaultOption, true); } if (this.settings.dpi.available) { const defaultOption = caps!.dpi!.option.find(o => !!o.is_default) || caps!.dpi!.option[0]; let matchingOption = null; if (this.settings.dpi.setFromUi) { const currentDpi = this.getSettingValue('dpi'); matchingOption = caps!.dpi!.option.find(o => { return o.horizontal_dpi === currentDpi.horizontal_dpi && o.vertical_dpi === currentDpi.vertical_dpi; }); } this.setSetting('dpi', matchingOption || defaultOption, true); } else if ( caps && caps.dpi && caps.dpi.option && caps.dpi.option.length > 0) { const unavailableValue = caps!.dpi!.option.find(o => !!o.is_default) || caps!.dpi!.option[0]; this.setSettingPath_('dpi.unavailableValue', unavailableValue); } if (!this.settings.color.setFromUi && this.settings.color.available) { const defaultOption = this.destination.defaultColorOption; if (defaultOption) { this.setSetting( 'color', !['STANDARD_MONOCHROME', 'CUSTOM_MONOCHROME'].includes( defaultOption.type!), true); } } else if ( !this.settings.color.available && (this.destination.id === GooglePromotedDestinationId.DOCS || this.destination.type === DestinationType.MOBILE)) { this.setSettingPath_('color.unavailableValue', true); } else if ( !this.settings.color.available && caps && caps.color && caps.color.option && caps.color.option.length > 0) { this.setSettingPath_( 'color.unavailableValue', !['STANDARD_MONOCHROME', 'CUSTOM_MONOCHROME'].includes( caps.color.option[0].type!)); } else if (!this.settings.color.available) { // if no color capability is reported, assume black and white. this.setSettingPath_('color.unavailableValue', false); } if (!this.settings.duplex.setFromUi && this.settings.duplex.available) { const defaultOption = caps!.duplex!.option.find(o => !!o.is_default); this.setSetting( 'duplex', defaultOption ? (defaultOption.type === DuplexType.LONG_EDGE || defaultOption.type === DuplexType.SHORT_EDGE) : false, true); this.setSetting( 'duplexShortEdge', defaultOption ? defaultOption.type === DuplexType.SHORT_EDGE : false, true); if (!this.settings.duplexShortEdge.available) { // Duplex is available, so must have only one two sided printing option. // Set duplexShortEdge's unavailable value based on the printer. this.setSettingPath_( 'duplexShortEdge.unavailableValue', caps!.duplex!.option.some(o => o.type === DuplexType.SHORT_EDGE)); } } else if ( !this.settings.duplex.available && caps && caps.duplex && caps.duplex.option) { // In this case, there must only be one option. const hasLongEdge = caps!.duplex!.option.some(o => o.type === DuplexType.LONG_EDGE); const hasShortEdge = caps!.duplex!.option.some(o => o.type === DuplexType.SHORT_EDGE); // If the only option available is long edge, the value should always be // true. this.setSettingPath_( 'duplex.unavailableValue', hasLongEdge || hasShortEdge); this.setSettingPath_('duplexShortEdge.unavailableValue', hasShortEdge); } else if (!this.settings.duplex.available) { // If no duplex capability is reported, assume false. this.setSettingPath_('duplex.unavailableValue', false); this.setSettingPath_('duplexShortEdge.unavailableValue', false); } if (this.settings.vendorItems.available) { const vendorSettings: {[key: string]: any} = {}; for (const item of caps!.vendor_capability!) { let defaultValue = null; if (item.type === 'SELECT' && item.select_cap && item.select_cap.option) { const defaultOption = item.select_cap.option.find(o => !!o.is_default); defaultValue = defaultOption ? defaultOption.value : null; } else if (item.type === 'RANGE') { if (item.range_cap) { defaultValue = item.range_cap.default || null; } } else if (item.type === 'TYPED_VALUE') { if (item.typed_value_cap) { defaultValue = item.typed_value_cap.default || null; } } if (defaultValue !== null) { vendorSettings[item.id] = defaultValue; } } this.setSetting('vendorItems', vendorSettings, true); } } /** * Caches the sticky settings and sets up the recent destinations. Sticky * settings will be applied when destinaton capabilities have been retrieved. */ setStickySettings(savedSettingsStr: string|null) { assert(!this.stickySettings_); if (!savedSettingsStr) { return; } let savedSettings; try { savedSettings = JSON.parse(savedSettingsStr) as SerializedSettings; } catch (e) { console.warn('Unable to parse state ' + e); return; // use default values rather than updating. } if (savedSettings.version !== 2) { return; } let recentDestinations = savedSettings.recentDestinations || []; if (!Array.isArray(recentDestinations)) { recentDestinations = [recentDestinations]; } // Remove unsupported privet printers from the sticky settings, // to free up these spots for supported printers. recentDestinations = recentDestinations.filter((d: RecentDestination) => { return d.origin !== DestinationOrigin.PRIVET; }); // <if expr="chromeos or lacros"> // Remove Cloud Print Drive destination. The Chrome OS version will always // be shown in the dropdown and is still supported. recentDestinations = recentDestinations.filter((d: RecentDestination) => { return d.id !== GooglePromotedDestinationId.DOCS; }); // </if> // Initialize recent destinations early so that the destination store can // start trying to fetch them. this.setSetting('recentDestinations', recentDestinations); savedSettings.recentDestinations = recentDestinations; this.stickySettings_ = savedSettings; } /** * Helper function for configurePolicySetting_(). Sets value and managed flag * for given setting. * @param settingName Name of the setting being applied. * @param value Value of the setting provided via policy. * @param managed Flag showing whether value of setting is managed. * @param applyOnDestinationUpdate Flag showing whether policy * should be applied on every destination update. */ private setPolicySetting_( settingName: string, value: any, managed: boolean, applyOnDestinationUpdate: boolean) { if (!this.policySettings_) { this.policySettings_ = {}; } (this.policySettings_ as {[key: string]: PolicyEntry})[settingName] = { value: value, managed: managed, applyOnDestinationUpdate: applyOnDestinationUpdate, }; } /** * Helper function for setPolicySettings(). Calculates value and managed flag * of the setting according to allowed and default modes. */ private configurePolicySetting_( settingName: string, allowedMode: any, defaultMode: any) { switch (settingName) { case 'headerFooter': { const value = allowedMode !== undefined ? allowedMode : defaultMode; if (value !== undefined) { this.setPolicySetting_( settingName, value, allowedMode !== undefined, /*applyOnDestinationUpdate=*/ false); } break; } case 'cssBackground': { const value = allowedMode ? allowedMode : defaultMode; if (value !== undefined) { this.setPolicySetting_( settingName, value === BackgroundGraphicsModeRestriction.ENABLED, !!allowedMode, /*applyOnDestinationUpdate=*/ false); } break; } case 'mediaSize': { if (defaultMode !== undefined) { this.setPolicySetting_( settingName, defaultMode, /*managed=*/ false, /*applyOnDestinationUpdate=*/ true); } break; } case 'color': { const value = allowedMode ? allowedMode : defaultMode; if (value !== undefined) { this.setPolicySetting_( settingName, value, !!allowedMode, /*applyOnDestinationUpdate=*/ false); } break; } case 'duplex': { const value = allowedMode ? allowedMode : defaultMode; if (value !== undefined) { this.setPolicySetting_( settingName, value, !!allowedMode, /*applyOnDestinationUpdate=*/ false); } break; } case 'pin': { const value = allowedMode ? allowedMode : defaultMode; if (value !== undefined) { this.setPolicySetting_( settingName, value, !!allowedMode, /*applyOnDestinationUpdate=*/ false); } break; } case 'printPdfAsImageAvailability': { const value = allowedMode !== undefined ? allowedMode : defaultMode; if (value !== undefined) { this.setPolicySetting_( settingName, value, /*managed=*/ false, /*applyOnDestinationUpdate=*/ false); } break; } case 'printPdfAsImage': { if (defaultMode !== undefined) { this.setPolicySetting_( settingName, defaultMode, /*managed=*/ false, /*applyOnDestinationUpdate=*/ false); } break; } default: break; } } /** * Sets settings in accordance to policies from native code, and prevents * those settings from being changed via other means. */ setPolicySettings(policies: Policies|undefined) { if (policies === undefined) { return; } const policiesObject = policies as {[key: string]: {defaultMode?: any, allowedMode?: any, value?: number}}; ['headerFooter', 'cssBackground', 'mediaSize'].forEach(settingName => { if (!policiesObject[settingName]) { return; } const defaultMode = policiesObject[settingName].defaultMode; const allowedMode = policiesObject[settingName].allowedMode; this.configurePolicySetting_(settingName, allowedMode, defaultMode); }); // <if expr="chromeos or lacros"> if (policiesObject['sheets']) { if (!this.policySettings_) { this.policySettings_ = {}; } this.policySettings_['sheets'] = { value: policiesObject['sheets'].value, applyOnDestinationUpdate: false, managed: true, }; } ['color', 'duplex', 'pin'].forEach(settingName => { if (!policiesObject[settingName]) { return; } const defaultMode = policiesObject[settingName].defaultMode; const allowedMode = policiesObject[settingName].allowedMode; this.configurePolicySetting_(settingName, allowedMode, defaultMode); }); // </if> // <if expr="is_win or is_macosx"> if (policies['printPdfAsImageAvailability']) { if (!this.policySettings_) { this.policySettings_ = {}; } const allowedMode = policies['printPdfAsImageAvailability'].allowedMode; this.configurePolicySetting_( 'printPdfAsImageAvailability', allowedMode, /*defaultMode=*/ false); } // </if> if (policies['printPdfAsImage']) { if (!this.policySettings_) { this.policySettings_ = {}; } const defaultMode = policies['printPdfAsImage'].defaultMode; this.configurePolicySetting_( 'printPdfAsImage', /*allowedMode=*/ undefined, defaultMode); } } applyStickySettings() { if (this.stickySettings_) { STICKY_SETTING_NAMES.forEach(settingName => { const setting = this.get(settingName, this.settings) as Setting; const value = (this.stickySettings_ as {[key: string]: any})[setting.key]; if (value !== undefined) { this.setSetting(settingName, value); } else { this.applyScalingStickySettings_(settingName); } }); } this.applyPersistentCddDefaults_(); this.applyPolicySettings_(); this.initialized_ = true; this.updateManaged_(); this.stickySettings_ = null; this.fire_('sticky-setting-changed', this.getStickySettings_()); } /** * Helper function for applyStickySettings(). Checks if the setting * is a scaling setting and applies by applying the old types * that rely on 'fitToPage' and 'customScaling'. * @param settingName Name of the setting being applied. */ private applyScalingStickySettings_(settingName: string) { // TODO(dhoss): Remove checks for 'customScaling' and 'fitToPage' if (settingName === 'scalingType' && 'customScaling' in this.stickySettings_!) { const isCustom = this.stickySettings_['customScaling']; const scalingType = isCustom ? ScalingType.CUSTOM : ScalingType.DEFAULT; this.setSetting(settingName, scalingType); } else if (settingName === 'scalingTypePdf') { if ('isFitToPageEnabled' in this.stickySettings_!) { const isFitToPage = this.stickySettings_['isFitToPageEnabled']; const scalingTypePdf = isFitToPage ? ScalingType.FIT_TO_PAGE : this.getSetting('scalingType').value; this.setSetting(settingName, scalingTypePdf); } else if (this.getSetting('scalingType').value === ScalingType.CUSTOM) { // In the event that 'isFitToPageEnabled' was not in the sticky // settings, and 'scalingType' has been set to custom, we want // 'scalingTypePdf' to match. this.setSetting(settingName, ScalingType.CUSTOM); } } } private applyPolicySettings_() { if (this.policySettings_) { for (const [settingName, policy] of Object.entries( this.policySettings_)) { const policyEntry = policy as PolicyEntry; // <if expr="chromeos or lacros"> if (settingName === 'sheets') { this.maxSheets = policyEntry.value; continue; } if (settingName === 'color') { this.set( 'settings.color.value', policyEntry.value === ColorModeRestriction.COLOR); this.set('settings.color.setByPolicy', policyEntry.managed); continue; } if (settingName === 'duplex') { let setDuplexTypeByPolicy = false; this.set( 'settings.duplex.value', policyEntry.value !== DuplexModeRestriction.SIMPLEX); if (policyEntry.value === DuplexModeRestriction.SHORT_EDGE) { this.set('settings.duplexShortEdge.value', true); setDuplexTypeByPolicy = true; } else if (policyEntry.value === DuplexModeRestriction.LONG_EDGE) { this.set('settings.duplexShortEdge.value', false); setDuplexTypeByPolicy = true; } this.set('settings.duplex.setByPolicy', policyEntry.managed); this.set( 'settings.duplexShortEdge.setByPolicy', policyEntry.managed && setDuplexTypeByPolicy); continue; } if (settingName === 'pin') { if (policyEntry.value === PinModeRestriction.NO_PIN && policyEntry.managed) { this.set('settings.pin.available', false); this.set('settings.pinValue.available', false); } else { this.set( 'settings.pin.value', policyEntry.value === PinModeRestriction.PIN); } this.set('settings.pin.setByPolicy', policyEntry.managed); continue; } // </if> // <if expr="is_win or is_macosx"> if (settingName === 'printPdfAsImageAvailability') { this.updateRasterizeAvailable_(); if (this.settings.rasterize.available) { // If rasterize is available then otherOptions must be available. this.setSettingPath_('otherOptions.available', true); } continue; } // </if> if (settingName === 'printPdfAsImage') { if (policyEntry.value) { this.setSetting('rasterize', policyEntry.value, true); } continue; } if (policyEntry.value !== undefined && !policyEntry.applyOnDestinationUpdate) { this.setSetting(settingName, policyEntry.value, true); if (policyEntry.managed) { this.set(`settings.${settingName}.setByPolicy`, true); } } } } } /** * If the setting has a default value specified in the CDD capabilities and * the attribute `reset_to_default` is true, this method will return the * default value for the setting; otherwise it will return null. */ private getResetValue_(capability: CapabilityWithReset): (object|null) { if (!capability.reset_to_default) { return null; } const cddDefault = capability.option.find(o => !!o.is_default); if (!cddDefault) { return null; } return cddDefault; } /** * For PrinterProvider printers, it's possible to specify for a setting to * always reset to the default value using the `reset_to_default` attribute. * If `reset_to_default` is true and a default value for the * setting is specified, this method will reset the setting * value to the default value. */ private applyPersistentCddDefaults_() { if (!this.destination || !this.destination.isExtension) { return; } const caps = this.destination && this.destination.capabilities ? this.destination.capabilities.printer : null; if (!caps) { return; } if (this.settings.mediaSize.available) { const cddDefault = this.getResetValue_(caps['media_size']!); if (cddDefault) { this.set('settings.mediaSize.value', cddDefault); } } if (this.settings.color.available) { const cddDefault = this.getResetValue_(caps['color']!) as ColorOption; if (cddDefault) { this.set( 'settings.color.value', !['STANDARD_MONOCHROME', 'CUSTOM_MONOCHROME'].includes( cddDefault.type!)); } } if (this.settings.duplex.available) { const cddDefault = this.getResetValue_(caps['duplex']!) as DuplexOption; if (cddDefault) { this.set( 'settings.duplex.value', cddDefault.type === DuplexType.LONG_EDGE || cddDefault.type === DuplexType.SHORT_EDGE); if (!this.settings.duplexShortEdge.available) { this.set( 'settings.duplexShortEdge.value', cddDefault.type === DuplexType.SHORT_EDGE); } } } if (this.settings.dpi.available) { const cddDefault = this.getResetValue_(caps['dpi']!); if (cddDefault) { this.set('settings.dpi.value', cddDefault); } } } /** * Restricts settings and applies defaults as defined by policy applicable to * current destination. */ applyDestinationSpecificPolicies() { if (this.settings.mediaSize.available && this.policySettings_) { const mediaSizePolicy = this.policySettings_['mediaSize'] && this.policySettings_['mediaSize'].value; if (mediaSizePolicy !== undefined) { const matchingOption = this.destination.capabilities!.printer.media_size!.option.find( o => { return o.width_microns === mediaSizePolicy.width && o.height_microns === mediaSizePolicy.height; }); if (matchingOption !== undefined) { this.set('settings.mediaSize.value', matchingOption); } } } this.updateManaged_(); } private updateManaged_() { let managedSettings = ['cssBackground', 'headerFooter']; // <if expr="chromeos or lacros"> managedSettings = managedSettings.concat(['color', 'duplex', 'duplexShortEdge', 'pin']); // </if> this.settingsManaged = managedSettings.some(settingName => { const setting = this.getSetting(settingName); return setting.available && setting.setByPolicy; }); } initialized(): boolean { return this.initialized_; } private getStickySettings_(): string { const serialization: {[key: string]: any} = {}; serialization['version'] = 2; STICKY_SETTING_NAMES.forEach(settingName => { const setting = this.get(settingName, this.settings); if (setting.setFromUi) { serialization[assert(setting.key)] = setting.value; } }); return JSON.stringify(serialization); } private getDuplexMode_(): DuplexMode { if (!this.getSettingValue('duplex')) { return DuplexMode.SIMPLEX; } return this.getSettingValue('duplexShortEdge') ? DuplexMode.SHORT_EDGE : DuplexMode.LONG_EDGE; } private getCddDuplexType_(): DuplexType { if (!this.getSettingValue('duplex')) { return DuplexType.NO_DUPLEX; } return this.getSettingValue('duplexShortEdge') ? DuplexType.SHORT_EDGE : DuplexType.LONG_EDGE; } /** * Creates a string that represents a print ticket. * @param destination Destination to print to. * @param openPdfInPreview Whether this print request is to open * the PDF in Preview app (Mac only). * @param showSystemDialog Whether this print request is to show * the system dialog. * @return Serialized print ticket. */ createPrintTicket( destination: Destination, openPdfInPreview: boolean, showSystemDialog: boolean): string { const dpi = this.getSettingValue('dpi') as DpiOption; const scalingSettingKey = this.getSetting('scalingTypePdf').available ? 'scalingTypePdf' : 'scalingType'; const ticket: PrintTicket = { mediaSize: this.getSettingValue('mediaSize') as MediaSizeValue, pageCount: this.getSettingValue('pages').length, landscape: this.getSettingValue('layout'), color: destination.getNativeColorModel( this.getSettingValue('color') as boolean), headerFooterEnabled: false, // only used in print preview marginsType: this.getSettingValue('margins'), duplex: this.getDuplexMode_(), copies: this.getSettingValue('copies'), collate: this.getSettingValue('collate'), shouldPrintBackgrounds: this.getSettingValue('cssBackground'), shouldPrintSelectionOnly: false, // only used in print preview previewModifiable: this.documentSettings.isModifiable, printToGoogleDrive: destination.id === GooglePromotedDestinationId.DOCS, printerType: getPrinterTypeForDestination(destination), rasterizePDF: this.getSettingValue('rasterize'), scaleFactor: this.getSettingValue(scalingSettingKey) === ScalingType.CUSTOM ? parseInt(this.getSettingValue('scaling'), 10) : 100, scalingType: this.getSettingValue(scalingSettingKey), pagesPerSheet: this.getSettingValue('pagesPerSheet'), dpiHorizontal: (dpi && 'horizontal_dpi' in dpi) ? dpi.horizontal_dpi : 0, dpiVertical: (dpi && 'vertical_dpi' in dpi) ? dpi.vertical_dpi : 0, dpiDefault: (dpi && 'is_default' in dpi) ? dpi.is_default! : false, deviceName: destination.id, pageWidth: this.pageSize.width, pageHeight: this.pageSize.height, showSystemDialog: showSystemDialog, }; // <if expr="chromeos or lacros"> ticket['printToGoogleDrive'] = ticket['printToGoogleDrive'] || destination.id === GooglePromotedDestinationId.SAVE_TO_DRIVE_CROS; // </if> // Set 'cloudPrintID' only if the destination is not local. if (!destination.isLocal) { ticket['cloudPrintID'] = destination.id; } if (openPdfInPreview) { ticket['openPDFInPreview'] = openPdfInPreview; } if (this.getSettingValue('margins') === MarginsType.CUSTOM) { ticket['marginsCustom'] = this.getSettingValue('customMargins'); } if (destination.isExtension) { // TODO(rbpotter): Get local and PDF printers to use the same ticket and // send only this ticket instead of nesting it in a larger ticket. ticket['ticket'] = this.createCloudJobTicket(destination); ticket['capabilities'] = JSON.stringify(destination.capabilities); } // <if expr="chromeos or lacros"> if (this.getSettingValue('pin')) { ticket['pinValue'] = this.getSettingValue('pinValue'); } if (destination.origin === DestinationOrigin.CROS) { ticket['advancedSettings'] = this.getSettingValue('vendorItems'); } // </if> return JSON.stringify(ticket); } /** * Creates an object that represents a Google Cloud Print print ticket. * @param destination Destination to print to. * @return Google Cloud Print print ticket. */ createCloudJobTicket(destination: Destination): string { assert( !destination.isLocal || destination.isExtension, 'Trying to create a Google Cloud Print print ticket for a local ' + ' non-extension destination'); assert( destination.capabilities, 'Trying to create a Google Cloud Print print ticket for a ' + 'destination with no print capabilities'); // Create CJT (Cloud Job Ticket) const cjt: CloudJobTicket = {version: '1.0', print: {}}; if (this.settings.collate.available) { cjt.print.collate = {collate: this.settings.collate.value}; } if (this.settings.color.available) { const selectedOption = destination.getSelectedColorOption( this.settings.color.value as boolean); if (!selectedOption) { console.warn('Could not find correct color option'); } else { cjt.print.color = {type: selectedOption.type}; if (selectedOption.hasOwnProperty('vendor_id')) { cjt.print.color!.vendor_id = selectedOption.vendor_id; } } } else { // Always try setting the color in the print ticket, otherwise a // reasonable reader of the ticket will have to do more work, or process // the ticket sub-optimally, in order to safely handle the lack of a // color ticket item. const defaultOption = destination.defaultColorOption; if (defaultOption) { cjt.print.color = {type: defaultOption.type}; if (defaultOption.hasOwnProperty('vendor_id')) { cjt.print.color!.vendor_id = defaultOption.vendor_id; } } } if (this.settings.copies.available) { cjt.print.copies = {copies: this.getSettingValue('copies')}; } if (this.settings.duplex.available) { cjt.print.duplex = { type: this.getCddDuplexType_(), }; } if (this.settings.mediaSize.available) { const mediaValue = this.settings.mediaSize.value; cjt.print.media_size = { width_microns: mediaValue.width_microns, height_microns: mediaValue.height_microns, is_continuous_feed: mediaValue.is_continuous_feed, vendor_id: mediaValue.vendor_id }; } if (!this.settings.layout.available) { // In this case "orientation" option is hidden from user, so user can't // adjust it for page content, see Landscape.isCapabilityAvailable(). // We can improve results if we set AUTO here. const capability = destination.capabilities!.printer ? destination.capabilities!.printer.page_orientation : null; if (capability && capability.option && capability.option.some(option => option.type === 'AUTO')) { cjt.print.page_orientation = {type: 'AUTO'}; } } else { cjt.print.page_orientation = { type: this.settings.layout.value ? 'LANDSCAPE' : 'PORTRAIT' }; } if (this.settings.dpi.available) { const dpiValue = this.settings.dpi.value; cjt.print.dpi = { horizontal_dpi: dpiValue.horizontal_dpi, vertical_dpi: dpiValue.vertical_dpi, vendor_id: dpiValue.vendor_id }; } if (this.settings.vendorItems.available) { const items = this.settings.vendorItems.value; cjt.print.vendor_ticket_item = []; for (const itemId in items) { if (items.hasOwnProperty(itemId)) { cjt.print.vendor_ticket_item.push({id: itemId, value: items[itemId]}); } } } return JSON.stringify(cjt); } } customElements.define(PrintPreviewModelElement.is, PrintPreviewModelElement);
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { PrivateLinkResources } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { DesktopVirtualizationAPIClient } from "../desktopVirtualizationAPIClient"; import { PrivateLinkResource, PrivateLinkResourcesListByHostPoolNextOptionalParams, PrivateLinkResourcesListByHostPoolOptionalParams, PrivateLinkResourcesListByWorkspaceNextOptionalParams, PrivateLinkResourcesListByWorkspaceOptionalParams, PrivateLinkResourcesListByHostPoolResponse, PrivateLinkResourcesListByWorkspaceResponse, PrivateLinkResourcesListByHostPoolNextResponse, PrivateLinkResourcesListByWorkspaceNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing PrivateLinkResources operations. */ export class PrivateLinkResourcesImpl implements PrivateLinkResources { private readonly client: DesktopVirtualizationAPIClient; /** * Initialize a new instance of the class PrivateLinkResources class. * @param client Reference to the service client */ constructor(client: DesktopVirtualizationAPIClient) { this.client = client; } /** * List the private link resources available for this hostpool. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param hostPoolName The name of the host pool within the specified resource group * @param options The options parameters. */ public listByHostPool( resourceGroupName: string, hostPoolName: string, options?: PrivateLinkResourcesListByHostPoolOptionalParams ): PagedAsyncIterableIterator<PrivateLinkResource> { const iter = this.listByHostPoolPagingAll( resourceGroupName, hostPoolName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByHostPoolPagingPage( resourceGroupName, hostPoolName, options ); } }; } private async *listByHostPoolPagingPage( resourceGroupName: string, hostPoolName: string, options?: PrivateLinkResourcesListByHostPoolOptionalParams ): AsyncIterableIterator<PrivateLinkResource[]> { let result = await this._listByHostPool( resourceGroupName, hostPoolName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByHostPoolNext( resourceGroupName, hostPoolName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByHostPoolPagingAll( resourceGroupName: string, hostPoolName: string, options?: PrivateLinkResourcesListByHostPoolOptionalParams ): AsyncIterableIterator<PrivateLinkResource> { for await (const page of this.listByHostPoolPagingPage( resourceGroupName, hostPoolName, options )) { yield* page; } } /** * List the private link resources available for this workspace. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace * @param options The options parameters. */ public listByWorkspace( resourceGroupName: string, workspaceName: string, options?: PrivateLinkResourcesListByWorkspaceOptionalParams ): PagedAsyncIterableIterator<PrivateLinkResource> { const iter = this.listByWorkspacePagingAll( resourceGroupName, workspaceName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByWorkspacePagingPage( resourceGroupName, workspaceName, options ); } }; } private async *listByWorkspacePagingPage( resourceGroupName: string, workspaceName: string, options?: PrivateLinkResourcesListByWorkspaceOptionalParams ): AsyncIterableIterator<PrivateLinkResource[]> { let result = await this._listByWorkspace( resourceGroupName, workspaceName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByWorkspaceNext( resourceGroupName, workspaceName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByWorkspacePagingAll( resourceGroupName: string, workspaceName: string, options?: PrivateLinkResourcesListByWorkspaceOptionalParams ): AsyncIterableIterator<PrivateLinkResource> { for await (const page of this.listByWorkspacePagingPage( resourceGroupName, workspaceName, options )) { yield* page; } } /** * List the private link resources available for this hostpool. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param hostPoolName The name of the host pool within the specified resource group * @param options The options parameters. */ private _listByHostPool( resourceGroupName: string, hostPoolName: string, options?: PrivateLinkResourcesListByHostPoolOptionalParams ): Promise<PrivateLinkResourcesListByHostPoolResponse> { return this.client.sendOperationRequest( { resourceGroupName, hostPoolName, options }, listByHostPoolOperationSpec ); } /** * List the private link resources available for this workspace. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace * @param options The options parameters. */ private _listByWorkspace( resourceGroupName: string, workspaceName: string, options?: PrivateLinkResourcesListByWorkspaceOptionalParams ): Promise<PrivateLinkResourcesListByWorkspaceResponse> { return this.client.sendOperationRequest( { resourceGroupName, workspaceName, options }, listByWorkspaceOperationSpec ); } /** * ListByHostPoolNext * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param hostPoolName The name of the host pool within the specified resource group * @param nextLink The nextLink from the previous successful call to the ListByHostPool method. * @param options The options parameters. */ private _listByHostPoolNext( resourceGroupName: string, hostPoolName: string, nextLink: string, options?: PrivateLinkResourcesListByHostPoolNextOptionalParams ): Promise<PrivateLinkResourcesListByHostPoolNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, hostPoolName, nextLink, options }, listByHostPoolNextOperationSpec ); } /** * ListByWorkspaceNext * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace * @param nextLink The nextLink from the previous successful call to the ListByWorkspace method. * @param options The options parameters. */ private _listByWorkspaceNext( resourceGroupName: string, workspaceName: string, nextLink: string, options?: PrivateLinkResourcesListByWorkspaceNextOptionalParams ): Promise<PrivateLinkResourcesListByWorkspaceNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, workspaceName, nextLink, options }, listByWorkspaceNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listByHostPoolOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/hostPools/{hostPoolName}/privateLinkResources", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PrivateLinkResourceListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.hostPoolName ], headerParameters: [Parameters.accept], serializer }; const listByWorkspaceOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/workspaces/{workspaceName}/privateLinkResources", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PrivateLinkResourceListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.workspaceName ], headerParameters: [Parameters.accept], serializer }; const listByHostPoolNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PrivateLinkResourceListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.hostPoolName ], headerParameters: [Parameters.accept], serializer }; const listByWorkspaceNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PrivateLinkResourceListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.workspaceName ], headerParameters: [Parameters.accept], serializer };
the_stack
import {Item} from "./Item"; import CustomError from "./Error"; import utils from "./utils"; const OR = Symbol("OR"); import * as DynamoDB from "@aws-sdk/client-dynamodb"; import {ObjectType} from "./General"; import {ExpressionAttributeNameMap, ExpressionAttributeValueMap} from "./Types"; import Internal from "./Internal"; import {Model} from "./Model"; import {InternalPropertiesClass} from "./InternalPropertiesClass"; const {internalProperties} = Internal.General; const isRawConditionObject = (object): boolean => Object.keys(object).length === 3 && ["ExpressionAttributeValues", "ExpressionAttributeNames"].every((item) => Boolean(object[item]) && typeof object[item] === "object"); export type ConditionFunction = (condition: Condition) => Condition; // TODO: There is a problem where you can have multiple keys in one `ConditionStorageType`, which will cause problems. We need to fix that. Likely be refactoring it so that the key is part of `ConditionsConditionStorageObject`. type ConditionStorageType = {[key: string]: ConditionsConditionStorageObject} | typeof OR; export type ConditionStorageTypeNested = ConditionStorageType | Array<ConditionStorageTypeNested>; type ConditionStorageSettingsConditions = ConditionStorageTypeNested[]; // TODO: the return value of the function below is incorrect. We need to add a property to the object that is a required string, where the property/key name is always equal to `settings.conditionString` type ConditionRequestObjectResult = {ExpressionAttributeNames?: ExpressionAttributeNameMap; ExpressionAttributeValues?: ExpressionAttributeValueMap}; interface ConditionComparisonType { name: ConditionComparisonComparatorName; typeName: ConditionComparisonComparatorDynamoName; not?: ConditionComparisonComparatorDynamoName; multipleArguments?: boolean; } enum ConditionComparisonComparatorName { equals = "eq", notEquals = "ne", lessThan = "lt", lessThanEquals = "le", greaterThan = "gt", greaterThanEquals = "ge", beginsWith = "beginsWith", contains = "contains", exists = "exists", in = "in", between = "between" } enum ConditionComparisonComparatorDynamoName { equals = "EQ", notEquals = "NE", lessThan = "LT", lessThanEquals = "LE", greaterThan = "GT", greaterThanEquals = "GE", beginsWith = "BEGINS_WITH", contains = "CONTAINS", notContains = "NOT_CONTAINS", exists = "EXISTS", notExists = "NOT_EXISTS", in = "IN", between = "BETWEEN" } const types: ConditionComparisonType[] = [ {"name": ConditionComparisonComparatorName.equals, "typeName": ConditionComparisonComparatorDynamoName.equals, "not": ConditionComparisonComparatorDynamoName.notEquals}, {"name": ConditionComparisonComparatorName.notEquals, "typeName": ConditionComparisonComparatorDynamoName.notEquals, "not": ConditionComparisonComparatorDynamoName.equals}, {"name": ConditionComparisonComparatorName.lessThan, "typeName": ConditionComparisonComparatorDynamoName.lessThan, "not": ConditionComparisonComparatorDynamoName.greaterThanEquals}, {"name": ConditionComparisonComparatorName.lessThanEquals, "typeName": ConditionComparisonComparatorDynamoName.lessThanEquals, "not": ConditionComparisonComparatorDynamoName.greaterThan}, {"name": ConditionComparisonComparatorName.greaterThan, "typeName": ConditionComparisonComparatorDynamoName.greaterThan, "not": ConditionComparisonComparatorDynamoName.lessThanEquals}, {"name": ConditionComparisonComparatorName.greaterThanEquals, "typeName": ConditionComparisonComparatorDynamoName.greaterThanEquals, "not": ConditionComparisonComparatorDynamoName.lessThan}, {"name": ConditionComparisonComparatorName.beginsWith, "typeName": ConditionComparisonComparatorDynamoName.beginsWith}, {"name": ConditionComparisonComparatorName.contains, "typeName": ConditionComparisonComparatorDynamoName.contains, "not": ConditionComparisonComparatorDynamoName.notContains}, {"name": ConditionComparisonComparatorName.exists, "typeName": ConditionComparisonComparatorDynamoName.exists, "not": ConditionComparisonComparatorDynamoName.notExists}, {"name": ConditionComparisonComparatorName.in, "typeName": ConditionComparisonComparatorDynamoName.in}, {"name": ConditionComparisonComparatorName.between, "typeName": ConditionComparisonComparatorDynamoName.between, "multipleArguments": true} ]; export type ConditionInitializer = Condition | ObjectType | string; export interface BasicOperators<T = Condition> { and: () => T; or: () => T; not: () => T; parenthesis: (value: Condition | ConditionFunction) => T; group: (value: Condition | ConditionFunction) => T; where: (key: string) => T; filter: (key: string) => T; attribute: (key: string) => T; eq: (value: any) => T; lt: (value: any) => T; le: (value: any) => T; gt: (value: any) => T; ge: (value: any) => T; beginsWith: (value: any) => T; contains: (value: any) => T; exists: () => T; in: (value: any) => T; between: (...values: any[]) => T; } export interface Condition extends BasicOperators { where: (key: string) => Condition; filter: (key: string) => Condition; attribute: (key: string) => Condition; eq: (value: any) => Condition; lt: (value: any) => Condition; le: (value: any) => Condition; gt: (value: any) => Condition; ge: (value: any) => Condition; beginsWith: (value: any) => Condition; contains: (value: any) => Condition; exists: () => Condition; in: (value: any) => Condition; between: (...values: any[]) => Condition; } type ConditionObject = { [key: string]: { type: ConditionComparisonComparatorDynamoName; value: any; } } | typeof OR; interface ConditionInternalProperties { requestObject: (model: Model<Item>, settings?: ConditionRequestObjectSettings) => Promise<ConditionRequestObjectResult>; settings?: { conditions?: ConditionObject[]; pending?: { key?: string; not?: boolean; type?: ConditionComparisonType; value?: any; }; // represents the pending chain of filter data waiting to be attached to the `conditions` parameter. For example, storing the key before we know what the comparison operator is. raw?: ConditionInitializer; } } export class Condition extends InternalPropertiesClass<ConditionInternalProperties> { /** * TODO * @param object * @returns Condition */ constructor (object?: ConditionInitializer) { super(); this.setInternalProperties(internalProperties, { "requestObject": async (model: Model<Item>, settings: ConditionRequestObjectSettings = {"conditionString": "ConditionExpression", "conditionStringType": "string"}): Promise<ConditionRequestObjectResult> => { const toDynamo = async (key: string, value: ObjectType): Promise<DynamoDB.AttributeValue> => { const newValue = (await Item.objectFromSchema({[key]: value}, model, {"type": "toDynamo", "modifiers": ["set"], "typeCheck": false}))[key]; return Item.objectToDynamo(newValue, {"type": "value"}); }; if (this.getInternalProperties(internalProperties).settings.raw && utils.object.equals(Object.keys(this.getInternalProperties(internalProperties).settings.raw).sort(), [settings.conditionString, "ExpressionAttributeValues", "ExpressionAttributeNames"].sort())) { return utils.async_reduce(Object.entries((this.getInternalProperties(internalProperties).settings.raw as ObjectType).ExpressionAttributeValues), async (obj, entry) => { const [key, value] = entry; // TODO: we should fix this so that we can do `isDynamoItem(value)` if (!Item.isDynamoObject({"key": value})) { obj.ExpressionAttributeValues[key] = await toDynamo(key, value); } return obj; }, this.getInternalProperties(internalProperties).settings.raw as ObjectType); } else if (this.getInternalProperties(internalProperties).settings.conditions.length === 0) { return {}; } let index = (settings.index || {}).start || 0; const setIndex = (i: number): void => { index = i; (settings.index || {"set": utils.empty_function}).set(i); }; async function main (input: ConditionStorageSettingsConditions): Promise<ConditionRequestObjectResult> { return utils.async_reduce(input, async (object: ConditionRequestObjectResult, entry: ConditionStorageTypeNested, i: number, arr: any[]) => { let expression = ""; if (Array.isArray(entry)) { const result = await main(entry); const newData = utils.merge_objects.main({"combineMethod": "object_combine"})({...result}, {...object}); const returnObject = utils.object.pick(newData, ["ExpressionAttributeNames", "ExpressionAttributeValues"]); expression = settings.conditionStringType === "array" ? result[settings.conditionString] : `(${result[settings.conditionString]})`; object = {...object, ...returnObject}; } else if (entry !== OR) { const [key, condition] = Object.entries(entry)[0]; const {value} = condition; const keys = {"name": `#a${index}`, "value": `:v${index}`}; setIndex(++index); const keyParts = key.split("."); if (keyParts.length === 1) { object.ExpressionAttributeNames[keys.name] = key; } else { keys.name = keyParts.reduce((finalName, part, index) => { const name = `${keys.name}_${index}`; object.ExpressionAttributeNames[name] = part; finalName.push(name); return finalName; }, []).join("."); } object.ExpressionAttributeValues[keys.value] = await toDynamo(key, value); switch (condition.type) { case "EQ": case "NE": expression = `${keys.name} ${condition.type === "EQ" ? "=" : "<>"} ${keys.value}`; break; case "IN": delete object.ExpressionAttributeValues[keys.value]; expression = `${keys.name} IN (${value.map((_v: any, i: number) => `${keys.value}_${i + 1}`).join(", ")})`; await Promise.all(value.map(async (valueItem: any, i: number) => { object.ExpressionAttributeValues[`${keys.value}_${i + 1}`] = await toDynamo(key, valueItem); })); break; case "GT": case "GE": case "LT": case "LE": expression = `${keys.name} ${condition.type.startsWith("G") ? ">" : "<"}${condition.type.endsWith("E") ? "=" : ""} ${keys.value}`; break; case "BETWEEN": expression = `${keys.name} BETWEEN ${keys.value}_1 AND ${keys.value}_2`; object.ExpressionAttributeValues[`${keys.value}_1`] = await toDynamo(key, value[0]); object.ExpressionAttributeValues[`${keys.value}_2`] = await toDynamo(key, value[1]); delete object.ExpressionAttributeValues[keys.value]; break; case "CONTAINS": case "NOT_CONTAINS": expression = `${condition.type === "NOT_CONTAINS" ? "NOT " : ""}contains (${keys.name}, ${keys.value})`; break; case "EXISTS": case "NOT_EXISTS": expression = `attribute_${condition.type === "NOT_EXISTS" ? "not_" : ""}exists (${keys.name})`; delete object.ExpressionAttributeValues[keys.value]; break; case "BEGINS_WITH": expression = `begins_with (${keys.name}, ${keys.value})`; break; } } else { return object; } const conditionStringNewItems: string[] = [expression]; if (object[settings.conditionString].length > 0) { conditionStringNewItems.unshift(` ${arr[i - 1] === OR ? "OR" : "AND"} `); } conditionStringNewItems.forEach((item) => { if (typeof object[settings.conditionString] === "string") { object[settings.conditionString] = `${object[settings.conditionString]}${item}`; } else { object[settings.conditionString].push(Array.isArray(item) ? item : item.trim()); } }); return object; }, {[settings.conditionString]: settings.conditionStringType === "array" ? [] : "", "ExpressionAttributeNames": {}, "ExpressionAttributeValues": {}}); } return utils.object.clearEmpties(await main(this.getInternalProperties(internalProperties).settings.conditions)); } }); if (object instanceof Condition) { this.setInternalProperties(internalProperties, { ...this.getInternalProperties(internalProperties), "settings": {...object.getInternalProperties(internalProperties).settings} }); } else { this.setInternalProperties(internalProperties, { ...this.getInternalProperties(internalProperties), "settings": { "conditions": [], "pending": {} // represents the pending chain of filter data waiting to be attached to the `conditions` parameter. For example, storing the key before we know what the comparison operator is. } }); if (typeof object === "object") { if (!isRawConditionObject(object)) { Object.keys(object).forEach((key) => { const value = object[key]; const valueType = typeof value === "object" && Object.keys(value).length > 0 ? Object.keys(value)[0] : "eq"; const comparisonType = types.find((item) => item.name === valueType); if (!comparisonType) { throw new CustomError.InvalidFilterComparison(`The type: ${valueType} is invalid.`); } this.getInternalProperties(internalProperties).settings.conditions.push({ [key]: { "type": comparisonType.typeName, "value": typeof value[valueType] !== "undefined" && value[valueType] !== null ? value[valueType] : value } }); }); } } else if (object) { const internalPropertiesObject = this.getInternalProperties(internalProperties); internalPropertiesObject.settings.pending.key = object; this.setInternalProperties(internalProperties, internalPropertiesObject); } const internalPropertiesObject = this.getInternalProperties(internalProperties); internalPropertiesObject.settings.raw = object; this.setInternalProperties(internalProperties, internalPropertiesObject); } return this; } /** * This function specifies an `OR` join between two conditions, as opposed to the default `AND`. The condition will return `true` if either condition is met. * * ```js * new dynamoose.Condition().where("id").eq(1).or().where("name").eq("Bob"); // id = 1 OR name = Bob * ``` * @returns Condition */ or (): Condition { this.getInternalProperties(internalProperties).settings.conditions.push(OR); return this; } /** * This function has no behavior and is only used to increase readability of your conditional. This function can be omitted with no behavior change to your code. * * ```js * // The two condition objects below are identical * new dynamoose.Condition().where("id").eq(1).and().where("name").eq("Bob"); * new dynamoose.Condition().where("id").eq(1).where("name").eq("Bob"); * ``` * @returns Condition */ and (): Condition { return this; } /** * This function sets the condition to use the opposite comparison type for the given condition. You can find the list opposite comparison types below. * * | Original | Opposite | * |---|---| * | equals (EQ) | not equals (NE) | * | less than or equals (LE) | greater than (GT) | * | less than (LT) | greater than or equals (GE) | * | null (NULL) | not null (NOT_NULL) | * | contains (CONTAINS) | not contains (NOT_CONTAINS) | * | exists (EXISTS) | not exists (NOT_EXISTS) | * * The following comparisons do not have an opposite comparison type, and will throw an error if you try to use condition.not() with them. * * | Original | * |---| * | in (IN) | * | between (BETWEEN) | * | begins with (BEGINS_WITH) | * * ```js * new dynamoose.Condition().where("id").not().eq(1); // Retrieve all objects where id does NOT equal 1 * new dynamoose.Condition().where("id").not().between(1, 2); // Will throw error since between does not have an opposite comparison type * ``` * @returns Condition */ not (): Condition { this.getInternalProperties(internalProperties).settings.pending.not = !this.getInternalProperties(internalProperties).settings.pending.not; return this; } /** * This function takes in a `Condition` instance as a parameter and uses that as a group. This lets you specify the priority of the conditional. You can also pass a function into the `condition` parameter and Dynamoose will call your function with one argument which is a condition instance that you can return to specify the group. * * ```js * // The two condition objects below are identical * new dynamoose.Condition().where("id").eq(1).and().parenthesis(new dynamoose.Condition().where("name").eq("Bob")); // id = 1 AND (name = Bob) * new dynamoose.Condition().where("id").eq(1).and().parenthesis((condition) => condition.where("name").eq("Bob")); // id = 1 AND (name = Bob) * ``` * * `condition.group` is an alias to this method. * @param condition A new Condition instance or a function. If a function is passed, it will be called with one argument which is a condition instance that you can return to specify the group. * @returns Condition */ parenthesis (condition: Condition | ConditionFunction): Condition { condition = typeof condition === "function" ? condition(new Condition()) : condition; const conditions = condition.getInternalProperties(internalProperties).settings.conditions; this.getInternalProperties(internalProperties).settings.conditions.push(conditions as any); return this; } /** * This function takes in a `Condition` instance as a parameter and uses that as a group. This lets you specify the priority of the conditional. You can also pass a function into the `condition` parameter and Dynamoose will call your function with one argument which is a condition instance that you can return to specify the group. * * ```js * // The two condition objects below are identical * new dynamoose.Condition().where("id").eq(1).and().group(new dynamoose.Condition().where("name").eq("Bob")); // id = 1 AND (name = Bob) * new dynamoose.Condition().where("id").eq(1).and().group((condition) => condition.where("name").eq("Bob")); // id = 1 AND (name = Bob) * ``` * * `condition.parenthesis` is an alias to this method. * @param condition A new Condition instance or a function. If a function is passed, it will be called with one argument which is a condition instance that you can return to specify the group. * @returns Condition */ group (condition: Condition | ConditionFunction): Condition { return this.parenthesis(condition); } } interface ConditionsConditionStorageObject { type: ConditionComparisonComparatorDynamoName; value: any; } function finalizePending (instance: Condition): void { const pending = instance.getInternalProperties(internalProperties).settings.pending; let dynamoNameType: ConditionComparisonComparatorDynamoName; if (pending.not === true) { if (!pending.type.not) { throw new CustomError.InvalidFilterComparison(`${pending.type.typeName} can not follow not()`); } dynamoNameType = pending.type.not; } else { dynamoNameType = pending.type.typeName; } instance.getInternalProperties(internalProperties).settings.conditions.push({ [pending.key]: { "type": dynamoNameType, "value": pending.value } }); instance.getInternalProperties(internalProperties).settings.pending = {}; } Condition.prototype.where = Condition.prototype.filter = Condition.prototype.attribute = function (this: Condition, key: string): Condition { this.getInternalProperties(internalProperties).settings.pending = {key}; return this; }; // TODO: I don't think this prototypes are being exposed which is gonna cause a lot of problems with our type definition file. Need to figure out a better way to do this since they aren't defined and are dynamic. types.forEach((type) => { Condition.prototype[type.name] = function (this: Condition, ...args: any[]): Condition { if (args.includes(undefined)) { console.warn(`Dynamoose Warning: Passing \`undefined\` into a condition ${type.name} is not supported and can lead to behavior where DynamoDB returns an error related to your conditional. In a future version of Dynamoose this behavior will throw an error. If you believe your conditional is valid and you received this message in error, please submit an issue at https://github.com/dynamoose/dynamoose/issues/new/choose.`); // eslint-disable-line no-console } this.getInternalProperties(internalProperties).settings.pending.value = type.multipleArguments ? args : args[0]; this.getInternalProperties(internalProperties).settings.pending.type = type; finalizePending(this); return this; }; }); interface ConditionRequestObjectSettings { conditionString: string; index?: { start: number; set: (newIndex: number) => void; }; conditionStringType: "array" | "string"; }
the_stack
import { Card, Classes, Dialog, H1, InputGroup } from '@blueprintjs/core'; import { IconNames } from '@blueprintjs/icons'; import * as React from 'react'; import Recorder from 'yareco'; import controlButton from '../../../../commons/ControlButton'; import { Input, PlaybackData, RecordingStatus } from '../../../../features/sourceRecorder/SourceRecorderTypes'; type SourcereelControlbarProps = DispatchProps & StateProps; type DispatchProps = { handleRecordInit: () => void; handleRecordPause: () => void; handleResetInputs: (inputs: Input[]) => void; handleSaveSourcecastData: ( title: string, description: string, uid: string, audio: Blob, playbackData: PlaybackData ) => void; handleSetSourcecastData: ( title: string, description: string, uid: string, audioUrl: string, playbackData: PlaybackData ) => void; handleSetEditorReadonly: (readonly: boolean) => void; handleTimerPause: () => void; handleTimerReset: () => void; handleTimerResume: (timeBefore: number) => void; handleTimerStart: () => void; handleTimerStop: () => void; getTimerDuration: () => number; }; type StateProps = { currentPlayerTime: number; editorValue: string; playbackData: PlaybackData; recordingStatus: RecordingStatus; }; type State = { dialogOpen: boolean; duration: number; fileDataBlob?: Blob; updater?: NodeJS.Timeout; saveTitle: string; saveDescription: string; saveUID: string; }; class SourcereelControlbar extends React.PureComponent<SourcereelControlbarProps, State> { private recorder?: Recorder = undefined; constructor(props: SourcereelControlbarProps) { super(props); this.state = { dialogOpen: false, duration: 0, updater: undefined, saveTitle: '', saveDescription: '', saveUID: '' }; } public async componentDidMount() { Recorder.getPermission().then( () => {}, (error: any) => { alert('Microphone not found: ' + error); } ); } public render() { const RecorderRecordPauseButton = controlButton( 'Record Pause', IconNames.SNOWFLAKE, this.props.handleRecordPause ); const RecorderPauseButton = controlButton('Pause', IconNames.PAUSE, this.handleRecorderPausing); const RecorderResumeButton = controlButton( 'Resume', IconNames.PLAY, this.handleRecorderResuming ); const RecorderResumeFromCurrentButton = controlButton( 'Resume Here', IconNames.PLAY, this.handleRecorderResumingFromCurrent ); const RecorderStartButton = controlButton( 'Record', IconNames.PLAY, this.handleRecorderStarting ); const RecorderStopButton = controlButton('Stop', IconNames.STOP, this.handleRecorderStopping); const RecorderResetButton = controlButton( 'Reset', IconNames.REFRESH, this.handleRecorderResetting ); const RecorderSaveButton = controlButton( 'Upload', IconNames.FLOPPY_DISK, this.handleOpenDialog ); return ( <div> <Dialog icon="info-sign" isOpen={this.state.dialogOpen} onClose={this.handleCloseDialog} title="Upload Sourcecast" canOutsideClickClose={true} > <div className={Classes.DIALOG_BODY}> <InputGroup id="title" leftIcon={IconNames.HEADER} onChange={this.handleSaveTitleInputChange} placeholder="Title" value={this.state.saveTitle} /> <br /> <InputGroup id="description" leftIcon={IconNames.LIST_DETAIL_VIEW} onChange={this.handleSaveDescriptionInputChange} placeholder="Description" value={this.state.saveDescription} /> <br /> <InputGroup id="uid" leftIcon={IconNames.KEY} onChange={this.handleSaveUIDInputChange} placeholder="UID (optional, only alphanumeric, dash and underscore allowed)" value={this.state.saveUID} /> </div> <div className={Classes.DIALOG_FOOTER}> <div className={Classes.DIALOG_FOOTER_ACTIONS}> {controlButton('Confirm Upload', IconNames.TICK, this.handleRecorderSaving)} {controlButton('Cancel', IconNames.CROSS, this.handleCloseDialog)} </div> </div> </Dialog> <br /> <div className="Timer"> <Card elevation={2} style={{ background: '#24323F' }}> <H1> {this.renderLabel( this.props.recordingStatus !== RecordingStatus.paused ? this.state.duration / 1000 : this.props.currentPlayerTime )} </H1> </Card> </div> <br /> <div className="RecorderControl"> {this.props.recordingStatus === RecordingStatus.notStarted && RecorderStartButton} {this.props.recordingStatus === RecordingStatus.paused && RecorderResumeButton} {this.props.recordingStatus === RecordingStatus.paused && RecorderResumeFromCurrentButton} {this.props.recordingStatus === RecordingStatus.recording && RecorderPauseButton} {this.props.recordingStatus === RecordingStatus.recording && RecorderRecordPauseButton} {this.props.recordingStatus === RecordingStatus.paused && RecorderStopButton} {this.props.recordingStatus === RecordingStatus.finished && RecorderSaveButton} {this.props.recordingStatus !== RecordingStatus.notStarted && RecorderResetButton} </div> <br /> </div> ); } private handleCloseDialog = () => this.setState({ dialogOpen: false }); private handleOpenDialog = () => this.setState({ dialogOpen: true }); private updateTimerDuration = () => { this.setState({ duration: this.props.getTimerDuration() }); }; private handleTruncatePlaybackData = () => { const truncatedInputs = this.props.playbackData.inputs.filter( deltaWithTime => deltaWithTime.time <= this.props.currentPlayerTime * 1000 ); this.props.handleResetInputs(truncatedInputs); }; private handleRecorderPausing = () => { if (!this.recorder) { return; } const { handleSetEditorReadonly, handleSetSourcecastData, handleTimerPause } = this.props; clearInterval(this.state.updater!); handleSetEditorReadonly(true); handleTimerPause(); this.recorder.pause(); const audioUrl = window.URL.createObjectURL(this.recorder.exportWAV()); handleSetSourcecastData('', '', '', audioUrl, this.props.playbackData); }; private handleRecorderStarting = () => { this.recorder = new Recorder(); const { handleRecordInit, handleSetEditorReadonly, handleTimerStart } = this.props; this.recorder.start().then( () => { handleRecordInit(); handleSetEditorReadonly(false); handleTimerStart(); const updater = setInterval(this.updateTimerDuration, 100); this.setState({ updater }); // this.recorder.onRecord = (duration: number) => console.log(duration); }, (error: any) => { alert('Microphone not found: ' + error); } ); }; private handleRecorderResuming = () => { if (!this.recorder) { return; } const { handleSetEditorReadonly, handleTimerResume } = this.props; handleSetEditorReadonly(false); // -1 means resume from the end handleTimerResume(-1); const updater = setInterval(this.updateTimerDuration, 100); this.setState({ updater }); this.recorder.resume(); }; private handleRecorderResumingFromCurrent = () => { if (!this.recorder) { return; } const { currentPlayerTime, handleSetEditorReadonly, handleTimerResume } = this.props; this.handleTruncatePlaybackData(); handleSetEditorReadonly(false); handleTimerResume(currentPlayerTime * 1000); const updater = setInterval(this.updateTimerDuration, 100); this.setState({ updater }); this.recorder.resume(currentPlayerTime); }; private handleRecorderStopping = () => { if (!this.recorder) { return; } const { handleSetEditorReadonly, handleTimerStop } = this.props; handleSetEditorReadonly(false); handleTimerStop(); clearInterval(this.state.updater!); this.recorder.stop(); this.setState({ fileDataBlob: this.recorder.exportWAV() }); this.recorder.clear(); }; private handleRecorderResetting = () => { const { handleSetEditorReadonly, handleTimerReset } = this.props; handleSetEditorReadonly(false); handleTimerReset(); clearInterval(this.state.updater!); this.setState({ duration: 0 }); if (this.recorder) { this.recorder.stop(); this.recorder.clear(); } }; private handleRecorderSaving = () => { if (!this.state.fileDataBlob) { alert('No recording found'); return; } this.props.handleSaveSourcecastData( this.state.saveTitle, this.state.saveDescription, this.state.saveUID, this.state.fileDataBlob, this.props.playbackData ); }; private renderLabel = (value: number) => { const min = Math.floor(value / 60); const sec = Math.floor(value - min * 60); const minString = min < 10 ? '0' + min : min; const secString = sec < 10 ? '0' + sec : sec; return minString + ':' + secString; }; private handleSaveTitleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => { this.setState({ saveTitle: event.target.value }); }; private handleSaveDescriptionInputChange = (event: React.ChangeEvent<HTMLInputElement>) => { this.setState({ saveDescription: event.target.value }); }; private handleSaveUIDInputChange = (event: React.ChangeEvent<HTMLInputElement>) => { this.setState({ saveUID: event.target.value }); }; } export default SourcereelControlbar;
the_stack
import _Global = require("../../Core/_Global"); import _Control = require("../../Utilities/_Control"); import _Dispose = require("../../Utilities/_Dispose"); import _ElementUtilities = require("../../Utilities/_ElementUtilities"); import _Resources = require("../../Core/_Resources"); import ControlProcessor = require("../../ControlProcessor"); import Scheduler = require("../../Scheduler"); import XYFocus = require("../../XYFocus"); require(["require-style!less/styles-scrollviewer"]); require(["require-style!less/colors-scrollviewer"]); "use strict"; var SMALL_SCROLL_AMOUNT = 200; var PERCENTAGE_OF_PAGE_TO_SCROLL = 0.8; var THRESHOLD_TO_SHOW_TOP_ARROW = 50; var Keys = _ElementUtilities.Key; var strings = { get pageDown() { return _Resources._getWinJSString("tv/scrollViewerPageDown").value; }, get pageUp() { return _Resources._getWinJSString("tv/scrollViewerPageUp").value; } }; export var ScrollMode = { /// <field type="String" locid="WinJS.UI.ScrollMode.text" helpKeyword="WinJS.UI.ScrollMode.text"> /// Indicates the ScrollViewer contains text and must be invoked with the A button, then the contents can be scrolled /// using directional navigation. /// </field> text: "text", /// <field type="String" locid="WinJS.UI.ScrollMode.nonModalText" helpKeyword="WinJS.UI.ScrollMode.nonModalText"> /// This mode is similar to text mode except the user does not need to press A to begin scrolling. Instead they move /// focus to the ScrollViewer and are able to scroll text. This mode should only be used if there are no focusable /// UI elements above or below the control. /// </field> nonModalText: "nonModalText", /// <field type="String" locid="WinJS.UI.ScrollMode.list" helpKeyword="WinJS.UI.ScrollMode.list"> /// Indicates the ScrollViewer contains focusable elements and those elements that are off-screen are scrolled into view /// when the user selects those elements. /// </field> list: "list" }; export class ScrollViewer { static isDeclarativeControlContainer = true; static supportedForProcessing = true; private _element: HTMLElement; private _canScrollDown = false; private _canScrollUp = false; private _disposed = false; private _previousFocusRoot: HTMLElement; private _pendingRefresh = false; private _scrollingContainer: HTMLElement; private _scrollingIndicatorElement: HTMLElement; private _scrollMode: string; private _vuiActive = false; private _vuiPageUpElement: HTMLElement; private _vuiPageDownElement: HTMLElement; // Used for testing private _refreshDone: () => any; /// <field type="HTMLElement" domElement="true" hidden="true" locid="WinJS.UI.ScrollViewer.element" helpKeyword="WinJS.UI.ScrollViewer.element"> /// Gets the DOM element that hosts the ScrollViewer. /// </field> get element() { return this._element; } /// <field type="String" locid="WinJS.UI.ScrollViewer.interactionMode" helpKeyword="WinJS.UI.ScrollViewer.interactionMode"> /// Gets or sets a property that indicates whether there are focusable elements within the ScrollViewer. The default value is false. /// </field> get scrollMode() { return this._scrollMode; } set scrollMode(value: string) { this._scrollMode = value; // If there are no focusable elements then we need to listen for the A button. if (this._scrollMode === ScrollMode.list) { _ElementUtilities.removeClass(this._element, "win-scrollviewer-scrollmode-text"); _ElementUtilities.removeClass(this._scrollingContainer, "win-xyfocus-togglemode"); _ElementUtilities.addClass(this._element, "win-scrollviewer-scrollmode-list"); this._element.removeEventListener("keydown", this._handleKeyDown, true); this._setInactive(); } else { _ElementUtilities.removeClass(this._element, "win-scrollviewer-scrollmode-list"); _ElementUtilities.addClass(this._element, "win-scrollviewer-scrollmode-text"); _ElementUtilities.addClass(this._scrollingContainer, "win-xyfocus-togglemode"); this._element.addEventListener("keydown", this._handleKeyDown, true); } } constructor(element?: HTMLElement, options: any = {}) { this._element = element || document.createElement("div"); this._element["winControl"] = this; _ElementUtilities.addClass(this._element, "win-disposable"); _ElementUtilities.addClass(this._element, "win-scrollviewer"); this._handleFocus = this._handleFocus.bind(this); this._handleFocusOut = this._handleFocusOut.bind(this); this._handleKeyDown = this._handleKeyDown.bind(this); this._handleListeningStateChanged = this._handleListeningStateChanged.bind(this); this._handleScroll = this._handleScroll.bind(this); this._scrollDownBySmallAmount = this._scrollDownBySmallAmount.bind(this); this._scrollUpBySmallAmount = this._scrollUpBySmallAmount.bind(this); this._scrollDownByLargeAmount = this._scrollDownByLargeAmount.bind(this); this._scrollUpByLargeAmount = this._scrollUpByLargeAmount.bind(this); this._scrollingIndicatorElement = document.createElement("div"); this._scrollingIndicatorElement.className = "win-scrollindicator"; this._scrollingIndicatorElement.innerHTML = "<div class='win-overlay-arrowindicators'>" + " <div class='win-overlay-scrollupindicator'></div>" + " <div class='win-overlay-scrolldownindicator'></div>" + "</div>" + "<div class='win-overlay-voiceindicators'>" + " <div class='win-overlay-voice-command win-overlay-pageupindicator' aria-label='" + strings.pageUp + "'></div>" + " <div class='win-overlay-voice-command win-overlay-pagedownindicator' aria-label='" + strings.pageDown + "'></div>" + "</div>"; this._scrollingIndicatorElement.addEventListener("listeningstatechanged", this._handleListeningStateChanged); this._vuiPageUpElement = <HTMLElement>this._scrollingIndicatorElement.querySelector(".win-overlay-pageupindicator"); this._vuiPageUpElement.addEventListener("click", this._scrollUpByLargeAmount); this._vuiPageDownElement = <HTMLElement>this._scrollingIndicatorElement.querySelector(".win-overlay-pagedownindicator"); this._vuiPageDownElement.addEventListener("click", this._scrollDownByLargeAmount); this._scrollingContainer = document.createElement("div"); this._scrollingContainer.tabIndex = 0; _ElementUtilities.addClass(this._scrollingContainer, "win-scrollviewer-contentelement"); // Put the contents in a scrolling container var child = this._element.firstChild; while (child) { var sibling = child.nextSibling; this._scrollingContainer.appendChild(child); child = sibling; } this._element.appendChild(this._scrollingContainer); this._element.appendChild(this._scrollingIndicatorElement); this._scrollingContainer.addEventListener("scroll", this._handleScroll, false); this._scrollingContainer.addEventListener("focus", this._handleFocus, false); this._element.addEventListener("focusout", this._handleFocusOut, false); // Set the default scroll mode this.scrollMode = ScrollMode.text; _Control.setOptions(this, options); // The scroll viewer has two interaction modes: // 1. Normal - In this state there is focusable content within the scrollable // region. Automatic focus handles directional navigation and scrolls // elements into view. // 2. Text - In this state there is no focusable content within the scrollable // region. Typically, this case is free text. In this case, the ScrollViewer // handles directional navigation and scrolls up and down. // // To determine which mode we are in, we look for focusable content. If there // is no focusable content, then we know we are in "Text" mode. // We need to wait for processAll to finish on the inner contents of the scrollable region, because we need accurate // sizing information to determine if a region is scrollable or not. ControlProcessor.processAll(this.element).done(() => { this.refresh(); }); } /// <signature helpKeyword="WinJS.UI.ScrollViewer.dispose"> /// <summary locid="WinJS.UI.ScrollViewer.dispose"> /// Disposes the control. /// </summary> /// </signature> dispose() { if (this._disposed) { return; } this._disposed = true; _ElementUtilities.removeClass(this._element, "win-xyfocus-suspended"); _Dispose.disposeSubTree(this.element); } /// <signature helpKeyword="WinJS.UI.ScrollViewer.refresh"> /// <summary locid="WinJS.UI.ScrollViewer.refresh"> /// Call this function whenever the contents of the ScrollViewer changes. /// </summary> /// </signature> refresh() { this._refreshVisuals(); } private _moveFocus(direction: string) { // If we successfully move focus to a new target element, then set the ScrollViewer as inactive if (this._isActive()) { var previousFocusRectangleObject = this._scrollingContainer.getBoundingClientRect(); var previousFocusRectangle = { top: previousFocusRectangleObject.top, left: previousFocusRectangleObject.left, width: previousFocusRectangleObject.width, height: previousFocusRectangleObject.height }; var nextFocusElement = XYFocus.moveFocus(direction, { referenceRect: previousFocusRectangle }); if (nextFocusElement) { this._setInactive(); // Sound: Choose one of the 4 focus sounds to play at random } } } private _refreshScrollClassNames() { if (this._scrollingContainer.scrollTop >= THRESHOLD_TO_SHOW_TOP_ARROW) { this._canScrollUp = true; } else { this._canScrollUp = false; } if (this._scrollingContainer.scrollTop >= (this._scrollingContainer.scrollHeight - this._element.clientHeight)) { this._canScrollDown = false; } else { this._canScrollDown = true; } // Note: We remove the classes in order so we can avoid labels flashing if (!this._canScrollUp && !this._canScrollDown) { _ElementUtilities.removeClass(this._scrollingIndicatorElement, "win-scrollable-down"); _ElementUtilities.removeClass(this._scrollingIndicatorElement, "win-scrollable-up"); _ElementUtilities.addClass(this._vuiPageUpElement, "win-voice-disableoverride"); _ElementUtilities.addClass(this._vuiPageDownElement, "win-voice-disableoverride"); } else if (!this._canScrollUp && this._canScrollDown) { _ElementUtilities.removeClass(this._vuiPageUpElement, "win-voice-disableoverride"); _ElementUtilities.removeClass(this._vuiPageDownElement, "win-voice-disableoverride"); _ElementUtilities.removeClass(this._scrollingIndicatorElement, "win-scrollable-up"); _ElementUtilities.addClass(this._scrollingIndicatorElement, "win-scrollable-down"); _ElementUtilities.addClass(this._vuiPageUpElement, "win-voice-disabledlabel"); _ElementUtilities.removeClass(this._vuiPageDownElement, "win-voice-disabledlabel"); } else if (this._canScrollUp && !this._canScrollDown) { _ElementUtilities.addClass(this._scrollingIndicatorElement, "win-scrollable-up"); _ElementUtilities.removeClass(this._scrollingIndicatorElement, "win-scrollable-down"); _ElementUtilities.removeClass(this._vuiPageUpElement, "win-voice-disabledlabel"); _ElementUtilities.addClass(this._vuiPageDownElement, "win-voice-disabledlabel"); _ElementUtilities.removeClass(this._vuiPageUpElement, "win-voice-disableoverride"); _ElementUtilities.removeClass(this._vuiPageDownElement, "win-voice-disableoverride"); } else { _ElementUtilities.addClass(this._scrollingIndicatorElement, "win-scrollable-up"); _ElementUtilities.addClass(this._scrollingIndicatorElement, "win-scrollable-down"); _ElementUtilities.removeClass(this._vuiPageUpElement, "win-voice-disabledlabel"); _ElementUtilities.removeClass(this._vuiPageDownElement, "win-voice-disabledlabel"); _ElementUtilities.removeClass(this._vuiPageUpElement, "win-voice-disableoverride"); _ElementUtilities.removeClass(this._vuiPageDownElement, "win-voice-disableoverride"); } } private _refreshVisuals() { if (this._pendingRefresh) { return; } this._pendingRefresh = true; // We call this function any time the size of the contents within the ScrollViewer changes. This function // determines if we need to display the visual treatment for "more content". Scheduler.schedule(() => { this._pendingRefresh = false; if (this._disposed) { this._refreshDone && this._refreshDone(); return; } // Set initial visibility for the arrow indicators if the contents of the scrollable region // is bigger than the viewable area. if (this._scrollingContainer.clientHeight < this._scrollingContainer.scrollHeight) { this._refreshScrollClassNames(); // We only make the ScrollViewer focusable if it has text content and the // text content does not fit on the screen. If the text content does fit // on the screen then there is no reason to make the user scroll because // they can see all of the text. if (this._scrollMode === ScrollMode.text || this._scrollMode === ScrollMode.nonModalText) { _ElementUtilities.addClass(this._scrollingContainer, "win-focusable"); } // Add a class to indicate that the content within the ScrollViewer is bigger than // the visible area which means the ScrollViewer will need to be able to Scroll. _ElementUtilities.addClass(this._element, "win-scrollable"); } else { _ElementUtilities.removeClass(this._element, "win-scrollable"); _ElementUtilities.addClass(this._vuiPageUpElement, "win-voice-disableoverride"); _ElementUtilities.addClass(this._vuiPageDownElement, "win-voice-disableoverride"); } this._refreshDone && this._refreshDone(); }, Scheduler.Priority.high, this, "ScrollViewer_refreshVisuals"); } private _scrollDownBySmallAmount() { if (this._isActive()) { _ElementUtilities._zoomTo(this._scrollingContainer, { contentX: 0, contentY: this._scrollingContainer.scrollTop + SMALL_SCROLL_AMOUNT, viewportX: 0, viewportY: 0 }); } } private _scrollUpBySmallAmount() { if (this._isActive()) { _ElementUtilities._zoomTo(this._scrollingContainer, { contentX: 0, contentY: this._scrollingContainer.scrollTop - SMALL_SCROLL_AMOUNT, viewportX: 0, viewportY: 0 }); } } private _scrollDownByLargeAmount() { if (this._isActive() || this._vuiActive) { _ElementUtilities._zoomTo(this._scrollingContainer, { contentX: 0, contentY: this._scrollingContainer.scrollTop + (PERCENTAGE_OF_PAGE_TO_SCROLL * this._scrollingContainer.clientHeight), viewportX: 0, viewportY: 0 }); } } private _scrollUpByLargeAmount() { if (this._isActive() || this._vuiActive) { _ElementUtilities._zoomTo(this._scrollingContainer, { contentX: 0, contentY: this._scrollingContainer.scrollTop - (PERCENTAGE_OF_PAGE_TO_SCROLL * this._scrollingContainer.clientHeight), viewportX: 0, viewportY: 0 }); } } private _isActive() { return _ElementUtilities.hasClass(this._scrollingContainer, "win-xyfocus-togglemode-active"); } private _setActive() { _ElementUtilities.addClass(this._scrollingContainer, "win-xyfocus-togglemode-active"); } private _setInactive() { _ElementUtilities.removeClass(this._scrollingContainer, "win-xyfocus-togglemode-active"); } private _handleFocus(ev: FocusEvent) { if (this._scrollMode === ScrollMode.nonModalText) { this._setActive(); } else if (this._scrollMode === ScrollMode.list) { _ElementUtilities._focusFirstFocusableElement(this._scrollingContainer, false, this._scrollingContainer); } } private _handleFocusOut(ev: FocusEvent) { // If focus leaves the ScrollViewer & it was in the "invoked" state, // we need to reset it's state. if (this._isActive() && !this._element.contains(<HTMLElement>document.activeElement)) { this._setInactive(); } } private _handleKeyDown(ev: KeyboardEvent) { // Only set handled = true for shoulder button cases so that // scroll viewer doesn't trigger a hub interaction. var handled = false; switch (ev.keyCode) { case Keys.upArrow: case Keys.GamepadDPadUp: case Keys.GamepadLeftThumbstickUp: if (this._scrollMode === ScrollMode.nonModalText) { if (this._scrollingContainer.scrollTop >= THRESHOLD_TO_SHOW_TOP_ARROW) { // No-op - the user can scroll up. } else { var nextFocusElement = XYFocus.findNextFocusElement("up"); if (nextFocusElement) { nextFocusElement.focus(); } } } this._scrollUpBySmallAmount(); break; case Keys.downArrow: case Keys.GamepadDPadDown: case Keys.GamepadLeftThumbstickDown: if (this._scrollMode === ScrollMode.nonModalText) { if (this._scrollingContainer.scrollTop >= (this._scrollingContainer.scrollHeight - this._element.clientHeight)) { var nextFocusElement = XYFocus.findNextFocusElement("down"); if (nextFocusElement) { nextFocusElement.focus(); } } else { // No-op - the user can scroll down } } this._scrollDownBySmallAmount(); break; case Keys.leftArrow: case Keys.GamepadDPadLeft: case Keys.GamepadLeftThumbstickLeft: this._moveFocus("left"); break; case Keys.rightArrow: case Keys.GamepadDPadRight: case Keys.GamepadLeftThumbstickRight: this._moveFocus("right"); break; case Keys.pageUp: case Keys.GamepadLeftShoulder: this._scrollUpByLargeAmount(); handled = true; break; case Keys.pageDown: case Keys.GamepadRightShoulder: this._scrollDownByLargeAmount(); handled = true; break; default: break; } if (handled) { ev.stopPropagation(); } } private _handleListeningStateChanged(e: any) { if (e.state === "inactive") { _ElementUtilities.removeClass(this._element, "win-voice-voicemodeactive"); this._vuiActive = false; } else { _ElementUtilities.addClass(this._element, "win-voice-voicemodeactive"); this._vuiActive = true; } } private _handleScroll(ev: MouseEvent) { this._refreshScrollClassNames(); } }
the_stack
import { default as Yasqe, Token, Hint, Position, Config, HintFn, HintConfig } from "../"; import Trie from "../trie"; import { EventEmitter } from "events"; import * as superagent from "superagent"; import { take } from "lodash-es"; const CodeMirror = require("codemirror"); require("./show-hint.scss"); export interface CompleterConfig { onInitialize?: (this: CompleterConfig, yasqe: Yasqe) => void; //allows for e.g. registering event listeners in yasqe, like the prefix autocompleter does isValidCompletionPosition: (yasqe: Yasqe) => boolean; get: (yasqe: Yasqe, token?: AutocompletionToken) => Promise<string[]> | string[]; preProcessToken?: (yasqe: Yasqe, token: Token) => AutocompletionToken; postProcessSuggestion?: (yasqe: Yasqe, token: AutocompletionToken, suggestedString: string) => string; postprocessHints?: (yasqe: Yasqe, hints: Hint[]) => Hint[]; bulk: boolean; autoShow?: boolean; persistenceId?: Config["persistenceId"]; name: string; } const SUGGESTIONS_LIMIT = 100; export interface AutocompletionToken extends Token { autocompletionString?: string; tokenPrefix?: string; tokenPrefixUri?: string; from?: Partial<Position>; to?: Partial<Position>; } export class Completer extends EventEmitter { protected yasqe: Yasqe; private trie?: Trie; private config: CompleterConfig; constructor(yasqe: Yasqe, config: CompleterConfig) { super(); this.yasqe = yasqe; this.config = config; } // private selectHint(data:EditorChange, completion:any) { // if (completion.text != this.yasqe.getTokenAt(this.yasqe.getDoc().getCursor()).string) { // this.yasqe.getDoc().replaceRange(completion.text, data.from, data.to); // } // }; private getStorageId() { return this.yasqe.getStorageId(this.config.persistenceId); } /** * Store bulk completion in local storage, and populates the trie */ private storeBulkCompletions(completions: string[]) { if (!completions || !(completions instanceof Array)) return; // store array as trie this.trie = new Trie(); for (const c of completions) { this.trie.insert(c); } // store in localstorage as well var storageId = this.getStorageId(); if (storageId) this.yasqe.storage.set(storageId, completions, 60 * 60 * 24 * 30, this.yasqe.handleLocalStorageQuotaFull); } /** * Get completion list from `get` function */ public getCompletions(token?: AutocompletionToken): Promise<string[]> { if (!this.config.get) return Promise.resolve([]); //No token, so probably getting as bulk if (!token) { if (this.config.get instanceof Array) return Promise.resolve(this.config.get); //wrapping call in a promise.resolve, so this when a `get` is both async or sync return Promise.resolve(this.config.get(this.yasqe)).then((suggestions) => { if (suggestions instanceof Array) return suggestions; return []; }); } //ok, there is a token const stringToAutocomplete = token.autocompletionString || token.string; if (this.trie) return Promise.resolve(take(this.trie.autoComplete(stringToAutocomplete), SUGGESTIONS_LIMIT)); if (this.config.get instanceof Array) return Promise.resolve( this.config.get.filter((possibleMatch) => possibleMatch.indexOf(stringToAutocomplete) === 0) ); //assuming it's a function return Promise.resolve(this.config.get(this.yasqe, token)).then((r) => { if (r instanceof Array) return r; return []; }); } /** * Populates completions. Pre-fetches those if bulk is set to true */ public initialize(): Promise<void> { if (this.config.onInitialize) this.config.onInitialize(this.yasqe); if (this.config.bulk) { if (this.config.get instanceof Array) { // we don't care whether the completions are already stored in // localstorage. just use this one this.storeBulkCompletions(this.config.get); return Promise.resolve(); } else { // if completions are defined in localstorage, use those! (calling the // function may come with overhead (e.g. async calls)) var completionsFromStorage: string[] | undefined; var storageId = this.getStorageId(); if (storageId) completionsFromStorage = this.yasqe.storage.get<string[]>(storageId); if (completionsFromStorage && completionsFromStorage.length > 0) { this.storeBulkCompletions(completionsFromStorage); return Promise.resolve(); } else { return this.getCompletions().then((c) => this.storeBulkCompletions(c)); } } } return Promise.resolve(); } private isValidPosition(): boolean { if (!this.config.isValidCompletionPosition) return false; //no way to check whether we are in a valid position if (!this.config.isValidCompletionPosition(this.yasqe)) { this.emit("invalidPosition", this); this.yasqe.hideNotification(this.config.name); return false; } if (!this.config.autoShow) { this.yasqe.showNotification(this.config.name, "Press CTRL - <spacebar> to autocomplete"); } this.emit("validPosition", this); return true; } private getHint(autocompletionToken: AutocompletionToken, suggestedString: string): Hint { if (this.config.postProcessSuggestion) { suggestedString = this.config.postProcessSuggestion(this.yasqe, autocompletionToken, suggestedString); } let from: Position | undefined; let to: Position; const cursor = this.yasqe.getDoc().getCursor(); if (autocompletionToken.from) { from = { ...cursor, ...autocompletionToken.from }; } // Need to set a 'to' part as well, as otherwise we'd be appending the result to the already typed filter const line = this.yasqe.getDoc().getCursor().line; if (autocompletionToken.to) { to = { ch: autocompletionToken?.to?.ch || this.yasqe.getCompleteToken().end, line: line }; } else if (autocompletionToken.string.length > 0) { to = { ch: this.yasqe.getCompleteToken().end, line: line }; } else { to = <any>autocompletionToken.from; } return { text: suggestedString, displayText: suggestedString, from: from, to: to, }; } private getHints(token: AutocompletionToken): Promise<Hint[]> { if (this.config.preProcessToken) { token = this.config.preProcessToken(this.yasqe, token); } if (token) return this.getCompletions(token) .then((suggestions) => suggestions.map((s) => this.getHint(token, s))) .then((hints) => { if (this.config.postprocessHints) return this.config.postprocessHints(this.yasqe, hints); return hints; }); return Promise.resolve([]); } public autocomplete(fromAutoShow: boolean) { //this part goes before the autoshow check, as we _would_ like notification showing to indicate a user can press ctrl-space if (!this.isValidPosition()) return false; const previousCompletionItem = this.yasqe.state.completionActive; // Showhint by defaults takes the autocomplete start position (the location of the cursor at the time of starting the autocompletion). const cursor = this.yasqe.getDoc().getCursor(); if ( // When the cursor goes before current completionItem (e.g. using arrow keys), it would close the autocompletions. // We want the autocompletion to be active at whatever point we are in the token, so let's modify this start pos with the start pos of the token previousCompletionItem && cursor.sticky && // Is undefined at the end of the token, otherwise it is set as either "before" or "after" (The movement of the cursor) cursor.ch !== previousCompletionItem.startPos.ch ) { this.yasqe.state.completionActive.startPos = cursor; } else if (previousCompletionItem && !cursor.sticky && cursor.ch < previousCompletionItem.startPos.ch) { // A similar thing happens when pressing backspace, CodeMirror will close this autocomplete when 'startLen' changes downward cursor.sticky = previousCompletionItem.startPos.sticky; this.yasqe.state.completionActive.startPos.ch = cursor.ch; this.yasqe.state.completionActive.startLen--; } if ( fromAutoShow && // from autoShow, i.e. this gets called each time the editor content changes (!this.config.autoShow || this.yasqe.state.completionActive) // Don't show and don't create a new instance when its already active ) { return false; } const getHints: HintFn = () => { return this.getHints(this.yasqe.getCompleteToken()).then((list) => { const cur = this.yasqe.getDoc().getCursor(); const token: AutocompletionToken = this.yasqe.getCompleteToken(); const hintResult = { list: list, from: <Position>{ line: cur.line, ch: token.start, }, to: <Position>{ line: cur.line, ch: token.end, }, }; CodeMirror.on(hintResult, "shown", () => { this.yasqe.emit("autocompletionShown", (this.yasqe as any).state.completionActive.widget); }); CodeMirror.on(hintResult, "close", () => { this.yasqe.emit("autocompletionClose"); }); return hintResult; }); }; getHints.async = false; //in their code, async means using a callback //we always return a promise, which should be properly handled regardless of this val var hintConfig: HintConfig = { closeCharacters: /[\s>"]/, completeSingle: false, hint: getHints, container: this.yasqe.rootEl, // Override these actions back to use their default function // Otherwise these would navigate to the start/end of the suggestion list, while this can also be accomplished with PgUp and PgDn extraKeys: { Home: (yasqe, event) => { yasqe.getDoc().setCursor({ ch: 0, line: event.data.from.line }); }, End: (yasqe, event) => { yasqe.getDoc().setCursor({ ch: yasqe.getLine(event.data.to.line).length, line: event.data.to.line }); }, }, ...this.yasqe.config.hintConfig, }; this.yasqe.showHint(hintConfig); return true; } } /** * Converts rdf:type to http://.../type and converts <http://...> to http://... * Stores additional info such as the used namespace and prefix in the token object */ export function preprocessIriForCompletion(yasqe: Yasqe, token: AutocompletionToken) { const queryPrefixes = yasqe.getPrefixesFromQuery(); const stringToPreprocess = token.string; if (stringToPreprocess.indexOf("<") < 0) { token.tokenPrefix = stringToPreprocess.substring(0, stringToPreprocess.indexOf(":") + 1); if (queryPrefixes[token.tokenPrefix.slice(0, -1)] != null) { token.tokenPrefixUri = queryPrefixes[token.tokenPrefix.slice(0, -1)]; } } token.autocompletionString = stringToPreprocess.trim(); if (stringToPreprocess.indexOf("<") < 0 && stringToPreprocess.indexOf(":") > -1) { // hmm, the token is prefixed. We still need the complete uri for autocompletions. generate this! for (var prefix in queryPrefixes) { if (token.tokenPrefix === prefix + ":") { token.autocompletionString = queryPrefixes[prefix]; token.autocompletionString += stringToPreprocess.substring(prefix.length + 1); break; } } } if (token.autocompletionString.indexOf("<") == 0) token.autocompletionString = token.autocompletionString.substring(1); if (token.autocompletionString.indexOf(">", token.autocompletionString.length - 1) > 0) token.autocompletionString = token.autocompletionString.substring(0, token.autocompletionString.length - 1); return token; } export function postprocessIriCompletion(_yasqe: Yasqe, token: AutocompletionToken, suggestedString: string) { if (token.tokenPrefix && token.autocompletionString && token.tokenPrefixUri) { // we need to get the suggested string back to prefixed form suggestedString = token.tokenPrefix + suggestedString.substring(token.tokenPrefixUri.length); } else { // it is a regular uri. add '<' and '>' to string suggestedString = "<" + suggestedString + ">"; } return suggestedString; } //Use protocol relative request when served via http[s]*. Otherwise (e.g. file://, fetch via http) export const fetchFromLov = ( yasqe: Yasqe, type: "class" | "property", token?: AutocompletionToken ): Promise<string[]> => { var reqProtocol = window.location.protocol.indexOf("http") === 0 ? "https://" : "http://"; const notificationKey = "autocomplete_" + type; if (!token || !token.string || token.string.trim().length == 0) { yasqe.showNotification(notificationKey, "Nothing to autocomplete yet!"); return Promise.resolve([]); } // //if notification bar is there, show a loader // yasqe.autocompleters.notifications // .getEl(completer) // .empty() // .append($("<span>Fetchting autocompletions &nbsp;</span>")) // .append($(yutils.svg.getElement(require("../imgs.js").loader)).addClass("notificationLoader")); // doRequests(); return superagent .get(reqProtocol + "lov.linkeddata.es/dataset/lov/api/v2/autocomplete/terms") .query({ q: token.autocompletionString, page_size: 50, type: type, }) .then( (result) => { if (result.body.results) { return result.body.results.map((r: any) => r.uri[0]); } return []; }, (_e) => { yasqe.showNotification(notificationKey, "Failed fetching suggestions"); } ); }; import variableCompleter from "./variables"; import prefixCompleter from "./prefixes"; import propertyCompleter from "./properties"; import classCompleter from "./classes"; export var completers: CompleterConfig[] = [variableCompleter, prefixCompleter, propertyCompleter, classCompleter];
the_stack
import { applyChangesToString, ChangeType, convertNxGenerator, formatFiles, getProjects, logger, stripIndents, Tree, visitNotIgnoredFiles, } from '@nrwl/devkit'; import { fileExists } from '@nrwl/workspace/src/utilities/fileutils'; import { findNodes } from '@nrwl/workspace/src/utilities/typescript/find-nodes'; import { join, normalize } from 'path'; import { SyntaxKind } from 'typescript'; import ts = require('typescript'); export async function migrateStoriesTo62Generator(tree: Tree) { let allComponentsWithStories: { componentName: string; componentPath: any; componentFileName: any; componentStoryPath: string; }[] = []; const result: { name: string; configFolder: string; projectRoot: string; projectSrc: string; }[] = findAllAngularProjectsWithStorybookConfiguration(tree); result?.forEach( (angularProjectWithStorybook: { name: string; configFolder: string; projectRoot: string; projectSrc: string; }) => { const componentResult = findAllComponentsWithStoriesForSpecificProject( tree, angularProjectWithStorybook.projectRoot ); allComponentsWithStories = [ ...allComponentsWithStories, ...componentResult, ]; } ); allComponentsWithStories?.forEach((componentInfo) => { changeSyntaxOfStory(tree, componentInfo.componentStoryPath); }); await formatFiles(tree); } export function findAllAngularProjectsWithStorybookConfiguration(tree: Tree): { name: string; configFolder: string; projectRoot: string; projectSrc: string; }[] { const projects = getProjects(tree); const projectsThatHaveStorybookConfiguration: { name: string; configFolder: string; projectRoot: string; projectSrc: string; }[] = [...projects.entries()] ?.filter( ([_, projectConfig]) => projectConfig.targets && projectConfig.targets.storybook && projectConfig.targets.storybook.options && projectConfig.targets.storybook.options.uiFramework === '@storybook/angular' ) ?.map(([projectName, projectConfig]) => { if (projectConfig.targets && projectConfig.targets.storybook) { return { name: projectName, configFolder: projectConfig.targets.storybook.options.config.configFolder, projectRoot: projectConfig.root, projectSrc: projectConfig.sourceRoot, }; } }); return projectsThatHaveStorybookConfiguration; } function findAllComponentsWithStoriesForSpecificProject( tree: Tree, projectPath: string ): { componentName: string; componentPath: any; componentFileName: any; componentStoryPath: string; }[] { let moduleFilePaths = [] as string[]; visitNotIgnoredFiles(tree, projectPath, (filePath) => { if (filePath?.endsWith('.module.ts')) { moduleFilePaths.push(filePath); } }); let componentFileInfos = []; moduleFilePaths?.map((moduleFilePath) => { const file = getTsSourceFile(tree, moduleFilePath); const ngModuleDecorators = findNodes(file, ts.SyntaxKind.Decorator); if (ngModuleDecorators.length === 0) { return; } const ngModuleDecorator = ngModuleDecorators[0]; const ngModuleNode = ngModuleDecorator?.getChildren()?.find((node) => { return node?.getText()?.startsWith('NgModule'); }); const ngModulePropertiesObject = ngModuleNode ?.getChildren() ?.find((node) => { return node.kind === SyntaxKind.SyntaxList; }); const ngModuleProperties = ngModulePropertiesObject ?.getChildren()[0] ?.getChildren() ?.find((node) => { return node?.getText()?.includes('declarations'); }); const declarationsPropertyAssignment = ngModuleProperties ?.getChildren() ?.find((node) => { return node?.getText()?.startsWith('declarations'); }); if (!declarationsPropertyAssignment) { logger.warn(stripIndents`No components declared in ${moduleFilePath}.`); } let declarationArray = declarationsPropertyAssignment ?.getChildren() ?.find((node) => node.kind === SyntaxKind.ArrayLiteralExpression); if (!declarationArray) { // Attempt to follow a variable instead of the literal const declarationVariable = declarationsPropertyAssignment ?.getChildren() ?.filter((node) => node.kind === SyntaxKind.Identifier)[1]; const variableName = declarationVariable?.getText(); const variableDeclaration = findNodes( file, SyntaxKind.VariableDeclaration )?.find((variableDeclaration) => { const identifier = variableDeclaration ?.getChildren() ?.find((node) => node.kind === SyntaxKind.Identifier); return identifier?.getText() === variableName; }); if (variableDeclaration) { declarationArray = variableDeclaration ?.getChildren() ?.find((node) => node.kind === SyntaxKind.ArrayLiteralExpression); } } const declaredComponents = declarationArray ?.getChildren() ?.find((node) => node.kind === SyntaxKind.SyntaxList) ?.getChildren() ?.filter((node) => node.kind === SyntaxKind.Identifier) ?.map((node) => node?.getText()) ?.filter((name) => name?.endsWith('Component')); const imports = file.statements?.filter( (statement) => statement.kind === SyntaxKind.ImportDeclaration ); const modulePath = moduleFilePath.substr( 0, moduleFilePath?.lastIndexOf('/') ); let componentInfo = declaredComponents?.map((componentName) => { try { const importStatement = imports?.find((statement) => { const namedImports = statement ?.getChildren() ?.find((node) => node.kind === SyntaxKind.ImportClause) ?.getChildren() ?.find((node) => node.kind === SyntaxKind.NamedImports); if (namedImports === undefined) return false; const importedIdentifiers = namedImports ?.getChildren() ?.find((node) => node.kind === SyntaxKind.SyntaxList) ?.getChildren() ?.filter((node) => node.kind === SyntaxKind.ImportSpecifier) ?.map((node) => node?.getText()); return importedIdentifiers?.includes(componentName); }); const fullPath = importStatement ?.getChildren() ?.find((node) => node.kind === SyntaxKind.StringLiteral) ?.getText() ?.slice(1, -1); // if it is a directory, search recursively for the component let fullCmpImportPath = moduleFilePath?.slice( 0, moduleFilePath?.lastIndexOf('/') ); if (fullCmpImportPath?.startsWith('/')) { fullCmpImportPath = fullCmpImportPath?.slice( 1, fullCmpImportPath.length ); } let componentImportPath = join(normalize(fullCmpImportPath), fullPath); let path = null; let componentFileName = null; let componentStoryPath = null; let storyExists = false; let componentExists = false; /** * Here we want to remove the <component-name>.component * part of the path, to just keep the * apps/<project-name>/src/app/<component-name> * or * libs/<project-name>/src/lib/<component-name> * part of the path */ componentImportPath = componentImportPath.slice( 0, componentImportPath.lastIndexOf('/') ); visitNotIgnoredFiles(tree, componentImportPath, (componentFilePath) => { if (componentFilePath?.endsWith('.ts')) { const content = tree.read(componentFilePath).toString('utf-8'); if (content?.indexOf(`class ${componentName}`) > -1) { componentExists = true; path = componentFilePath; componentFileName = componentFilePath?.slice( componentFilePath?.lastIndexOf('/') + 1, componentFilePath?.lastIndexOf('.') ) + '.ts'; } if (componentFilePath?.endsWith('.stories.ts')) { componentStoryPath = componentFilePath; storyExists = true; } } }); if (!storyExists || !componentExists) { path = null; componentFileName = null; componentStoryPath = null; } if (path !== null) { return { componentName: componentName, componentPath: path, componentFileName, componentStoryPath: componentStoryPath, }; } else { const path = fullPath?.slice(0, fullPath?.lastIndexOf('/')); const componentFileName = fullPath?.slice(fullPath?.lastIndexOf('/') + 1) + '.ts'; componentStoryPath = fullPath + '.stories.ts'; if (fileExists(componentStoryPath)) { return { componentName: componentName, componentPath: path + componentFileName, componentFileName, componentStoryPath: componentStoryPath, }; } else { return undefined; } } } catch (e) { logger.warn(`Could not find file for ${componentName}. Error: ${e}`); return undefined; } }); if (componentInfo) { componentInfo = componentInfo?.filter((info) => info !== undefined); componentFileInfos = [...componentFileInfos, ...componentInfo]; } }); return componentFileInfos; } export function getTsSourceFile(host: Tree, path: string): ts.SourceFile { const buffer = host.read(path); if (!buffer) { throw new Error(`Could not read TS file (${path}).`); } const content = buffer.toString(); const source = ts.createSourceFile( path, content, ts.ScriptTarget.Latest, true ); return source; } async function changeSyntaxOfStory(tree: Tree, storyFilePath: string) { const file = getTsSourceFile(tree, storyFilePath); const appFileContent = tree.read(storyFilePath, 'utf-8'); let newContents = appFileContent; const storiesVariableDeclaration = findNodes(file, [ ts.SyntaxKind.VariableDeclaration, ]); const storiesExportDefault = findNodes(file, [ ts.SyntaxKind.ExportAssignment, ]); const defaultExportNode = storiesExportDefault[0]; const defaultExportObject = defaultExportNode?.getChildren()?.find((node) => { return node.kind === SyntaxKind.ObjectLiteralExpression; }); const defaultPropertiesList = defaultExportObject ?.getChildren() ?.find((node) => { return node.kind === SyntaxKind.SyntaxList; }); const hasTitle = defaultPropertiesList?.getChildren()?.find((node) => { return ( node.kind === SyntaxKind.PropertyAssignment && node.getText().startsWith('title') ); }); /** * A component node will look like this: * * component: MyTestComponent * * And this is what we need to remove. */ let firstComponentNode: ts.Node; /** * The result of ts.Node.getStart() will give us the index * of that node in the whole original file. * While we're editing that file, the getStart() will * still reference the original file. So, during deletion, * it would go and delete characters using the original index. * * We need to save the length of the characters that have been removed * so far, so that we can substract it from the index. * Since it's parsing the file linearly and in order, then this * logic works. * */ let lengthOfRemovalsSoFar = 0; storiesVariableDeclaration?.forEach((oneStory) => { const oneExportedStoryArrowFunction = oneStory ?.getChildren() ?.find((node) => { return node.kind === SyntaxKind.ArrowFunction; }); const inParenthesis = oneExportedStoryArrowFunction ?.getChildren() ?.find((node) => { return node.kind === SyntaxKind.ParenthesizedExpression; }); const objectLiteralOfStory = inParenthesis?.getChildren()?.find((node) => { return node.kind === SyntaxKind.ObjectLiteralExpression; }); const propertiesList = objectLiteralOfStory?.getChildren()?.find((node) => { return node.kind === SyntaxKind.SyntaxList; }); const hasComponentDeclared = propertiesList?.getChildren()?.find((node) => { return ( node.kind === SyntaxKind.PropertyAssignment && node.getText().startsWith('component') ); }); if (hasComponentDeclared) { /** * Here I am saving the first component to appear * in the case where we have multiple stories */ if (!firstComponentNode) { firstComponentNode = hasComponentDeclared; } /** * Here we are performing the following check: * If the component we will be adding in the default declaration * which is the first component that we find * is the same for this story as well, * then remove it. */ if (hasComponentDeclared.getText() === firstComponentNode.getText()) { const indexOfPropertyName = hasComponentDeclared.getStart(); const lengthOfRemoval = hasComponentDeclared?.getText()?.length + 1; newContents = applyChangesToString(newContents, [ { type: ChangeType.Delete, start: indexOfPropertyName - lengthOfRemovalsSoFar, length: lengthOfRemoval, }, ]); lengthOfRemovalsSoFar = lengthOfRemovalsSoFar + lengthOfRemoval; } } }); if (hasTitle && firstComponentNode) { const indexOfPropertyName = hasTitle.getEnd(); newContents = applyChangesToString(newContents, [ { type: ChangeType.Insert, index: indexOfPropertyName + 2, text: firstComponentNode.getText() + ',', }, ]); tree.write(storyFilePath, newContents); } await formatFiles(tree); } export default migrateStoriesTo62Generator; export const migrateStoriesSchematic = convertNxGenerator( migrateStoriesTo62Generator );
the_stack
import * as loginPage from '../../Base/pages/Login.po'; import { LoginPageData } from '../../Base/pagedata/LoginPageData'; import * as timeOffPage from '../../Base/pages/TimeOff.po'; import { TimeOffPageData } from '../../Base/pagedata/TimeOffPageData'; import * as dashboardPage from '../../Base/pages/Dashboard.po'; import { CustomCommands } from '../../commands'; import * as faker from 'faker'; import * as logoutPage from '../../Base/pages/Logout.po'; import * as manageEmployeesPage from '../../Base/pages/ManageEmployees.po'; import { Given, Then, When, And } from 'cypress-cucumber-preprocessor/steps'; const pageLoadTimeout = Cypress.config('pageLoadTimeout'); let firstName = faker.name.firstName(); let lastName = faker.name.lastName(); let username = faker.internet.userName(); let password = faker.internet.password(); let employeeEmail = faker.internet.email(); let imgUrl = faker.image.avatar(); // Login with email Given('Login with default credentials', () => { CustomCommands.login(loginPage, LoginPageData, dashboardPage); }); // Add employee And('User can add new employee', () => { dashboardPage.verifyAccountingDashboardIfVisible(); CustomCommands.addEmployee( manageEmployeesPage, firstName, lastName, username, employeeEmail, password, imgUrl ); }); // Add new policy And('User can visit Employees time off page', () => { CustomCommands.logout(dashboardPage, logoutPage, loginPage); CustomCommands.clearCookies(); CustomCommands.login(loginPage, LoginPageData, dashboardPage); cy.visit('/#/pages/employees/time-off', { timeout: pageLoadTimeout }); }); And('User can see time off settings button', () => { timeOffPage.timeOffSettingsButtonVisible(); }); When('User click on time off settings button', () => { timeOffPage.clickTimeOffSettingsButton(1); }); Then('User can see add new policy button', () => { timeOffPage.addNewPolicyButtonVisible(); }); When('User click on add new policy button', () => { timeOffPage.clickAddNewPolicyButton(); }); Then('User can see policy input field', () => { timeOffPage.policyInputFieldVisible(); }); And('User can enter policy name', () => { timeOffPage.enterNewPolicyName(TimeOffPageData.addNewPolicyData); }); And('User can see employee select dropdown', () => { timeOffPage.selectEmployeeDropdownVisible(); }); When('User click on employee select dropdown', () => { timeOffPage.clickSelectEmployeeDropdown(); }); Then('User can select employee from dropdown select options', () => { timeOffPage.selectEmployeeFromHolidayDropdown(0); timeOffPage.clickKeyboardButtonByKeyCode(9); }); And('User can see save new policy button', () => { timeOffPage.saveButtonVisible(); }); When('User click on save new policy button', () => { timeOffPage.clickSaveButton(); }); Then('Notification message will appear', () => { timeOffPage.waitMessageToHide(); }); And('User can see back button', () => { timeOffPage.backButtonVisible(); }); When('User click on back button', () => { timeOffPage.clickBackButton(); }); // Create new time off request Then('User can see request button', () => { timeOffPage.requestButtonVisible(); }); When('User click on request button', () => { timeOffPage.clickRequestButton(); }); Then('User can see employee select', () => { timeOffPage.employeeSelectorVisible(); }); When('User click employee select', () => { timeOffPage.clickEmployeeSelector(); }); Then('User can see employee dropdown', () => { timeOffPage.employeeDropdownVisible(); }); And('User can select employee from dropdown options', () => { timeOffPage.selectEmployeeFromDropdown(1); }); And('User can see time off policy select', () => { timeOffPage.selectTimeOffPolicyVisible(); }); When('User click on time off policy select', () => { timeOffPage.clickTimeOffPolicyDropdown(); }); Then('User can see time off policy dropdown', () => { timeOffPage.timeOffPolicyDropdownOptionVisible(); }); And('User can select time off policy from dropdown options', () => { timeOffPage.selectTimeOffPolicy(TimeOffPageData.addNewPolicyData); }); And('User can see start date input field', () => { timeOffPage.startDateInputVisible(); }); And('User can enter start date', () => { timeOffPage.enterStartDateData(); }); And('User can see end date input field', () => { timeOffPage.endDateInputVisible(); }); And('User can enter and date', () => { timeOffPage.enterEndDateData(); }); And('User can see description input field', () => { timeOffPage.descriptionInputVisible(); }); And('User can enter description', () => { timeOffPage.enterDdescriptionInputData(TimeOffPageData.defaultDescription); }); And('User can see save request button', () => { timeOffPage.saveRequestButtonVisible(); }); When('User click on save request button', () => { timeOffPage.clickSaveRequestButton(); }); Then('Notification message will appear', () => { timeOffPage.waitMessageToHide(); }); // Deny time off request And('User can see time off requests table', () => { timeOffPage.timeOffTableRowVisible(); }); When('User click on time off requests table row', () => { timeOffPage.selectTimeOffTableRow(0); }); Then('User can see deny time off request button', () => { timeOffPage.denyTimeOffButtonVisible(); }); When('User click on deny time off request button', () => { timeOffPage.clickDenyTimeOffButton(); }); Then('Notification message will appear', () => { timeOffPage.waitMessageToHide(); }); // Approve time off request And('User can see approve time off request button', () => { timeOffPage.selectTimeOffTableRow(0); timeOffPage.approveTimeOffButtonVisible(); }); When('User click on approve time off request button', () => { timeOffPage.clickApproveTimeOffButton(); }); Then('User can see request button', () => { timeOffPage.requestButtonVisible(); }); When('User click on request button', () => { timeOffPage.clickRequestButton(); }); Then('User can see employee select again', () => { timeOffPage.employeeSelectorVisibleAgain(); }); When('User click employee select', () => { timeOffPage.clickEmployeeSelector(); }); Then('User can see employee dropdown', () => { timeOffPage.employeeDropdownVisible(); }); And('User can select employee from dropdown options', () => { timeOffPage.selectEmployeeFromDropdown(1); }); And('User can see time off policy select', () => { timeOffPage.selectTimeOffPolicyVisible(); }); When('User click on time off policy select', () => { timeOffPage.clickTimeOffPolicyDropdown(); }); Then('User can see time off policy dropdown again', () => { timeOffPage.timeOffPolicyDropdownOptionVisible(); }); And('User can select time off policy from dropdown options', () => { timeOffPage.selectTimeOffPolicy(TimeOffPageData.addNewPolicyData); }); And('User can see start date input field', () => { timeOffPage.startDateInputVisible(); }); And('User can enter start date', () => { timeOffPage.enterStartDateData(); }); And('User can see end date input field', () => { timeOffPage.endDateInputVisible(); }); And('User can enter and date', () => { timeOffPage.enterEndDateData(); }); And('User can see description input field', () => { timeOffPage.descriptionInputVisible(); }); And('User can enter description', () => { timeOffPage.enterDdescriptionInputData(TimeOffPageData.defaultDescription); }); And('User can see save request button', () => { timeOffPage.saveRequestButtonVisible(); }); When('User click on save request button', () => { timeOffPage.clickSaveRequestButton(); }); Then('Notification message will appear', () => { timeOffPage.waitMessageToHide(); }); // Delete time off request And('User can see time off requests table again', () => { timeOffPage.timeOffTableRowVisible(); }); When('User click on time off requests table row again', () => { timeOffPage.selectTimeOffTableRow(0); }); Then('User can see delete time off request button', () => { timeOffPage.deleteTimeOffBtnVisible(); }); When('User click on delete time off request button', () => { timeOffPage.clickDeleteTimeOffButton(); }); Then('User can see confirm delete button', () => { timeOffPage.confirmDeleteTimeOffBtnVisible(); }); When('User click on confirm delete button', () => { timeOffPage.clickConfirmDeleteTimeOffButoon(); }); Then('Notification message will appear', () => { timeOffPage.waitMessageToHide(); }); // Add holiday And('User can see add holiday button', () => { timeOffPage.addHolidayButtonVisible(); }); When('User click on add holiday button', () => { timeOffPage.clickAddHolidayButton(); }); Then('User can see holiday name select', () => { timeOffPage.selectHolidayNameVisible(); }); When('User click on holiday select', () => { timeOffPage.clickSelectHolidayName(); }); Then('User can select holiday from dropdown options', () => { timeOffPage.selectHolidayOption(0); }); And('User can see select employee dropdown', () => { timeOffPage.verifyEmployeeSelectorVisible(); }); When('User click on select employee dropdown', () => { timeOffPage.clickEmployeeSelectorDropdown(); }); Then('User can select employee from select dropdown options', () => { timeOffPage.selectEmployeeFromHolidayDropdown(0); timeOffPage.clickKeyboardButtonByKeyCode(9); }); And('User can see again time off policy dropdown', () => { timeOffPage.verifyTimeOffPolicyVisible(); }); When('User click on time off policy dropdown', () => { timeOffPage.clickTimeOffPolicySelector(); }); Then('User can see again time off policy dropdown', () => { timeOffPage.timeOffPolicyDropdownOptionVisible(); }); And('User can select again time off policy from dropdown options', () => { timeOffPage.selectTimeOffPolicy(TimeOffPageData.addNewPolicyData); }); And('User can see start holiday input field', () => { timeOffPage.startHolidayDateInputVisible(); }); And('User can enter start holiday date', () => { timeOffPage.enterStartHolidayDate(); }); And('User can see end holiday date input field', () => { timeOffPage.endHolidayDateInputVisible(); }); And('User can enter end holiday date', () => { timeOffPage.enterEndHolidayDate(); timeOffPage.clickKeyboardButtonByKeyCode(9); }); And('User can see save holiday button', () => { timeOffPage.saveButtonVisible(); }); When('User click on save holiday button', () => { timeOffPage.clickSaveButton(); }); Then('Notification message will appear', () => { timeOffPage.waitMessageToHide(); });
the_stack
import type { EventPhase } from '@interactjs/core/InteractEvent' import type { Interaction, DoAnyPhaseArg } from '@interactjs/core/Interaction' import type { EdgeOptions, FullRect, Point, Rect } from '@interactjs/types/index' import clone from '@interactjs/utils/clone' import extend from '@interactjs/utils/extend' import * as rectUtils from '@interactjs/utils/rect' import type { Modifier, ModifierArg, ModifierState } from './base' export interface ModificationResult { delta: Point rectDelta: Rect coords: Point rect: FullRect eventProps: any[] changed: boolean } interface MethodArg { phase: EventPhase pageCoords: Point rect: FullRect coords: Point preEnd?: boolean skipModifiers?: number } export default class Modification { states: ModifierState[] = [] startOffset: Rect = { left: 0, right: 0, top: 0, bottom: 0 } startDelta!: Point result!: ModificationResult endResult!: Point edges!: EdgeOptions readonly interaction: Readonly<Interaction> constructor (interaction: Interaction) { this.interaction = interaction this.result = createResult() } start ({ phase }: { phase: EventPhase }, pageCoords: Point) { const { interaction } = this const modifierList = getModifierList(interaction) this.prepareStates(modifierList) this.edges = extend({}, interaction.edges) this.startOffset = getRectOffset(interaction.rect, pageCoords) this.startDelta = { x: 0, y: 0 } const arg = this.fillArg({ phase, pageCoords, preEnd: false, }) this.result = createResult() this.startAll(arg) const result = (this.result = this.setAll(arg)) return result } fillArg (arg: Partial<ModifierArg>) { const { interaction } = this arg.interaction = interaction arg.interactable = interaction.interactable arg.element = interaction.element arg.rect = arg.rect || interaction.rect arg.edges = this.edges arg.startOffset = this.startOffset return arg as ModifierArg } startAll (arg: MethodArg & Partial<ModifierArg>) { for (const state of this.states) { if (state.methods.start) { arg.state = state state.methods.start(arg as ModifierArg) } } } setAll (arg: MethodArg & Partial<ModifierArg>): ModificationResult { const { phase, preEnd, skipModifiers, rect: unmodifiedRect } = arg arg.coords = extend({}, arg.pageCoords) arg.rect = extend({}, unmodifiedRect) const states = skipModifiers ? this.states.slice(skipModifiers) : this.states const newResult = createResult(arg.coords, arg.rect) for (const state of states) { const { options } = state const lastModifierCoords = extend({}, arg.coords) let returnValue = null if (state.methods?.set && this.shouldDo(options, preEnd, phase)) { arg.state = state returnValue = state.methods.set(arg as ModifierArg<never>) rectUtils.addEdges(this.interaction.edges, arg.rect, { x: arg.coords.x - lastModifierCoords.x, y: arg.coords.y - lastModifierCoords.y, }) } newResult.eventProps.push(returnValue) } newResult.delta.x = arg.coords.x - arg.pageCoords.x newResult.delta.y = arg.coords.y - arg.pageCoords.y newResult.rectDelta.left = arg.rect.left - unmodifiedRect.left newResult.rectDelta.right = arg.rect.right - unmodifiedRect.right newResult.rectDelta.top = arg.rect.top - unmodifiedRect.top newResult.rectDelta.bottom = arg.rect.bottom - unmodifiedRect.bottom const prevCoords = this.result.coords const prevRect = this.result.rect if (prevCoords && prevRect) { const rectChanged = newResult.rect.left !== prevRect.left || newResult.rect.right !== prevRect.right || newResult.rect.top !== prevRect.top || newResult.rect.bottom !== prevRect.bottom newResult.changed = rectChanged || prevCoords.x !== newResult.coords.x || prevCoords.y !== newResult.coords.y } return newResult } applyToInteraction (arg: { phase: EventPhase, rect?: Rect }) { const { interaction } = this const { phase } = arg const curCoords = interaction.coords.cur const startCoords = interaction.coords.start const { result, startDelta } = this const curDelta = result.delta if (phase === 'start') { extend(this.startDelta, result.delta) } for (const [coordsSet, delta] of [ [startCoords, startDelta], [curCoords, curDelta], ] as const) { coordsSet.page.x += delta.x coordsSet.page.y += delta.y coordsSet.client.x += delta.x coordsSet.client.y += delta.y } const { rectDelta } = this.result const rect = arg.rect || interaction.rect rect.left += rectDelta.left rect.right += rectDelta.right rect.top += rectDelta.top rect.bottom += rectDelta.bottom rect.width = rect.right - rect.left rect.height = rect.bottom - rect.top } setAndApply ( arg: Partial<DoAnyPhaseArg> & { phase: EventPhase preEnd?: boolean skipModifiers?: number modifiedCoords?: Point }, ): void | false { const { interaction } = this const { phase, preEnd, skipModifiers } = arg const result = this.setAll( this.fillArg({ preEnd, phase, pageCoords: arg.modifiedCoords || interaction.coords.cur.page, }), ) this.result = result // don't fire an action move if a modifier would keep the event in the same // cordinates as before if ( !result.changed && (!skipModifiers || skipModifiers < this.states.length) && interaction.interacting() ) { return false } if (arg.modifiedCoords) { const { page } = interaction.coords.cur const adjustment = { x: arg.modifiedCoords.x - page.x, y: arg.modifiedCoords.y - page.y, } result.coords.x += adjustment.x result.coords.y += adjustment.y result.delta.x += adjustment.x result.delta.y += adjustment.y } this.applyToInteraction(arg) } beforeEnd (arg: Omit<DoAnyPhaseArg, 'iEvent'> & { state?: ModifierState }): void | false { const { interaction, event } = arg const states = this.states if (!states || !states.length) { return } let doPreend = false for (const state of states) { arg.state = state const { options, methods } = state const endPosition = methods.beforeEnd && methods.beforeEnd((arg as unknown) as ModifierArg) if (endPosition) { this.endResult = endPosition return false } doPreend = doPreend || (!doPreend && this.shouldDo(options, true, arg.phase, true)) } if (doPreend) { // trigger a final modified move before ending interaction.move({ event, preEnd: true }) } } stop (arg: { interaction: Interaction }) { const { interaction } = arg if (!this.states || !this.states.length) { return } const modifierArg: Partial<ModifierArg> = extend( { states: this.states, interactable: interaction.interactable, element: interaction.element, rect: null, }, arg, ) this.fillArg(modifierArg) for (const state of this.states) { modifierArg.state = state if (state.methods.stop) { state.methods.stop(modifierArg as ModifierArg) } } this.states = null this.endResult = null } prepareStates (modifierList: Modifier[]) { this.states = [] for (let index = 0; index < modifierList.length; index++) { const { options, methods, name } = modifierList[index] this.states.push({ options, methods, index, name, }) } return this.states } restoreInteractionCoords ({ interaction: { coords, rect, modification } }: { interaction: Interaction }) { if (!modification.result) return const { startDelta } = modification const { delta: curDelta, rectDelta } = modification.result const coordsAndDeltas = [ [coords.start, startDelta], [coords.cur, curDelta], ] for (const [coordsSet, delta] of coordsAndDeltas as any) { coordsSet.page.x -= delta.x coordsSet.page.y -= delta.y coordsSet.client.x -= delta.x coordsSet.client.y -= delta.y } rect.left -= rectDelta.left rect.right -= rectDelta.right rect.top -= rectDelta.top rect.bottom -= rectDelta.bottom } shouldDo (options, preEnd?: boolean, phase?: string, requireEndOnly?: boolean) { if ( // ignore disabled modifiers !options || options.enabled === false || // check if we require endOnly option to fire move before end (requireEndOnly && !options.endOnly) || // don't apply endOnly modifiers when not ending (options.endOnly && !preEnd) || // check if modifier should run be applied on start (phase === 'start' && !options.setStart) ) { return false } return true } copyFrom (other: Modification) { this.startOffset = other.startOffset this.startDelta = other.startDelta this.edges = other.edges this.states = other.states.map((s) => clone(s) as ModifierState) this.result = createResult(extend({}, other.result.coords), extend({}, other.result.rect)) } destroy () { for (const prop in this) { this[prop] = null } } } function createResult (coords?: Point, rect?: FullRect): ModificationResult { return { rect, coords, delta: { x: 0, y: 0 }, rectDelta: { left: 0, right: 0, top: 0, bottom: 0, }, eventProps: [], changed: true, } } function getModifierList (interaction) { const actionOptions = interaction.interactable.options[interaction.prepared.name] const actionModifiers = actionOptions.modifiers if (actionModifiers && actionModifiers.length) { return actionModifiers } return ['snap', 'snapSize', 'snapEdges', 'restrict', 'restrictEdges', 'restrictSize'] .map((type) => { const options = actionOptions[type] return ( options && options.enabled && { options, methods: options._methods, } ) }) .filter((m) => !!m) } export function getRectOffset (rect, coords) { return rect ? { left: coords.x - rect.left, top: coords.y - rect.top, right: rect.right - coords.x, bottom: rect.bottom - coords.y, } : { left: 0, top: 0, right: 0, bottom: 0, } }
the_stack
| Copyright (c) 2014-2017, PhosphorJS Contributors | | Distributed under the terms of the BSD 3-Clause License. | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ import { ArrayExt, each } from '@lumino/algorithm'; import { ElementExt } from '@lumino/domutils'; import { Message, MessageLoop } from '@lumino/messaging'; import { AttachedProperty } from '@lumino/properties'; import { BoxEngine, BoxSizer } from './boxengine'; import { LayoutItem } from './layout'; import { PanelLayout } from './panellayout'; import { Utils } from './utils'; import { Widget } from './widget'; /** * A layout which arranges its widgets into resizable sections. */ export class SplitLayout extends PanelLayout { /** * Construct a new split layout. * * @param options - The options for initializing the layout. */ constructor(options: SplitLayout.IOptions) { super(); this.renderer = options.renderer; if (options.orientation !== undefined) { this._orientation = options.orientation; } if (options.alignment !== undefined) { this._alignment = options.alignment; } if (options.spacing !== undefined) { this._spacing = Utils.clampDimension(options.spacing); } } /** * Dispose of the resources held by the layout. */ dispose(): void { // Dispose of the layout items. each(this._items, (item) => { item.dispose(); }); // Clear the layout state. this._box = null; this._items.length = 0; this._sizers.length = 0; this._handles.length = 0; // Dispose of the rest of the layout. super.dispose(); } /** * The renderer used by the split layout. */ readonly renderer: SplitLayout.IRenderer; /** * Get the layout orientation for the split layout. */ get orientation(): SplitLayout.Orientation { return this._orientation; } /** * Set the layout orientation for the split layout. */ set orientation(value: SplitLayout.Orientation) { if (this._orientation === value) { return; } this._orientation = value; if (!this.parent) { return; } this.parent.dataset['orientation'] = value; this.parent.fit(); } /** * Get the content alignment for the split layout. * * #### Notes * This is the alignment of the widgets in the layout direction. * * The alignment has no effect if the widgets can expand to fill the * entire split layout. */ get alignment(): SplitLayout.Alignment { return this._alignment; } /** * Set the content alignment for the split layout. * * #### Notes * This is the alignment of the widgets in the layout direction. * * The alignment has no effect if the widgets can expand to fill the * entire split layout. */ set alignment(value: SplitLayout.Alignment) { if (this._alignment === value) { return; } this._alignment = value; if (!this.parent) { return; } this.parent.dataset['alignment'] = value; this.parent.update(); } /** * Get the inter-element spacing for the split layout. */ get spacing(): number { return this._spacing; } /** * Set the inter-element spacing for the split layout. */ set spacing(value: number) { value = Utils.clampDimension(value); if (this._spacing === value) { return; } this._spacing = value; if (!this.parent) { return; } this.parent.fit(); } /** * A read-only array of the split handles in the layout. */ get handles(): ReadonlyArray<HTMLDivElement> { return this._handles; } /** * Get the relative sizes of the widgets in the layout. * * @returns A new array of the relative sizes of the widgets. * * #### Notes * The returned sizes reflect the sizes of the widgets normalized * relative to their siblings. * * This method **does not** measure the DOM nodes. */ relativeSizes(): number[] { return Private.normalize(this._sizers.map((sizer) => sizer.size)); } /** * Set the relative sizes for the widgets in the layout. * * @param sizes - The relative sizes for the widgets in the panel. * * #### Notes * Extra values are ignored, too few will yield an undefined layout. * * The actual geometry of the DOM nodes is updated asynchronously. */ setRelativeSizes(sizes: number[]): void { // Copy the sizes and pad with zeros as needed. let n = this._sizers.length; let temp = sizes.slice(0, n); while (temp.length < n) { temp.push(0); } // Normalize the padded sizes. let normed = Private.normalize(temp); // Apply the normalized sizes to the sizers. for (let i = 0; i < n; ++i) { let sizer = this._sizers[i]; sizer.sizeHint = normed[i]; sizer.size = normed[i]; } // Set the flag indicating the sizes are normalized. this._hasNormedSizes = true; // Trigger an update of the parent widget. if (this.parent) { this.parent.update(); } } /** * Move the offset position of a split handle. * * @param index - The index of the handle of the interest. * * @param position - The desired offset position of the handle. * * #### Notes * The position is relative to the offset parent. * * This will move the handle as close as possible to the desired * position. The sibling widgets will be adjusted as necessary. */ moveHandle(index: number, position: number): void { // Bail if the index is invalid or the handle is hidden. let handle = this._handles[index]; if (!handle || handle.classList.contains('lm-mod-hidden')) { return; } // Compute the desired delta movement for the handle. let delta: number; if (this._orientation === 'horizontal') { delta = position - handle.offsetLeft; } else { delta = position - handle.offsetTop; } // Bail if there is no handle movement. if (delta === 0) { return; } // Prevent widget resizing unless needed. for (let sizer of this._sizers) { if (sizer.size > 0) { sizer.sizeHint = sizer.size; } } // Adjust the sizers to reflect the handle movement. BoxEngine.adjust(this._sizers, index, delta); // Update the layout of the widgets. if (this.parent) { this.parent.update(); } } /** * Perform layout initialization which requires the parent widget. */ protected init(): void { this.parent!.dataset['orientation'] = this.orientation; this.parent!.dataset['alignment'] = this.alignment; super.init(); } /** * Attach a widget to the parent's DOM node. * * @param index - The current index of the widget in the layout. * * @param widget - The widget to attach to the parent. * * #### Notes * This is a reimplementation of the superclass method. */ protected attachWidget(index: number, widget: Widget): void { // Create the item, handle, and sizer for the new widget. let item = new LayoutItem(widget); let handle = Private.createHandle(this.renderer); let average = Private.averageSize(this._sizers); let sizer = Private.createSizer(average); // Insert the item, handle, and sizer into the internal arrays. ArrayExt.insert(this._items, index, item); ArrayExt.insert(this._sizers, index, sizer); ArrayExt.insert(this._handles, index, handle); // Send a `'before-attach'` message if the parent is attached. if (this.parent!.isAttached) { MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach); } // Add the widget and handle nodes to the parent. this.parent!.node.appendChild(widget.node); this.parent!.node.appendChild(handle); // Send an `'after-attach'` message if the parent is attached. if (this.parent!.isAttached) { MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach); } // Post a fit request for the parent widget. this.parent!.fit(); } /** * Move a widget in the parent's DOM node. * * @param fromIndex - The previous index of the widget in the layout. * * @param toIndex - The current index of the widget in the layout. * * @param widget - The widget to move in the parent. * * #### Notes * This is a reimplementation of the superclass method. */ protected moveWidget( fromIndex: number, toIndex: number, widget: Widget ): void { // Move the item, sizer, and handle for the widget. ArrayExt.move(this._items, fromIndex, toIndex); ArrayExt.move(this._sizers, fromIndex, toIndex); ArrayExt.move(this._handles, fromIndex, toIndex); // Post a fit request to the parent to show/hide last handle. this.parent!.fit(); } /** * Detach a widget from the parent's DOM node. * * @param index - The previous index of the widget in the layout. * * @param widget - The widget to detach from the parent. * * #### Notes * This is a reimplementation of the superclass method. */ protected detachWidget(index: number, widget: Widget): void { // Remove the item, handle, and sizer for the widget. let item = ArrayExt.removeAt(this._items, index); let handle = ArrayExt.removeAt(this._handles, index); ArrayExt.removeAt(this._sizers, index); // Send a `'before-detach'` message if the parent is attached. if (this.parent!.isAttached) { MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach); } // Remove the widget and handle nodes from the parent. this.parent!.node.removeChild(widget.node); this.parent!.node.removeChild(handle!); // Send an `'after-detach'` message if the parent is attached. if (this.parent!.isAttached) { MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach); } // Dispose of the layout item. item!.dispose(); // Post a fit request for the parent widget. this.parent!.fit(); } /** * A message handler invoked on a `'before-show'` message. */ protected onBeforeShow(msg: Message): void { super.onBeforeShow(msg); this.parent!.update(); } /** * A message handler invoked on a `'before-attach'` message. */ protected onBeforeAttach(msg: Message): void { super.onBeforeAttach(msg); this.parent!.fit(); } /** * A message handler invoked on a `'child-shown'` message. */ protected onChildShown(msg: Widget.ChildMessage): void { this.parent!.fit(); } /** * A message handler invoked on a `'child-hidden'` message. */ protected onChildHidden(msg: Widget.ChildMessage): void { this.parent!.fit(); } /** * A message handler invoked on a `'resize'` message. */ protected onResize(msg: Widget.ResizeMessage): void { if (this.parent!.isVisible) { this._update(msg.width, msg.height); } } /** * A message handler invoked on an `'update-request'` message. */ protected onUpdateRequest(msg: Message): void { if (this.parent!.isVisible) { this._update(-1, -1); } } /** * A message handler invoked on a `'fit-request'` message. */ protected onFitRequest(msg: Message): void { if (this.parent!.isAttached) { this._fit(); } } /** * Update the item position. * * @param i Item index * @param isHorizontal Whether the layout is horizontal or not * @param left Left position in pixels * @param top Top position in pixels * @param height Item height * @param width Item width * @param size Item size */ protected updateItemPosition( i: number, isHorizontal: boolean, left: number, top: number, height: number, width: number, size: number ): void { const item = this._items[i]; if (item.isHidden) { return; } // Fetch the style for the handle. let handleStyle = this._handles[i].style; // Update the widget and handle, and advance the relevant edge. if (isHorizontal) { left += this.widgetOffset; item.update(left, top, size, height); left += size; handleStyle.top = `${top}px`; handleStyle.left = `${left}px`; handleStyle.width = `${this._spacing}px`; handleStyle.height = `${height}px`; } else { top += this.widgetOffset; item.update(left, top, width, size); top += size; handleStyle.top = `${top}px`; handleStyle.left = `${left}px`; handleStyle.width = `${width}px`; handleStyle.height = `${this._spacing}px`; } } /** * Fit the layout to the total size required by the widgets. */ private _fit(): void { // Update the handles and track the visible widget count. let nVisible = 0; let lastHandleIndex = -1; for (let i = 0, n = this._items.length; i < n; ++i) { if (this._items[i].isHidden) { this._handles[i].classList.add('lm-mod-hidden'); /* <DEPRECATED> */ this._handles[i].classList.add('p-mod-hidden'); /* </DEPRECATED> */ } else { this._handles[i].classList.remove('lm-mod-hidden'); /* <DEPRECATED> */ this._handles[i].classList.remove('p-mod-hidden'); /* </DEPRECATED> */ lastHandleIndex = i; nVisible++; } } // Hide the handle for the last visible widget. if (lastHandleIndex !== -1) { this._handles[lastHandleIndex].classList.add('lm-mod-hidden'); /* <DEPRECATED> */ this._handles[lastHandleIndex].classList.add('p-mod-hidden'); /* </DEPRECATED> */ } // Update the fixed space for the visible items. this._fixed = this._spacing * Math.max(0, nVisible - 1) + this.widgetOffset * this._items.length; // Setup the computed minimum size. let horz = this._orientation === 'horizontal'; let minW = horz ? this._fixed : 0; let minH = horz ? 0 : this._fixed; // Update the sizers and computed size limits. for (let i = 0, n = this._items.length; i < n; ++i) { // Fetch the item and corresponding box sizer. let item = this._items[i]; let sizer = this._sizers[i]; // Prevent resizing unless necessary. if (sizer.size > 0) { sizer.sizeHint = sizer.size; } // If the item is hidden, it should consume zero size. if (item.isHidden) { sizer.minSize = 0; sizer.maxSize = 0; continue; } // Update the size limits for the item. item.fit(); // Update the stretch factor. sizer.stretch = SplitLayout.getStretch(item.widget); // Update the sizer limits and computed min size. if (horz) { sizer.minSize = item.minWidth; sizer.maxSize = item.maxWidth; minW += item.minWidth; minH = Math.max(minH, item.minHeight); } else { sizer.minSize = item.minHeight; sizer.maxSize = item.maxHeight; minH += item.minHeight; minW = Math.max(minW, item.minWidth); } } // Update the box sizing and add it to the computed min size. let box = (this._box = ElementExt.boxSizing(this.parent!.node)); minW += box.horizontalSum; minH += box.verticalSum; // Update the parent's min size constraints. let style = this.parent!.node.style; style.minWidth = `${minW}px`; style.minHeight = `${minH}px`; // Set the dirty flag to ensure only a single update occurs. this._dirty = true; // Notify the ancestor that it should fit immediately. This may // cause a resize of the parent, fulfilling the required update. if (this.parent!.parent) { MessageLoop.sendMessage(this.parent!.parent!, Widget.Msg.FitRequest); } // If the dirty flag is still set, the parent was not resized. // Trigger the required update on the parent widget immediately. if (this._dirty) { MessageLoop.sendMessage(this.parent!, Widget.Msg.UpdateRequest); } } /** * Update the layout position and size of the widgets. * * The parent offset dimensions should be `-1` if unknown. */ private _update(offsetWidth: number, offsetHeight: number): void { // Clear the dirty flag to indicate the update occurred. this._dirty = false; // Compute the visible item count. let nVisible = 0; for (let i = 0, n = this._items.length; i < n; ++i) { nVisible += +!this._items[i].isHidden; } // Bail early if there are no visible items to layout. if (nVisible === 0 && this.widgetOffset === 0) { return; } // Measure the parent if the offset dimensions are unknown. if (offsetWidth < 0) { offsetWidth = this.parent!.node.offsetWidth; } if (offsetHeight < 0) { offsetHeight = this.parent!.node.offsetHeight; } // Ensure the parent box sizing data is computed. if (!this._box) { this._box = ElementExt.boxSizing(this.parent!.node); } // Compute the actual layout bounds adjusted for border and padding. let top = this._box.paddingTop; let left = this._box.paddingLeft; let width = offsetWidth - this._box.horizontalSum; let height = offsetHeight - this._box.verticalSum; // Set up the variables for justification and alignment offset. let extra = 0; let offset = 0; let horz = this._orientation === 'horizontal'; if (nVisible > 0) { // Compute the adjusted layout space. let space: number; if (horz) { // left += this.widgetOffset; space = Math.max(0, width - this._fixed); } else { // top += this.widgetOffset; space = Math.max(0, height - this._fixed); } // Scale the size hints if they are normalized. if (this._hasNormedSizes) { for (let sizer of this._sizers) { sizer.sizeHint *= space; } this._hasNormedSizes = false; } // Distribute the layout space to the box sizers. let delta = BoxEngine.calc(this._sizers, space); // Account for alignment if there is extra layout space. if (delta > 0) { switch (this._alignment) { case 'start': break; case 'center': extra = 0; offset = delta / 2; break; case 'end': extra = 0; offset = delta; break; case 'justify': extra = delta / nVisible; offset = 0; break; default: throw 'unreachable'; } } } // Layout the items using the computed box sizes. for (let i = 0, n = this._items.length; i < n; ++i) { // Fetch the item. const item = this._items[i]; // Fetch the computed size for the widget. const size = item.isHidden ? 0 : this._sizers[i].size + extra; this.updateItemPosition( i, horz, horz ? left + offset : left, horz ? top : top + offset, height, width, size ); const fullOffset = this.widgetOffset + (this._handles[i].classList.contains('lm-mod-hidden') ? 0 : this._spacing); if (horz) { left += size + fullOffset; } else { top += size + fullOffset; } } } protected widgetOffset = 0; private _fixed = 0; private _spacing = 4; private _dirty = false; private _hasNormedSizes = false; private _sizers: BoxSizer[] = []; private _items: LayoutItem[] = []; private _handles: HTMLDivElement[] = []; private _box: ElementExt.IBoxSizing | null = null; private _alignment: SplitLayout.Alignment = 'start'; private _orientation: SplitLayout.Orientation = 'horizontal'; } /** * The namespace for the `SplitLayout` class statics. */ export namespace SplitLayout { /** * A type alias for a split layout orientation. */ export type Orientation = 'horizontal' | 'vertical'; /** * A type alias for a split layout alignment. */ export type Alignment = 'start' | 'center' | 'end' | 'justify'; /** * An options object for initializing a split layout. */ export interface IOptions { /** * The renderer to use for the split layout. */ renderer: IRenderer; /** * The orientation of the layout. * * The default is `'horizontal'`. */ orientation?: Orientation; /** * The content alignment of the layout. * * The default is `'start'`. */ alignment?: Alignment; /** * The spacing between items in the layout. * * The default is `4`. */ spacing?: number; } /** * A renderer for use with a split layout. */ export interface IRenderer { /** * Create a new handle for use with a split layout. * * @returns A new handle element. */ createHandle(): HTMLDivElement; } /** * Get the split layout stretch factor for the given widget. * * @param widget - The widget of interest. * * @returns The split layout stretch factor for the widget. */ export function getStretch(widget: Widget): number { return Private.stretchProperty.get(widget); } /** * Set the split layout stretch factor for the given widget. * * @param widget - The widget of interest. * * @param value - The value for the stretch factor. */ export function setStretch(widget: Widget, value: number): void { Private.stretchProperty.set(widget, value); } } /** * The namespace for the module implementation details. */ namespace Private { /** * The property descriptor for a widget stretch factor. */ export const stretchProperty = new AttachedProperty<Widget, number>({ name: 'stretch', create: () => 0, coerce: (owner, value) => Math.max(0, Math.floor(value)), changed: onChildSizingChanged, }); /** * Create a new box sizer with the given size hint. */ export function createSizer(size: number): BoxSizer { let sizer = new BoxSizer(); sizer.sizeHint = Math.floor(size); return sizer; } /** * Create a new split handle node using the given renderer. */ export function createHandle( renderer: SplitLayout.IRenderer ): HTMLDivElement { let handle = renderer.createHandle(); handle.style.position = 'absolute'; return handle; } /** * Compute the average size of an array of box sizers. */ export function averageSize(sizers: BoxSizer[]): number { return sizers.reduce((v, s) => v + s.size, 0) / sizers.length || 0; } /** * Normalize an array of values. */ export function normalize(values: number[]): number[] { let n = values.length; if (n === 0) { return []; } let sum = values.reduce((a, b) => a + Math.abs(b), 0); return sum === 0 ? values.map((v) => 1 / n) : values.map((v) => v / sum); } /** * The change handler for the attached sizing properties. */ function onChildSizingChanged(child: Widget): void { if (child.parent && child.parent.layout instanceof SplitLayout) { child.parent.fit(); } } }
the_stack
import { useEffect, useRef, useState, useMemo, useCallback, forwardRef, useImperativeHandle, } from "react"; // @ts-expect-error no type definition import rangeAtIndex from "range-at-index"; import type { Renderer } from "./renderers"; const useForceRefresh = () => { const setState = useState(0)[1]; return useCallback(() => setState((p) => p + 1), []); }; const STYLE_KEYS: (keyof React.CSSProperties)[] = [ "direction", "padding", "paddingTop", "paddingBottom", "paddingLeft", "paddingRight", "margin", "marginTop", "marginBottom", "marginLeft", "marginRight", "border", "borderWidth", "borderTopWidth", "borderBottomWidth", "borderLeftWidth", "borderRightWidth", "borderStyle", "borderTopStyle", "borderBottomStyle", "borderLeftStyle", "borderRightStyle", "fontSize", "fontFamily", "fontStyle", "fontVariant", "fontWeight", "fontStretch", "fontSizeAdjust", "textAlign", "textTransform", "textIndent", "letterSpacing", "wordSpacing", "lineHeight", "whiteSpace", "wordBreak", "overflowWrap", "tabSize", "MozTabSize", ]; const getPropertyValue = (style: CSSStyleDeclaration, key: string): string => { return style.getPropertyValue(key); }; const setProperty = ( style: CSSStyleDeclaration, key: string, value: string ) => { style.setProperty(key, value); }; const getValueFromStyle = (style: CSSStyleDeclaration, key: string): number => { const value = getPropertyValue(style, key); if (!value) { return 0; } else { return parseInt(value, 10); } }; const getStyle = getComputedStyle; const getVerticalPadding = (style: CSSStyleDeclaration): number => { return ( getValueFromStyle(style, "padding-top") + getValueFromStyle(style, "padding-bottom") + getValueFromStyle(style, "border-top") + getValueFromStyle(style, "border-bottom") ); }; const getHorizontalPadding = (style: CSSStyleDeclaration): number => { return ( getValueFromStyle(style, "padding-left") + getValueFromStyle(style, "padding-right") + getValueFromStyle(style, "border-left") + getValueFromStyle(style, "border-right") ); }; const setRangeText = ( el: HTMLTextAreaElement, text: string, start: number, end: number, preserve?: SelectionMode ) => { if (el.setRangeText) { el.setRangeText(text, start, end, preserve); } else { el.focus(); el.selectionStart = start; el.selectionEnd = end; document.execCommand("insertText", false, text); } // Invoke onChange to lift state up el.dispatchEvent(new Event("input", { bubbles: true })); }; const getPointedElement = ( textarea: HTMLTextAreaElement, backdrop: HTMLDivElement, e: React.MouseEvent ): HTMLElement | null => { const POINTER_EVENTS = "pointer-events"; const textareaStyle = textarea.style; const backdropStyle = backdrop.style; const prev = getPropertyValue(textareaStyle, POINTER_EVENTS); const backPrev = getPropertyValue(backdropStyle, POINTER_EVENTS); setProperty(textareaStyle, POINTER_EVENTS, "none"); setProperty(backdropStyle, POINTER_EVENTS, "auto"); const pointed = document.elementFromPoint( e.clientX, e.clientY ) as HTMLElement | null; setProperty(textareaStyle, POINTER_EVENTS, prev); setProperty(backdropStyle, POINTER_EVENTS, backPrev); if (isInsideBackdrop(pointed, backdrop)) { return pointed; } else { return null; } }; const isInsideBackdrop = ( pointed: HTMLElement | null, backdrop: HTMLDivElement ): boolean => !!pointed && backdrop !== pointed && backdrop.contains(pointed); const dispatchMouseEvent = ( target: HTMLElement, type: string, init: MouseEventInit ) => { target.dispatchEvent(new MouseEvent(type, init)); }; const dispatchClonedMouseEvent = (pointed: HTMLElement, e: MouseEvent) => { dispatchMouseEvent(pointed, e.type, e); }; const dispatchMouseMoveEvent = ( pointed: HTMLElement | null, prevPointed: React.MutableRefObject<HTMLElement | null>, e: MouseEvent ) => { if (pointed) { dispatchClonedMouseEvent(pointed, e); } if (prevPointed.current !== pointed) { dispatchMouseOutEvent(prevPointed, e, pointed); if (pointed) { dispatchMouseEvent(pointed, "mouseover", e); } } }; const dispatchMouseOutEvent = ( prevPointed: React.MutableRefObject<HTMLElement | null>, e: MouseEvent, pointed: HTMLElement | null ) => { if (prevPointed.current) { dispatchMouseEvent(prevPointed.current, "mouseout", e); } prevPointed.current = pointed; }; const getSelectionStart = ( el: HTMLTextAreaElement, compositionEvent: CompositionEvent | null ): number => { let pos = el.selectionStart; if (compositionEvent) { pos = Math.min(pos, el.selectionEnd - compositionEvent.data.length); } return pos; }; const getSelectionEnd = ( el: HTMLTextAreaElement, compositionEvent: CompositionEvent | null ): number => { let pos = el.selectionEnd; if (compositionEvent) { pos = Math.min(pos, el.selectionStart + compositionEvent.data.length); } return pos; }; const stopPropagation = (event: React.MouseEvent) => { event.stopPropagation(); }; // for caret position detection const CARET_DETECTOR = <span style={{ color: "transparent" }}>{"\u200b"}</span>; export type CaretPosition = | { focused: false; selectionStart: number; selectionEnd: number; } | { focused: true; selectionStart: number; selectionEnd: number; top: number; left: number; height: number; }; export type RichTextareaHandle = { ref: React.RefObject<HTMLTextAreaElement>; selectionStart: number; selectionEnd: number; focus: () => void; blur: () => void; select: () => void; setSelectionRange: ( start: number, end: number, direction?: "forward" | "backward" | "none" ) => void; setRangeText: ( text: string, start: number, end: number, preserve?: SelectionMode ) => void; }; export type RichTextareaProps = Omit< JSX.IntrinsicElements["textarea"], "value" | "defaultValue" | "children" > & { value: string; children?: Renderer; autoHeight?: boolean; onSelectionChange?: (pos: CaretPosition, value: string) => void; }; export const RichTextarea = forwardRef<RichTextareaHandle, RichTextareaProps>( ( { children: render, value, autoHeight, style, onScroll, onInput, onCompositionStart, onCompositionUpdate, onCompositionEnd, onKeyDown, onClick, onMouseDown, onMouseUp, onMouseMove, onMouseLeave, onFocus, onBlur, onSelectionChange, ...props }, propRef ): React.ReactElement => { const ref = useRef<HTMLTextAreaElement>(null); const backdropRef = useRef<HTMLDivElement>(null); const [[left, top], setPos] = useState<[left: number, top: number]>([0, 0]); const [[width, height, hPadding, vPadding], setRect] = useState< [width: number, height: number, hPadding: number, vPadding: number] >([0, 0, 0, 0]); const refresh = useForceRefresh(); const [focused, setFocused] = useState<boolean>(false); const compositionRef = useRef<CompositionEvent | null>(null); const caretColorRef = useRef(""); const pointedRef = useRef<HTMLElement | null>(null); const selectionStart = ref.current && getSelectionStart(ref.current, compositionRef.current); const selectionEnd = ref.current && getSelectionEnd(ref.current, compositionRef.current); const totalWidth = width + hPadding; const totalHeight = height + vPadding; const setCaretPosition = useCallback(() => { if (!onSelectionChange) return; setTimeout(() => { refresh(); }); }, [onSelectionChange]); useImperativeHandle( propRef, () => ({ ref: ref, get selectionStart() { if (!ref.current) return 0; return getSelectionStart(ref.current, compositionRef.current); }, get selectionEnd() { if (!ref.current) return 0; return getSelectionEnd(ref.current, compositionRef.current); }, focus: () => { if (!ref.current) return; ref.current.focus(); }, blur: () => { if (!ref.current) return; ref.current.blur(); }, select: () => { if (!ref.current) return; ref.current.select(); }, setSelectionRange: (...args) => { if (!ref.current) return; ref.current.focus(); ref.current.setSelectionRange(...args); }, setRangeText: (...args) => { if (!ref.current) return; setRangeText(ref.current, ...args); }, }), [ref] ); useEffect(() => { if (!ref.current) return; const observer = new ResizeObserver(([entry]) => { const contentRect = entry!.contentRect; if (!ref.current) return; const style = getStyle(ref.current); setRect([ contentRect.width, contentRect.height, getHorizontalPadding(style), getVerticalPadding(style), ]); }); observer.observe(ref.current); return () => { observer.disconnect(); }; }, []); useEffect(() => { const textarea = ref.current; const backdrop = backdropRef.current; if (!backdrop || !textarea) return; const s = getStyle(textarea); const textareaStyle = textarea.style; const backdropStyle = backdrop.style; if (!caretColorRef.current) { caretColorRef.current = getPropertyValue(s, "color"); } STYLE_KEYS.forEach((k) => { backdropStyle[k as any] = s[k as any]!; }); textareaStyle.color = backdropStyle.borderColor = "transparent"; textareaStyle.caretColor = style?.caretColor || caretColorRef.current; }, [style]); useEffect(() => { if (selectionStart == null || selectionEnd == null || !onSelectionChange) return; if (!focused && !compositionRef.current) { onSelectionChange( { focused: false, selectionStart: selectionStart, selectionEnd: selectionEnd, }, value ); } else { const range = rangeAtIndex( backdropRef.current, selectionStart, selectionStart + 1 ) as Range; const rect = range.getBoundingClientRect(); onSelectionChange( { focused: true, top: rect.top, left: rect.left, height: rect.height, selectionStart: selectionStart, selectionEnd: selectionEnd, }, value ); } }, [focused, selectionStart, selectionEnd]); useEffect(() => { const textarea = ref.current; if (!autoHeight || !textarea) return; textarea.style.height = "auto"; textarea.style.height = `${textarea.scrollHeight}px`; }); return ( <div style={useMemo( (): React.CSSProperties => ({ display: "inline-block", position: "relative", width: totalWidth, height: totalHeight, }), [totalWidth, totalHeight] )} > <div style={useMemo((): React.CSSProperties => { const s: React.CSSProperties = { position: "absolute", overflow: "hidden", top: 0, left: 0, width: totalWidth, height: totalHeight, }; if (!style) return s; if (style.background) s.background = style.background; if (style.backgroundColor) s.backgroundColor = style.backgroundColor; return s; }, [totalWidth, totalHeight, style])} > <div ref={backdropRef} aria-hidden style={useMemo( (): React.CSSProperties => ({ width, transform: `translate(${-left}px, ${-top}px)`, pointerEvents: "none", userSelect: "none", msUserSelect: "none", WebkitUserSelect: "none", // https://stackoverflow.com/questions/2545542/font-size-rendering-inconsistencies-on-an-iphone textSizeAdjust: "100%", WebkitTextSizeAdjust: "100%", }), [left, top, width] )} // Stop propagation of events dispatched on backdrop onClick={stopPropagation} onMouseDown={stopPropagation} onMouseUp={stopPropagation} onMouseOver={stopPropagation} onMouseOut={stopPropagation} onMouseMove={stopPropagation} > {useMemo(() => (render ? render(value) : value), [value, render])} {CARET_DETECTOR} </div> </div> <textarea {...props} ref={ref} value={value} style={useMemo( () => ({ ...style, background: "transparent", margin: 0, // Fixed bug that sometimes texts disappear in Chrome for unknown reason position: "absolute", }), [style] )} onScroll={useCallback( (e: React.UIEvent<HTMLTextAreaElement>) => { setPos([e.currentTarget.scrollLeft, e.currentTarget.scrollTop]); onScroll?.(e); }, [onScroll] )} onInput={useCallback( (e: React.FormEvent<HTMLTextAreaElement>) => { onInput?.(e); setCaretPosition(); }, [onInput, setCaretPosition] )} onCompositionStart={useCallback( (e: React.CompositionEvent<HTMLTextAreaElement>) => { compositionRef.current = e.nativeEvent; onCompositionStart?.(e); }, [onCompositionStart] )} onCompositionUpdate={useCallback( (e: React.CompositionEvent<HTMLTextAreaElement>) => { compositionRef.current = e.nativeEvent; onCompositionUpdate?.(e); }, [onCompositionUpdate] )} onCompositionEnd={useCallback( (e: React.CompositionEvent<HTMLTextAreaElement>) => { compositionRef.current = null; onCompositionEnd?.(e); }, [onCompositionEnd] )} onKeyDown={useCallback( (e: React.KeyboardEvent<HTMLTextAreaElement>) => { // Ignore keydown events during IME composition. // Safari sometimes fires keydown event after compositionend so also ignore it. // https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event#ignoring_keydown_during_ime_composition if (e.nativeEvent.isComposing || e.nativeEvent.keyCode === 229) { return; } onKeyDown?.(e); setCaretPosition(); }, [onKeyDown, setCaretPosition] )} onClick={useCallback( (e: React.MouseEvent<HTMLTextAreaElement>) => { onClick?.(e); const textarea = ref.current; const backdrop = backdropRef.current; if (!textarea || !backdrop) return; const pointed = getPointedElement(textarea, backdrop, e); if (pointed) { dispatchClonedMouseEvent(pointed, e.nativeEvent); } }, [onClick] )} onMouseDown={useCallback( (e: React.MouseEvent<HTMLTextAreaElement>) => { onMouseDown?.(e); setCaretPosition(); const textarea = ref.current; const backdrop = backdropRef.current; if (!textarea || !backdrop) return; const pointed = getPointedElement(textarea, backdrop, e); if (pointed) { dispatchClonedMouseEvent(pointed, e.nativeEvent); } }, [onMouseDown, setCaretPosition] )} onMouseUp={useCallback( (e: React.MouseEvent<HTMLTextAreaElement>) => { onMouseUp?.(e); setCaretPosition(); const textarea = ref.current; const backdrop = backdropRef.current; if (!textarea || !backdrop) return; const pointed = getPointedElement(textarea, backdrop, e); if (pointed) { dispatchClonedMouseEvent(pointed, e.nativeEvent); } }, [onMouseUp, setCaretPosition] )} onMouseMove={useCallback( (e: React.MouseEvent<HTMLTextAreaElement>) => { onMouseMove?.(e); const textarea = ref.current; const backdrop = backdropRef.current; if (!textarea || !backdrop) return; const pointed = getPointedElement(textarea, backdrop, e); dispatchMouseMoveEvent(pointed, pointedRef, e.nativeEvent); }, [onMouseMove] )} onMouseLeave={useCallback( (e: React.MouseEvent<HTMLTextAreaElement>) => { onMouseLeave?.(e); dispatchMouseOutEvent(pointedRef, e.nativeEvent, null); }, [onMouseLeave] )} onFocus={useCallback( (e: React.FocusEvent<HTMLTextAreaElement>) => { onFocus?.(e); setFocused(true); }, [onFocus] )} onBlur={useCallback( (e: React.FocusEvent<HTMLTextAreaElement>) => { onBlur?.(e); setFocused(false); }, [onBlur] )} /> </div> ); } );
the_stack
import { Component, ViewChild } from '@angular/core'; import { fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { FormBuilder, FormsModule, ReactiveFormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { IgxRippleModule } from '../directives/ripple/ripple.directive'; import { IgxCheckboxComponent } from './checkbox.component'; import { configureTestSuite } from '../test-utils/configure-suite'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; describe('IgxCheckbox', () => { configureTestSuite(); beforeAll(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ InitCheckboxComponent, CheckboxSimpleComponent, CheckboxDisabledComponent, CheckboxReadonlyComponent, CheckboxIndeterminateComponent, CheckboxRequiredComponent, CheckboxExternalLabelComponent, CheckboxInvisibleLabelComponent, CheckboxDisabledTransitionsComponent, CheckboxFormGroupComponent, IgxCheckboxComponent ], imports: [FormsModule, ReactiveFormsModule, IgxRippleModule, NoopAnimationsModule] }) .compileComponents(); })); it('Initializes a checkbox', () => { const fixture = TestBed.createComponent(InitCheckboxComponent); fixture.detectChanges(); const checkbox = fixture.componentInstance.cb; const nativeCheckbox = checkbox.nativeCheckbox.nativeElement; const nativeLabel = checkbox.nativeLabel.nativeElement; const placeholderLabel = fixture.debugElement.query(By.css('.igx-checkbox__label')).nativeElement; expect(nativeCheckbox).toBeTruthy(); expect(nativeCheckbox.id).toEqual('igx-checkbox-0-input'); expect(nativeCheckbox.getAttribute('aria-label')).toEqual(null); expect(nativeCheckbox.getAttribute('aria-labelledby')).toMatch('igx-checkbox-0-label'); expect(nativeLabel).toBeTruthy(); // No longer have a for attribute to not propagate clicks to the native checkbox // expect(nativeLabel.getAttribute('for')).toEqual('igx-checkbox-0-input'); expect(placeholderLabel.textContent.trim()).toEqual('Init'); expect(placeholderLabel.classList).toContain('igx-checkbox__label'); expect(placeholderLabel.getAttribute('id')).toEqual('igx-checkbox-0-label'); // When aria-label is present, aria-labeledby shouldn't be checkbox.ariaLabel = 'New Label'; fixture.detectChanges(); expect(nativeCheckbox.getAttribute('aria-labelledby')).toEqual(null); expect(nativeCheckbox.getAttribute('aria-label')).toMatch('New Label'); }); it('Initializes with ngModel', fakeAsync(() => { const fixture = TestBed.createComponent(CheckboxSimpleComponent); fixture.detectChanges(); const testInstance = fixture.componentInstance; const checkboxInstance = testInstance.cb; const nativeCheckbox = checkboxInstance.nativeCheckbox.nativeElement; fixture.detectChanges(); expect(nativeCheckbox.checked).toBe(false); expect(checkboxInstance.checked).toBe(null); testInstance.subscribed = true; checkboxInstance.name = 'my-checkbox'; // One change detection cycle for updating our checkbox fixture.detectChanges(); tick(); expect(checkboxInstance.checked).toBe(true); // Now one more change detection cycle to update the native checkbox fixture.detectChanges(); tick(); expect(nativeCheckbox.checked).toBe(true); expect(checkboxInstance.name).toEqual('my-checkbox'); })); it('Initializes with form group', () => { const fixture = TestBed.createComponent(CheckboxFormGroupComponent); fixture.detectChanges(); const testInstance = fixture.componentInstance; const checkboxInstance = testInstance.cb; const form = testInstance.myForm; form.setValue({ checkbox: true }); expect(checkboxInstance.checked).toBe(true); form.reset(); expect(checkboxInstance.checked).toBe(null); }); it('Initializes with external label', () => { const fixture = TestBed.createComponent(CheckboxExternalLabelComponent); const checkboxInstance = fixture.componentInstance.cb; const nativeCheckbox = checkboxInstance.nativeCheckbox.nativeElement; const externalLabel = fixture.debugElement.query(By.css('#my-label')).nativeElement; fixture.detectChanges(); expect(nativeCheckbox.getAttribute('aria-labelledby')).toMatch(externalLabel.getAttribute('id')); expect(externalLabel.textContent).toMatch(fixture.componentInstance.label); }); it('Initializes with invisible label', () => { const fixture = TestBed.createComponent(CheckboxInvisibleLabelComponent); const checkboxInstance = fixture.componentInstance.cb; const nativeCheckbox = checkboxInstance.nativeCheckbox.nativeElement; fixture.detectChanges(); expect(nativeCheckbox.getAttribute('aria-label')).toMatch(fixture.componentInstance.label); }); it('Positions label before and after checkbox', () => { const fixture = TestBed.createComponent(CheckboxSimpleComponent); const checkboxInstance = fixture.componentInstance.cb; const placeholderLabel = checkboxInstance.placeholderLabel.nativeElement; const labelStyles = window.getComputedStyle(placeholderLabel); fixture.detectChanges(); expect(labelStyles.order).toEqual('0'); checkboxInstance.labelPosition = 'before'; fixture.detectChanges(); expect(labelStyles.order).toEqual('-1'); }); it('Indeterminate state', fakeAsync(() => { const fixture = TestBed.createComponent(CheckboxIndeterminateComponent); const testInstance = fixture.componentInstance; const checkboxInstance = testInstance.cb; const nativeCheckbox = checkboxInstance.nativeCheckbox.nativeElement; const nativeLabel = checkboxInstance.nativeLabel.nativeElement; // Before any changes indeterminate should be true fixture.detectChanges(); expect(checkboxInstance.indeterminate).toBe(true); expect(nativeCheckbox.indeterminate).toBe(true); testInstance.subscribed = true; fixture.detectChanges(); tick(); // First change detection should update our checkbox state and API call should not change indeterminate expect(checkboxInstance.checked).toBe(true); expect(checkboxInstance.indeterminate).toBe(true); // Second change detection should update native checkbox state but indeterminate should not change fixture.detectChanges(); tick(); expect(nativeCheckbox.indeterminate).toBe(true); expect(nativeCheckbox.checked).toBe(true); // Should not change the state nativeCheckbox.dispatchEvent(new Event('change')); fixture.detectChanges(); expect(nativeCheckbox.indeterminate).toBe(true); expect(checkboxInstance.checked).toBe(true); expect(nativeCheckbox.checked).toBe(true); // Should update the state on click nativeLabel.click(); fixture.detectChanges(); expect(nativeCheckbox.indeterminate).toBe(false); expect(checkboxInstance.checked).toBe(false); expect(nativeCheckbox.checked).toBe(false); // Should update the state again on click nativeLabel.click(); fixture.detectChanges(); expect(nativeCheckbox.indeterminate).toBe(false); expect(checkboxInstance.checked).toBe(true); expect(nativeCheckbox.checked).toBe(true); // Should be able to set indeterminate again checkboxInstance.indeterminate = true; fixture.detectChanges(); expect(nativeCheckbox.indeterminate).toBe(true); expect(checkboxInstance.checked).toBe(true); expect(nativeCheckbox.checked).toBe(true); })); it('Disabled state', () => { const fixture = TestBed.createComponent(CheckboxDisabledComponent); const testInstance = fixture.componentInstance; const checkboxInstance = testInstance.cb; const nativeCheckbox = checkboxInstance.nativeCheckbox.nativeElement; const nativeLabel = checkboxInstance.nativeLabel.nativeElement; const placeholderLabel = checkboxInstance.placeholderLabel.nativeElement; fixture.detectChanges(); expect(checkboxInstance.disabled).toBe(true); expect(nativeCheckbox.disabled).toBe(true); nativeCheckbox.dispatchEvent(new Event('change')); nativeLabel.click(); placeholderLabel.click(); fixture.detectChanges(); // Should not update expect(checkboxInstance.checked).toBe(null); expect(testInstance.subscribed).toBe(false); }); it('Readonly state', () => { const fixture = TestBed.createComponent(CheckboxReadonlyComponent); const testInstance = fixture.componentInstance; const checkboxInstance = testInstance.cb; const nativeCheckbox = checkboxInstance.nativeCheckbox.nativeElement; const nativeLabel = checkboxInstance.nativeLabel.nativeElement; const placeholderLabel = checkboxInstance.placeholderLabel.nativeElement; fixture.detectChanges(); expect(checkboxInstance.readonly).toBe(true); expect(testInstance.subscribed).toBe(false); nativeCheckbox.dispatchEvent(new Event('change')); fixture.detectChanges(); // Should not update expect(testInstance.subscribed).toBe(false); nativeLabel.click(); fixture.detectChanges(); // Should not update expect(testInstance.subscribed).toBe(false); placeholderLabel.click(); fixture.detectChanges(); // Should not update expect(testInstance.subscribed).toBe(false); nativeCheckbox.click(); fixture.detectChanges(); // Should not update expect(testInstance.subscribed).toBe(false); expect(checkboxInstance.indeterminate).toBe(true); }); it('Should be able to enable/disable CSS transitions', () => { const fixture = TestBed.createComponent(CheckboxDisabledTransitionsComponent); const testInstance = fixture.componentInstance; const checkboxInstance = testInstance.cb; const checkboxHost = fixture.debugElement.query(By.css('igx-checkbox')).nativeElement; fixture.detectChanges(); expect(checkboxInstance.disableTransitions).toBe(true); expect(checkboxHost.classList).toContain('igx-checkbox--plain'); testInstance.cb.disableTransitions = false; fixture.detectChanges(); expect(checkboxHost.classList).not.toContain('igx-checkbox--plain'); }); it('Required state', () => { const fixture = TestBed.createComponent(CheckboxRequiredComponent); const testInstance = fixture.componentInstance; const checkboxInstance = testInstance.cb; const nativeCheckbox = checkboxInstance.nativeCheckbox.nativeElement; fixture.detectChanges(); expect(checkboxInstance.required).toBe(true); expect(nativeCheckbox.required).toBeTruthy(); checkboxInstance.required = false; fixture.detectChanges(); expect(checkboxInstance.required).toBe(false); expect(nativeCheckbox.required).toBe(false); }); it('Event handling', () => { const fixture = TestBed.createComponent(CheckboxSimpleComponent); const testInstance = fixture.componentInstance; const checkboxInstance = testInstance.cb; const cbxEl = fixture.debugElement.query(By.directive(IgxCheckboxComponent)).nativeElement; const nativeCheckbox = checkboxInstance.nativeCheckbox.nativeElement; const nativeLabel = checkboxInstance.nativeLabel.nativeElement; const placeholderLabel = checkboxInstance.placeholderLabel.nativeElement; fixture.detectChanges(); expect(checkboxInstance.focused).toBe(false); cbxEl.dispatchEvent(new KeyboardEvent('keyup')); fixture.detectChanges(); expect(checkboxInstance.focused).toBe(true); nativeCheckbox.dispatchEvent(new Event('blur')); fixture.detectChanges(); expect(checkboxInstance.focused).toBe(false); nativeLabel.click(); fixture.detectChanges(); expect(testInstance.changeEventCalled).toBe(true); expect(testInstance.subscribed).toBe(true); expect(testInstance.clickCounter).toEqual(1); placeholderLabel.click(); fixture.detectChanges(); expect(testInstance.changeEventCalled).toBe(true); expect(testInstance.subscribed).toBe(false); expect(testInstance.clickCounter).toEqual(2); }); describe('EditorProvider', () => { it('Should return correct edit element', () => { const fixture = TestBed.createComponent(CheckboxSimpleComponent); fixture.detectChanges(); const instance = fixture.componentInstance.cb; const editElement = fixture.debugElement.query(By.css('.igx-checkbox__input')).nativeElement; expect(instance.getEditElement()).toBe(editElement); }); }); }); @Component({ template: `<igx-checkbox #cb>Init</igx-checkbox>` }) class InitCheckboxComponent { @ViewChild('cb', { static: true }) public cb: IgxCheckboxComponent; } @Component({ template: `<igx-checkbox #cb (change)="onChange()" (click)="onClick()" [(ngModel)]="subscribed">Simple</igx-checkbox>` }) class CheckboxSimpleComponent { @ViewChild('cb', { static: true }) public cb: IgxCheckboxComponent; public changeEventCalled = false; public subscribed = false; public clickCounter = 0; public onChange() { this.changeEventCalled = true; } public onClick() { this.clickCounter++; } } @Component({ template: `<igx-checkbox #cb [(ngModel)]="subscribed" [indeterminate]="true" >Indeterminate</igx-checkbox>`}) class CheckboxIndeterminateComponent { @ViewChild('cb', { static: true }) public cb: IgxCheckboxComponent; public subscribed = false; } @Component({ template: `<igx-checkbox #cb required>Required</igx-checkbox>` }) class CheckboxRequiredComponent { @ViewChild('cb', { static: true }) public cb: IgxCheckboxComponent; } @Component({ template: `<igx-checkbox #cb [(ngModel)]="subscribed" [disabled]="true">Disabled</igx-checkbox>`}) class CheckboxDisabledComponent { @ViewChild('cb', { static: true }) public cb: IgxCheckboxComponent; public subscribed = false; } @Component({ template: `<igx-checkbox #cb [(ngModel)]="subscribed" [checked]="subscribed" [indeterminate]="true" [readonly]="true">Readonly</igx-checkbox>`}) class CheckboxReadonlyComponent { @ViewChild('cb', { static: true }) public cb: IgxCheckboxComponent; public subscribed = false; } @Component({ template: `<p id="my-label">{{label}}</p> <igx-checkbox #cb aria-labelledby="my-label"></igx-checkbox>` }) class CheckboxExternalLabelComponent { @ViewChild('cb', { static: true }) public cb: IgxCheckboxComponent; public label = 'My Label'; } @Component({ template: `<igx-checkbox #cb [aria-label]="label"></igx-checkbox>` }) class CheckboxInvisibleLabelComponent { @ViewChild('cb', { static: true }) public cb: IgxCheckboxComponent; public label = 'Invisible Label'; } @Component({ template: `<igx-checkbox #cb [disableTransitions]="true"></igx-checkbox>` }) class CheckboxDisabledTransitionsComponent { @ViewChild('cb', { static: true }) public cb: IgxCheckboxComponent; } @Component({ template: `<form [formGroup]="myForm"><igx-checkbox #cb formControlName="checkbox">Form Group</igx-checkbox></form>` }) class CheckboxFormGroupComponent { @ViewChild('cb', { static: true }) public cb: IgxCheckboxComponent; public myForm = this.fb.group({ checkbox: [''] }); constructor(private fb: FormBuilder) {} }
the_stack
import { map } from 'rxjs/operators'; import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { Observable, of as observableOf } from 'rxjs'; import { reduce, includes, concat } from 'lodash/fp'; import { sortBy } from 'lodash'; import { ChefEvent, RespChefEvent, RespEventCollection, EventFeedFilter, RespChefEventCollection, GuitarString, GuitarStringItem, ResponseGuitarStringCollection, GuitarStringCollection, RespEventCounts, EventTypeCount, EventTaskCount, ChefEventCollection, Chicklet } from '../../types/types'; import { initialState } from './event-feed.reducer'; import { environment } from '../../../environments/environment'; import * as moment from 'moment/moment'; const GATEWAY_URL = environment.gateway_url; const CONFIG_MGMT_URL = environment.config_mgmt_url; const ENTITY_TYPE_TAG = 'event-type'; const ENTITY_TYPE_DATA_BAG_ITEM_TAG = 'item'; const ENTITY_TYPE_DATA_BAG_TAG = 'bag'; const ENTITY_TYPE_COOKBOOK_TAG = 'cookbook'; const ENTITY_TYPE_COOKBOOK_VERSION_TAG = 'version'; const ENTITY_TYPE_ARTIFACT_COOKBOOK_VERSION_TAG = 'cookbook_artifact_version'; @Injectable() export class EventFeedService { constructor( private httpClient: HttpClient ) {} getEventFeed(filters: EventFeedFilter): Observable<ChefEventCollection> { const url = `${GATEWAY_URL}/eventfeed`; const options = { params: this.buildEventFeedURLSearchParams(filters, null) }; return this.httpClient .get<RespChefEventCollection>(url, options).pipe( map((res) => this.convertResponseToChefEvents(res))); } loadMoreEventFeed(filters: EventFeedFilter, lastEvent: ChefEvent): Observable<ChefEventCollection> { const url = `${GATEWAY_URL}/eventfeed`; const options = { params: this.buildEventFeedURLSearchParams(filters, lastEvent) }; return this.httpClient .get<RespChefEventCollection>(url, options).pipe( map((res) => this.convertResponseToChefEvents(res))); } getEventTypeCount(filters: EventFeedFilter): Observable<EventTypeCount> { const url = `${GATEWAY_URL}/event_type_counts`; const options = { params: this.buildEventCountsURLSearchParams(filters) }; return this.httpClient .get<RespEventCounts>(url, options).pipe( map((respCounts) => new EventTypeCount(respCounts))); } getEventTaskCount(filters: EventFeedFilter): Observable<EventTaskCount> { const url = `${GATEWAY_URL}/event_task_counts`; const options = { params: this.buildEventCountsURLSearchParams(filters) }; return this.httpClient .get<RespEventCounts>(url, options).pipe( map((respCounts) => { return new EventTaskCount(respCounts); })); } getSuggestions(type: string, text: string): Observable<string[]> { if (text && text.length > 0) { const params = new HttpParams().set('type', type).set('text', text); const url = `${CONFIG_MGMT_URL}/suggestions`; return this.httpClient.get<Chicklet[]>(url, {params}).pipe(map((suggestions: Chicklet[]) => suggestions.map(item => item.text))); } else { return observableOf([]); } } getGuitarStrings(filters: EventFeedFilter): Observable<GuitarStringCollection> { const url = `${GATEWAY_URL}/eventstrings`; const options = { params: this.buildEventStringsURLSearchParams(filters) }; return this.httpClient .get(url, options).pipe( map((res) => this.convertResponseToGuitarStringCollection(res))); } convertResponseToGuitarStringCollection(json: any): GuitarStringCollection { const responseGuitarStringCollection: ResponseGuitarStringCollection = json; if (!responseGuitarStringCollection.start || !responseGuitarStringCollection.end || !responseGuitarStringCollection.hours_between) { throw new Error('Guitar strings response is missing the start, end, or hours_between value'); } const start = moment(responseGuitarStringCollection.start).startOf('day'); const end = moment(responseGuitarStringCollection.end).endOf('day'); const hoursBetween = responseGuitarStringCollection.hours_between; if (start.isAfter(end)) { throw new Error('Guitar strings response: start date is after end date'); } if ( hoursBetween < 1 || 24 % hoursBetween !== 0) { throw new Error('Guitar strings response: hoursBetween is invalid value: ' + hoursBetween ); } const numberOfDays = Math.round(end.diff(start, 'days', true)); const expectedNumberOfItems = (24 / hoursBetween) * numberOfDays; const guitarStringCollection = responseGuitarStringCollection.strings.map(responseString => { const eventAction = responseString.event_action; const items: GuitarStringItem[] = this.createGuitarStringItemCollection( start, hoursBetween, responseString.collection, expectedNumberOfItems); return new GuitarString(eventAction, items); }); // order the event actions to be 'create', 'delete', and 'update' const sortedGuitarStringCollection = sortBy(guitarStringCollection, string => string.eventAction); return new GuitarStringCollection(sortedGuitarStringCollection, start, end); } private convertResponseToChefEvents( respEventCollection: RespChefEventCollection): ChefEventCollection { const events = respEventCollection.events.map( (respEvent: RespChefEvent) => new ChefEvent(respEvent)); return new ChefEventCollection(events, respEventCollection.total_events); } buildEventCountsURLSearchParams(filters: EventFeedFilter): HttpParams { let searchParam: HttpParams = new HttpParams(); if (filters.searchBar) { const searchBarWithChildren = this.addChildEventTypes(filters.searchBar); searchParam = this.flattenSearchBar(searchBarWithChildren, searchParam); } if (filters.startDate) { searchParam = searchParam.append('start', filters.startDate.valueOf().toString()); } else { searchParam = searchParam.append('start', initialState.filters.startDate.valueOf().toString()); } if (filters.endDate) { searchParam = searchParam.append('end', filters.endDate.valueOf().toString()); } return searchParam; } buildEventStringsURLSearchParams(filters: EventFeedFilter): HttpParams { let searchParam: HttpParams = new HttpParams(); if (filters.searchBar) { const searchBarWithChildren = this.addChildEventTypes(filters.searchBar); searchParam = this.flattenSearchBar(searchBarWithChildren, searchParam); } searchParam = searchParam.append('timezone', Intl.DateTimeFormat().resolvedOptions().timeZone); if (filters.hoursBetween) { searchParam = searchParam.append('hours_between', filters.hoursBetween.toString()); } else { searchParam = searchParam.append('hours_between', '1'); } if (filters.startDate) { searchParam = searchParam.append('start', filters.startDate.format('YYYY-MM-DD')); } else { searchParam = searchParam.append('start', initialState.filters.startDate.format('YYYY-MM-DD')); } if (filters.endDate) { searchParam = searchParam.append('end', filters.endDate.format('YYYY-MM-DD')); } else { searchParam = searchParam.append('end', moment().format('YYYY-MM-DD')); } return searchParam; } private flattenSearchBar(filters: Chicklet[], searchParam: HttpParams): HttpParams { return reduce((params: HttpParams, filter: { type: string, text: string }) => { const filterParam = `${encodeURIComponent(filter.type)}:${encodeURIComponent(filter.text)}`; return params.append('filter', filterParam); }, searchParam, filters); } addChildEventTypes(filters: Chicklet[]): Chicklet[] { const entityTypes: string[] = filters.filter((filter: Chicklet) => filter.type === ENTITY_TYPE_TAG).map((filter: Chicklet) => filter.text); if (includes(ENTITY_TYPE_DATA_BAG_TAG, entityTypes) && !includes(ENTITY_TYPE_DATA_BAG_ITEM_TAG, entityTypes)) { filters = concat(filters, {type: ENTITY_TYPE_TAG, text: ENTITY_TYPE_DATA_BAG_ITEM_TAG}); } if (includes(ENTITY_TYPE_COOKBOOK_TAG, entityTypes) && !includes(ENTITY_TYPE_COOKBOOK_VERSION_TAG, entityTypes)) { filters = concat(filters, {type: ENTITY_TYPE_TAG, text: ENTITY_TYPE_COOKBOOK_VERSION_TAG}); } if (includes(ENTITY_TYPE_COOKBOOK_TAG, entityTypes) && !includes(ENTITY_TYPE_ARTIFACT_COOKBOOK_VERSION_TAG, entityTypes)) { filters = concat(filters, {type: ENTITY_TYPE_TAG, text: ENTITY_TYPE_ARTIFACT_COOKBOOK_VERSION_TAG}); } return filters; } buildEventFeedURLSearchParams(filters: EventFeedFilter, lastEvent: ChefEvent): HttpParams { let searchParam: HttpParams = new HttpParams(); // By default, we want to collapse events of the same type, action and // performed by the same user if (filters.collapse === false) { searchParam = searchParam.append('collapse', 'false'); } else { searchParam = searchParam.append('collapse', 'true'); } if (filters.searchBar) { const searchBarWithChildren = this.addChildEventTypes(filters.searchBar); searchParam = this.flattenSearchBar(searchBarWithChildren, searchParam); } if (filters.task) { searchParam = searchParam.append('filter', `task:${filters.task}`); } if (filters.requestorName) { searchParam = searchParam.append('filter', `requestor_name:${filters.requestorName}`); } if (filters.pageSize) { searchParam = searchParam.append('page_size', `${filters.pageSize}`); } else { searchParam = searchParam.append('page_size', '100'); } if (filters.startDate) { searchParam = searchParam.append('start', filters.startDate.valueOf().toString()); } else { searchParam = searchParam.append('start', initialState.filters.startDate.valueOf().toString()); } if (filters.endDate) { searchParam = searchParam.append('end', filters.endDate.valueOf().toString()); } if (lastEvent) { searchParam = searchParam.append('before', new Date(lastEvent.endTime).valueOf().toString()); searchParam = searchParam.append('cursor', lastEvent.endId); } return searchParam; } private createGuitarStringItemCollection( initialStart: moment.Moment, hoursBetweenItems: number, respEventCollection: RespEventCollection[], expectedNumberOfItems: number): GuitarStringItem[] { const guitarStringItemCollection = respEventCollection.map((eventCollection: RespEventCollection, index: number) => { const start = initialStart.clone().add( hoursBetweenItems * index, 'hours').startOf('hour'); const end = initialStart.clone().add( hoursBetweenItems * index, 'hours').endOf('hour'); return new GuitarStringItem(eventCollection.events_count, start, end); }); // We are guaranteeing that each day has 24 hours // This solves the when daylight saving time start or end is within the range. if ( guitarStringItemCollection.length > expectedNumberOfItems ) { return guitarStringItemCollection.slice(0, expectedNumberOfItems); } else if ( guitarStringItemCollection.length < expectedNumberOfItems ) { for ( let index = guitarStringItemCollection.length; index < expectedNumberOfItems; index++) { const start = initialStart.clone().add( hoursBetweenItems * index, 'hours').startOf('hour'); const end = initialStart.clone().add( hoursBetweenItems * index, 'hours').endOf('hour'); guitarStringItemCollection.push(new GuitarStringItem([], start, end)); } } return guitarStringItemCollection; } }
the_stack
import { State, Agile, StateObserver, Observer, ComputedTracker, } from '../../../src'; import { LogMock } from '../../helper/logMock'; describe('State Tests', () => { let dummyAgile: Agile; beforeEach(() => { LogMock.mockLogs(); dummyAgile = new Agile(); jest.spyOn(State.prototype, 'set'); jest.clearAllMocks(); }); it('should create State and should call initial set (default config)', () => { // Overwrite select once to not call it jest.spyOn(State.prototype, 'set').mockReturnValueOnce(undefined as any); const state = new State(dummyAgile, 'coolValue'); expect(state.set).toHaveBeenCalledWith('coolValue', { overwrite: true }); expect(state._key).toBeUndefined(); expect(state.isSet).toBeFalsy(); expect(state.isPlaceholder).toBeTruthy(); expect(state.initialStateValue).toBe('coolValue'); expect(state._value).toBe('coolValue'); expect(state.previousStateValue).toBe('coolValue'); expect(state.nextStateValue).toBe('coolValue'); expect(state.observers['value']).toBeInstanceOf(StateObserver); expect(Array.from(state.observers['value'].dependents)).toStrictEqual([]); expect(state.observers['value'].key).toBeUndefined(); expect(state.sideEffects).toStrictEqual({}); }); it('should create State and should call initial set (specific config)', () => { // Overwrite select once to not call it jest.spyOn(State.prototype, 'set').mockReturnValueOnce(undefined as any); const dummyObserver = new Observer(dummyAgile); const state = new State(dummyAgile, 'coolValue', { key: 'coolState', dependents: [dummyObserver], }); expect(state.set).toHaveBeenCalledWith('coolValue', { overwrite: true }); expect(state._key).toBe('coolState'); expect(state.isSet).toBeFalsy(); expect(state.isPlaceholder).toBeTruthy(); expect(state.initialStateValue).toBe('coolValue'); expect(state._value).toBe('coolValue'); expect(state.previousStateValue).toBe('coolValue'); expect(state.nextStateValue).toBe('coolValue'); expect(state.observers['value']).toBeInstanceOf(StateObserver); expect(Array.from(state.observers['value'].dependents)).toStrictEqual([ dummyObserver, ]); expect(state.observers['value'].key).toBe('coolState'); expect(state.sideEffects).toStrictEqual({}); }); it("should create State and shouldn't call initial set (config.isPlaceholder = true)", () => { // Overwrite select once to not call it jest.spyOn(State.prototype, 'set').mockReturnValueOnce(undefined as any); const state = new State(dummyAgile, 'coolValue', { isPlaceholder: true }); expect(state.set).not.toHaveBeenCalled(); expect(state._key).toBeUndefined(); expect(state.isSet).toBeFalsy(); expect(state.isPlaceholder).toBeTruthy(); expect(state.initialStateValue).toBe('coolValue'); expect(state._value).toBe('coolValue'); expect(state.previousStateValue).toBe('coolValue'); expect(state.nextStateValue).toBe('coolValue'); expect(state.observers['value']).toBeInstanceOf(StateObserver); expect(Array.from(state.observers['value'].dependents)).toStrictEqual([]); expect(state.observers['value'].key).toBeUndefined(); expect(state.sideEffects).toStrictEqual({}); }); describe('State Function Tests', () => { let numberState: State<number>; let objectState: State<{ name: string; age: number }>; let arrayState: State<string[]>; let booleanState: State<boolean>; beforeEach(() => { numberState = new State<number>(dummyAgile, 10, { key: 'numberStateKey', }); objectState = new State<{ name: string; age: number }>( dummyAgile, { name: 'jeff', age: 10 }, { key: 'objectStateKey', } ); arrayState = new State<string[]>(dummyAgile, ['jeff'], { key: 'arrayStateKey', }); booleanState = new State<boolean>(dummyAgile, false, { key: 'booleanStateKey', }); }); describe('value set function tests', () => { it('should call set function with passed value', () => { numberState.set = jest.fn(); numberState.value = 20; expect(numberState.set).toHaveBeenCalledWith(20); }); }); describe('value get function tests', () => { it('should return current value', () => { expect(numberState.value).toBe(10); ComputedTracker.tracked = jest.fn(); }); it('should return current value', () => { const value = numberState.value; expect(value).toBe(10); expect(ComputedTracker.tracked).toHaveBeenCalledWith( numberState.observers['value'] ); }); }); describe('key set function tests', () => { it('should call setKey with passed value', () => { numberState.setKey = jest.fn(); numberState.key = 'newKey'; expect(numberState.setKey).toHaveBeenCalledWith('newKey'); }); }); describe('key get function tests', () => { it('should return current State Key', () => { expect(numberState.key).toBe('numberStateKey'); }); }); describe('setKey function tests', () => { let dummyOutputObserver: Observer; beforeEach(() => { dummyOutputObserver = new StateObserver(numberState, { key: 'oldKey' }); numberState.observers['output'] = dummyOutputObserver; }); it('should update the key indicator of the State and all associated Observers', () => { numberState.setKey('newKey'); expect(numberState._key).toBe('newKey'); expect(numberState.observers['value'].key).toBe('newKey'); expect(numberState.observers['output'].key).toBe('newKey'); }); }); describe('set function tests', () => { beforeEach(() => { jest.spyOn(numberState.observers['value'], 'ingestValue'); }); it('should ingestValue if value has correct type (default config)', () => { numberState.set(20); LogMock.hasNotLogged('warn'); LogMock.hasNotLogged('error'); expect(numberState.observers['value'].ingestValue).toHaveBeenCalledWith( 20, { force: false, } ); }); it('should ingestValue if passed function returns value with correct type (default config)', () => { numberState.set((value) => value + 20); LogMock.hasNotLogged('warn'); LogMock.hasNotLogged('error'); expect(numberState.observers['value'].ingestValue).toHaveBeenCalledWith( 30, { force: false, } ); }); it('should ingestValue if value has correct type (specific config)', () => { numberState.set(20, { sideEffects: { enabled: false, }, background: true, storage: false, }); LogMock.hasNotLogged('warn'); LogMock.hasNotLogged('error'); expect(numberState.observers['value'].ingestValue).toHaveBeenCalledWith( 20, { sideEffects: { enabled: false, }, background: true, storage: false, force: false, } ); }); it("should ingestValue if value hasn't correct type but the type isn't explicit defined (default config)", () => { numberState.set('coolValue' as any); LogMock.hasNotLogged('warn'); LogMock.hasNotLogged('error'); expect(numberState.observers['value'].ingestValue).toHaveBeenCalledWith( 'coolValue', { force: false } ); }); }); describe('ingest function tests', () => { beforeEach(() => { numberState.observers['value'].ingest = jest.fn(); }); it('should call ingest function in Observer (default config)', () => { numberState.ingest(); expect(numberState.observers['value'].ingest).toHaveBeenCalledWith({}); }); it('should call ingest function in Observer (specific config)', () => { numberState.ingest({ force: true, background: true, }); expect(numberState.observers['value'].ingest).toHaveBeenCalledWith({ background: true, force: true, }); }); }); describe('addSideEffect function tests', () => { const sideEffectFunction = () => { /* empty function */ }; it('should add passed callback function to sideEffects at passed key (default config)', () => { numberState.addSideEffect('dummyKey', sideEffectFunction); expect(numberState.sideEffects).toHaveProperty('dummyKey'); expect(numberState.sideEffects['dummyKey']).toStrictEqual({ callback: sideEffectFunction, weight: 10, }); LogMock.hasNotLogged('warn'); }); it('should add passed callback function to sideEffects at passed key (specific config)', () => { numberState.addSideEffect('dummyKey', sideEffectFunction, { weight: 999, }); expect(numberState.sideEffects).toHaveProperty('dummyKey'); expect(numberState.sideEffects['dummyKey']).toStrictEqual({ callback: sideEffectFunction, weight: 999, }); LogMock.hasNotLogged('warn'); }); it("shouldn't add passed invalid function to sideEffects at passed key (default config)", () => { numberState.addSideEffect('dummyKey', 10 as any); expect(numberState.sideEffects).not.toHaveProperty('dummyKey'); LogMock.hasLoggedCode('00:03:01', ['Side Effect Callback', 'function']); }); }); describe('removeSideEffect function tests', () => { beforeEach(() => { numberState.sideEffects['dummyKey'] = { callback: jest.fn(), weight: 0, }; }); it('should remove sideEffect at key from State', () => { numberState.removeSideEffect('dummyKey'); expect(numberState.sideEffects).not.toHaveProperty('dummyKey'); }); }); describe('hasSideEffect function tests', () => { beforeEach(() => { numberState.sideEffects['dummyKey'] = { callback: jest.fn(), weight: 0, }; }); it('should return true if SideEffect at given Key exists', () => { expect(numberState.hasSideEffect('dummyKey')).toBeTruthy(); }); it("should return false if SideEffect at given Key doesn't exists", () => { expect(numberState.hasSideEffect('notExistingDummyKey')).toBeFalsy(); }); }); }); });
the_stack
import { createElement, remove } from '@syncfusion/ej2-base'; import { Maps, ILoadedEventArgs, DataLabel } from '../../../src/index'; import { usMap } from '../../maps/data/data.spec'; import { IPrintEventArgs } from '../../../src/maps/model/interface'; import { PdfPageOrientation } from '@syncfusion/ej2-pdf-export'; import { beforePrint } from '../../../src/maps/model/constants'; import { Legend, Annotations, PdfExport, ImageExport, Print } from '../../../src/maps/index'; import { profile, inMB, getMemoryProfile } from '../common.spec'; Maps.Inject(Legend, Annotations, DataLabel, PdfExport, ImageExport, Print ); export function getElementByID(id: string): Element { return document.getElementById(id); } describe('Map layer testing', () => { beforeAll(() => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } }); describe(' Map layer testing', () => { let mapObj: Maps; let mapElement: Element; let temp: Element; mapElement = createElement('div', { id: 'container' }); temp = createElement('div', { id: 'tempElement' }); (<any>window).open = () => { return { document: { write: () => { }, close: () => { } }, close: () => { }, print: () => { }, focus: () => { }, moveTo: () => { }, resizeTo: () => { } }; }; beforeAll(() => { let template: Element = createElement('div', { id: 'template', styles: 'display: none;border: 2px solid red' }); document.body.appendChild(template); template.innerHTML = "<div id='templateWrap' style='background-color:#4472c4;border-radius: 3px;'>" + "<img src='./img1.jpg' style='border-radius: 0px;width: 24px;height: 24px;padding: 2px;' />" + "<div style='color:white;float: right;padding: 2px;line-height: 20px; text-align: center; font-family:Roboto; font-style: medium; fontp-size:14px;'><span>Print</span></div></div>"; document.body.appendChild(mapElement); document.body.appendChild(temp); mapObj = new Maps({ allowImageExport: true, allowPdfExport : true, allowPrint : true, layers: [{ shapeSettings: { fill: '#C3E6ED', }, dataLabelSettings: { visible: true, labelPath: 'name', }, shapeData: usMap, }, ], annotations: [{ content: '#template', x: '50%', y: '50%' }], loaded: (args: Object): void => { mapObj.print(); } }); mapObj.appendTo('#container'); }); afterAll((): void => { remove(mapElement); mapObj.destroy(); }); it('checking a print', (done: Function) => { mapObj.beforePrint = (args: IPrintEventArgs): void => { expect(args.htmlContent.outerHTML.indexOf('<div id="container" class="e-control e-maps e-lib" aria-label="Maps Element" tabindex="1"') > -1).toBe(true); done(); }; mapObj.print(); mapObj.refresh(); }); it('Checking a PDF', (): void => { mapObj.loaded = (args: ILoadedEventArgs): void => { let element: Element = document.getElementById(mapObj.element.id + '_Annotations_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; mapObj.export('PDF', 'Map'); mapObj.refresh(); }); it('Checking argument cancel', (done: Function) => { mapObj.beforePrint = (args: IPrintEventArgs): void => { args.cancel = true; expect(args.htmlContent.outerHTML.indexOf('<div id="container" class="e-control e-maps e-lib" aria-label="Maps Element" tabindex="1"') > -1).toBe(true); done(); }; mapObj.print(); mapObj.refresh(); }); it('Checking to print in multiple element', (done: Function) => { mapObj.loaded = (args: Object): void => { mapObj.print(['container', 'tempElement']); }; mapObj.beforePrint = (args: IPrintEventArgs): void => { expect(args.htmlContent.outerHTML.indexOf('tempElement') > -1).toBe(true); done(); }; mapObj.refresh(); }); it('Checking annotation style', (done: Function) => { mapObj.beforePrint = (args: IPrintEventArgs): void => { expect(args.htmlContent.outerHTML.indexOf('style="background-color:#4472c4;border-radius: 3px;"') > -1).toBe(true); done(); }; mapObj.refresh(); }); it('Checking to print direct element', (done: Function) => { mapObj.loaded = (args: Object): void => { mapObj.print(document.getElementById('container')); }; mapObj.beforePrint = (args: IPrintEventArgs): void => { expect(args.htmlContent.outerHTML.indexOf('<div id="container" class="e-control e-maps e-lib" aria-label="Maps Element" tabindex="1"') > -1).toBe(true); done(); }; mapObj.refresh(); }); it('Checking to print single element', (done: Function) => { mapObj.loaded = (args: Object): void => { mapObj.print('tempElement'); }; mapObj.beforePrint = (args: IPrintEventArgs): void => { expect(args.htmlContent.outerHTML.indexOf('<div id="tempElement"') > -1).toBe(true); done(); }; mapObj.refresh(); }); it('Checking Image export- JPEG', (done: Function) => { mapObj.export('JPEG', 'map'); setTimeout(() => { expect('').toBe(''); done(); }, 500); }); it('Checking Image export - SVG', (done: Function) => { mapObj.export('SVG', 'map'); setTimeout(() => { expect('').toBe(''); done(); }, 500); }); it('Checking Image export - PNG', (done: Function) => { mapObj.export('PNG', 'map'); setTimeout(() => { expect('').toBe(''); done(); }, 500); }); it('Checking export - PDF - Potrait', (done: Function) => { mapObj.export('PDF', 'map', PdfPageOrientation.Portrait); setTimeout(() => { expect('').toBe(''); done(); }, 500); }); it('Checking to return base64 for png', (done: Function) => { mapObj.export('PNG', 'map', PdfPageOrientation.Portrait, false); setTimeout(() => { expect('').toBe(''); done(); }, 500); }); it('Checking to return base64 for SVG', (done: Function) => { mapObj.export('SVG', 'map', PdfPageOrientation.Portrait, false); setTimeout(() => { expect('').toBe(''); done(); }, 500); }); it('Checking to return base64 for JPEG', (done: Function) => { mapObj.export('JPEG', 'map', PdfPageOrientation.Portrait, false); setTimeout(() => { expect('').toBe(''); done(); }, 500); }); it('Checking to return base64 for PDF', (done: Function) => { mapObj.export('PDF', 'map', PdfPageOrientation.Portrait, false); setTimeout(() => { expect('').toBe(''); done(); }, 500); }); }); describe('Map Tile layer testing', () => { let mapObj: Maps; let mapElement: Element; let temp: Element; mapElement = createElement('div', { id: 'container' }); temp = createElement('div', { id: 'tempElement' }); (<any>window).open = () => { return { document: { write: () => { }, close: () => { } }, close: () => { }, print: () => { }, focus: () => { }, moveTo: () => { }, resizeTo: () => { } }; }; beforeAll(() => { let template: Element = createElement('div', { id: 'template', styles: 'display: none;border: 2px solid red' }); document.body.appendChild(template); template.innerHTML = "<div id='templateWrap' style='background-color:#4472c4;border-radius: 3px;'>" + "<img src='./img1.jpg' style='border-radius: 0px;width: 24px;height: 24px;padding: 2px;' />" + "<div style='color:white;float: right;padding: 2px;line-height: 20px; text-align: center; font-family:Roboto; font-style: medium; fontp-size:14px;'><span>Print</span></div></div>"; document.body.appendChild(mapElement); document.body.appendChild(temp); mapObj = new Maps({ allowPdfExport : true, allowImageExport : true, allowPrint : true, zoomSettings: { enable: true }, titleSettings: { text: 'Open Street Map', textStyle: { size: '13px' } }, layers: [{ layerType: 'OSM', markerSettings: [ { visible: true, dataSource: [ { latitude: 37.6276571, longitude: -122.4276688, name: 'San Bruno' }, { latitude: 33.5302186, longitude: -117.7418381, name: 'Laguna Niguel' }, ], shape: 'Circle', height: 20, width: 20, animationDuration: 0 }, ] }, { type: 'SubLayer', shapeData: usMap } ], }); mapObj.appendTo('#container'); }); afterAll((): void => { remove(mapElement); mapObj.destroy(); }); it('Checking Image export for Tile map - SVG', (done: Function) => { mapObj.export('SVG', 'map'); setTimeout(() => { expect('').toBe(''); done(); }, 500); }); it('Checking Image export Image Tile map - PNG', (done: Function) => { mapObj.export('PNG', 'map'); setTimeout(() => { expect('').toBe(''); done(); }, 500); }); it('Checking Image export for Tile map - JPEG', (done: Function) => { mapObj.export('JPEG', 'map'); setTimeout(() => { expect('').toBe(''); done(); }, 500); }); it('Checking Pdf export for Tile map - PDF', (done: Function) => { mapObj.export('PDF', 'map'); setTimeout(() => { expect('').toBe(''); done(); }, 500); }); it('Checking to return base64 for JPEG', (done: Function) => { mapObj.export('JPEG', 'map', PdfPageOrientation.Portrait, false); setTimeout(() => { expect('').toBe(''); done(); }, 500); }); it('Checking to return base64 for png', (done: Function) => { mapObj.export('PNG', 'map', PdfPageOrientation.Portrait, false); setTimeout(() => { expect('').toBe(''); done(); }, 500); }); it('Checking to return base64 for SVG', (done: Function) => { mapObj.export('SVG', 'map', PdfPageOrientation.Portrait, false); setTimeout(() => { expect('').toBe(''); done(); }, 500); }); it('Checking to return base64 for PDF', (done: Function) => { mapObj.export('PDF', 'map', PdfPageOrientation.Portrait, false); setTimeout(() => { expect('').toBe(''); done(); }, 500); }); it('Checking Image export in PDF ', (done: Function) => { mapObj.allowImageExport = false; mapObj.export('SVG', 'map',PdfPageOrientation.Portrait,true); setTimeout(() => { expect('').toBe(''); done(); }, 500); }); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange); //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()); //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); });
the_stack
import { FSHTank, FSHDocument } from '../../src/import'; import { Profile, Logical, RuleSet, FshCode, FshValueSet, Instance, FshCodeSystem } from '../../src/fshtypes'; import { InsertRule, CardRule, ConceptRule, AssignmentRule, AddElementRule, CaretValueRule } from '../../src/fshtypes/rules'; import { loggerSpy, assertCardRule, assertValueSetConceptComponent, assertAssignmentRule, assertAddElementRule, assertCaretValueRule, assertConceptRule } from '../testhelpers'; import { minimalConfig } from '../utils/minimalConfig'; import { applyInsertRules } from '../../src/fhirtypes/common'; describe('applyInsertRules', () => { let doc: FSHDocument; let tank: FSHTank; let profile: Profile; let instance: Instance; let ruleSet1: RuleSet; let ruleSet2: RuleSet; beforeEach(() => { doc = new FSHDocument('fileName'); tank = new FSHTank([doc], minimalConfig); loggerSpy.reset(); profile = new Profile('Foo').withFile('Profile.fsh').withLocation([5, 6, 7, 16]); profile.parent = 'Observation'; doc.profiles.set(profile.name, profile); instance = new Instance('Far'); instance.instanceOf = 'Patient'; doc.instances.set(instance.name, instance); ruleSet1 = new RuleSet('Bar'); doc.ruleSets.set(ruleSet1.name, ruleSet1); ruleSet2 = new RuleSet('Baz'); doc.ruleSets.set(ruleSet2.name, ruleSet2); }); it('should apply rules from a single level insert rule', () => { // RuleSet: Bar // * category 1..1 // // Profile: Foo // Parent: Observation // * insert Bar const cardRule = new CardRule('category'); cardRule.min = 1; cardRule.max = '1'; ruleSet1.rules.push(cardRule); const insertRule = new InsertRule(''); insertRule.ruleSet = 'Bar'; profile.rules.push(insertRule); applyInsertRules(profile, tank); expect(profile.rules).toHaveLength(1); assertCardRule(profile.rules[0], 'category', 1, '1'); }); it('should apply rules from a single level insert rule with a path', () => { // RuleSet: Bar // * coding 1..* // // Profile: Foo // Parent: Observation // * category insert Bar const cardRule = new CardRule('coding'); cardRule.min = 1; cardRule.max = '*'; ruleSet1.rules.push(cardRule); const insertRule = new InsertRule('category'); insertRule.ruleSet = 'Bar'; profile.rules.push(insertRule); applyInsertRules(profile, tank); expect(profile.rules).toHaveLength(1); assertCardRule(profile.rules[0], 'category.coding', 1, '*'); }); it('should apply a rule without a path from a single level insert rule with a path', () => { // RuleSet: Bar // * ^short = "foo" // // Profile: Foo // Parent: Observation // * category insert Bar const caretRule = new CaretValueRule(''); caretRule.caretPath = 'short'; caretRule.value = 'foo'; ruleSet1.rules.push(caretRule); const insertRule = new InsertRule('category'); insertRule.ruleSet = 'Bar'; profile.rules.push(insertRule); applyInsertRules(profile, tank); expect(profile.rules).toHaveLength(1); assertCaretValueRule(profile.rules[0], 'category', 'short', 'foo', undefined, []); }); it('should only apply soft indexing once when applying rules from a rule with a path', () => { // RuleSet: Bar // * family = "foo" // * given[0] = "bar" // // Instance: Foo // InstanceOf: Patient // * name[+] insert Bar const rule1 = new AssignmentRule('family'); rule1.value = 'foo'; rule1.exactly = false; rule1.isInstance = false; const rule2 = new AssignmentRule('given[0]'); rule2.value = 'bar'; rule2.exactly = false; rule2.isInstance = false; ruleSet1.rules.push(rule1, rule2); const insertRule1 = new InsertRule('name[+]'); insertRule1.ruleSet = 'Bar'; instance.rules.push(insertRule1); applyInsertRules(instance, tank); expect(instance.rules).toHaveLength(2); assertAssignmentRule(instance.rules[0], 'name[+].family', 'foo', false, false); assertAssignmentRule(instance.rules[1], 'name[=].given[0]', 'bar', false, false); }); it('should not apply rules from a single level insert rule that are not valid', () => { // RuleSet: Bar // * #bear // // Profile: Foo // Parent: Observation // * insert Bar const concept = new ConceptRule('bear').withFile('Concept.fsh').withLocation([1, 2, 3, 4]); ruleSet1.rules.push(concept); const insertRule = new InsertRule('').withFile('Insert.fsh').withLocation([5, 6, 7, 8]); insertRule.ruleSet = 'Bar'; profile.rules.push(insertRule); applyInsertRules(profile, tank); expect(profile.rules).toHaveLength(0); expect(loggerSpy.getLastMessage('error')).toMatch( /ConceptRule.*Profile.*File: Concept\.fsh.*Line: 1 - 3.*Applied in File: Insert\.fsh.*Line: 5 - 7\D*/s ); }); it('should apply rules from a single level insert rule in correct order', () => { // RuleSet: Bar // * subject 1.. // // Profile: Foo // Parent: Observation // * category ..1 // * insert Bar // * focus ..1 const categoryRule = new CardRule('category'); categoryRule.min = 1; categoryRule.max = '1'; const subjectRule = new CardRule('subject'); subjectRule.min = 1; subjectRule.max = '1'; const focusRule = new CardRule('focus'); focusRule.min = 1; focusRule.max = '1'; const insertRule = new InsertRule(''); insertRule.ruleSet = 'Bar'; ruleSet1.rules.push(subjectRule); profile.rules.push(categoryRule, insertRule, focusRule); applyInsertRules(profile, tank); expect(profile.rules).toHaveLength(3); assertCardRule(profile.rules[0], 'category', 1, '1'); assertCardRule(profile.rules[1], 'subject', 1, '1'); assertCardRule(profile.rules[2], 'focus', 1, '1'); }); it('should apply rules from multiple single level insert rules in correct order', () => { // RuleSet: Bar // * status 1..1 // RuleSet: Baz // * focus 1..1 // // Profile: Foo // Parent: Observation // * insert Bar // * insert Baz const subjectRule = new CardRule('subject'); subjectRule.min = 1; subjectRule.max = '1'; ruleSet1.rules.push(subjectRule); const focusRule = new CardRule('focus'); focusRule.min = 1; focusRule.max = '1'; ruleSet2.rules.push(focusRule); const barRule = new InsertRule(''); barRule.ruleSet = 'Bar'; const bazRule = new InsertRule(''); bazRule.ruleSet = 'Baz'; profile.rules.push(barRule, bazRule); applyInsertRules(profile, tank); expect(profile.rules).toHaveLength(2); assertCardRule(profile.rules[0], 'subject', 1, '1'); assertCardRule(profile.rules[1], 'focus', 1, '1'); }); it('should apply rules from repeated single level insert rules in correct order', () => { // RuleSet: Bar // * status 1..1 // // Profile: Foo // Parent: Observation // * insert Bar // * insert Bar const subjectRule = new CardRule('subject'); subjectRule.min = 1; subjectRule.max = '1'; ruleSet1.rules.push(subjectRule); const barRule = new InsertRule(''); barRule.ruleSet = 'Bar'; profile.rules.push(barRule, barRule); applyInsertRules(profile, tank); expect(profile.rules).toHaveLength(2); assertCardRule(profile.rules[0], 'subject', 1, '1'); assertCardRule(profile.rules[1], 'subject', 1, '1'); }); it('should apply rules from a nested insert rule in the correct order', () => { // RuleSet: Bar // * category ..1 // * insert Baz // RuleSet: Baz // * subject 1.. // Profile: Foo // Parent: Observation // * insert Bar // * focus ..1 const categoryRule = new CardRule('category'); categoryRule.min = 1; categoryRule.max = '1'; const subjectRule = new CardRule('subject'); subjectRule.min = 1; subjectRule.max = '1'; const focusRule = new CardRule('focus'); focusRule.min = 1; focusRule.max = '1'; const insertBazRule = new InsertRule(''); insertBazRule.ruleSet = 'Baz'; const insertBarRule = new InsertRule(''); insertBarRule.ruleSet = 'Bar'; ruleSet1.rules.push(categoryRule, insertBazRule); ruleSet2.rules.push(subjectRule); profile.rules.push(insertBarRule, focusRule); applyInsertRules(profile, tank); expect(profile.rules).toHaveLength(3); assertCardRule(profile.rules[0], 'category', 1, '1'); assertCardRule(profile.rules[1], 'subject', 1, '1'); assertCardRule(profile.rules[2], 'focus', 1, '1'); }); it('should apply rules from a nested insert rule with paths', () => { // RuleSet: Bar // * coding 1..* // * coding insert Baz // // RuleSet: Baz // * system 1..1 // // Profile: Foo // Parent: Observation // * category insert Bar // * focus ..1 const categoryRule = new CardRule('coding'); categoryRule.min = 1; categoryRule.max = '*'; const subjectRule = new CardRule('system'); subjectRule.min = 1; subjectRule.max = '1'; const focusRule = new CardRule('focus'); focusRule.min = 1; focusRule.max = '1'; const insertBazRule = new InsertRule('coding'); insertBazRule.ruleSet = 'Baz'; const insertBarRule = new InsertRule('category'); insertBarRule.ruleSet = 'Bar'; ruleSet1.rules.push(categoryRule, insertBazRule); ruleSet2.rules.push(subjectRule); profile.rules.push(insertBarRule, focusRule); applyInsertRules(profile, tank); expect(profile.rules).toHaveLength(3); assertCardRule(profile.rules[0], 'category.coding', 1, '*'); assertCardRule(profile.rules[1], 'category.coding.system', 1, '1'); assertCardRule(profile.rules[2], 'focus', 1, '1'); }); it('should apply rules from a nested insert rule even when they repeat', () => { // RuleSet: Bar // * category ..1 // * insert Baz // RuleSet: Baz // * subject 1.. // Profile: Foo // Parent: Observation // * insert Baz // * insert Bar // * focus ..1 const categoryRule = new CardRule('category'); categoryRule.min = 1; categoryRule.max = '1'; const subjectRule = new CardRule('subject'); subjectRule.min = 1; subjectRule.max = '1'; const focusRule = new CardRule('focus'); focusRule.min = 1; focusRule.max = '1'; const insertBazRule = new InsertRule(''); insertBazRule.ruleSet = 'Baz'; const insertBarRule = new InsertRule(''); insertBarRule.ruleSet = 'Bar'; ruleSet1.rules.push(categoryRule, insertBazRule); ruleSet2.rules.push(subjectRule); profile.rules.push(insertBazRule, insertBarRule, focusRule); applyInsertRules(profile, tank); expect(profile.rules).toHaveLength(4); assertCardRule(profile.rules[0], 'subject', 1, '1'); assertCardRule(profile.rules[1], 'category', 1, '1'); assertCardRule(profile.rules[2], 'subject', 1, '1'); assertCardRule(profile.rules[3], 'focus', 1, '1'); }); it('should convert a ConceptRule with a system to a ValueSetConceptComponent when applying to a FshValueSet', () => { // RuleSet: Bar // * ZOO#bear "brown bear" // // ValueSet: Foo // * insert Bar const vs = new FshValueSet('Foo').withFile('VS.fsh').withLocation([5, 6, 7, 16]); doc.valueSets.set(vs.name, vs); const concept = new ConceptRule('bear', 'brown bear'); concept.system = 'ZOO'; ruleSet1.rules.push(concept); const insertRule = new InsertRule(''); insertRule.ruleSet = 'Bar'; vs.rules.push(insertRule); applyInsertRules(vs, tank); expect(vs.rules).toHaveLength(1); assertValueSetConceptComponent( vs.rules[0], undefined, undefined, [new FshCode('bear', 'ZOO', 'brown bear')], true ); }); it('should not convert a ConceptRule without a system to a ValueSetConceptComponent when applying to a FshValueSet', () => { // RuleSet: Bar // * #bear "brown bear" // // ValueSet: Foo // * insert Bar const vs = new FshValueSet('Foo'); doc.valueSets.set(vs.name, vs); const concept = new ConceptRule('bear', 'brown bear') .withFile('RuleSets.fsh') .withLocation([8, 5, 8, 16]); ruleSet1.rules.push(concept); const insertRule = new InsertRule('').withFile('VS.fsh').withLocation([7, 6, 7, 16]); insertRule.ruleSet = 'Bar'; vs.rules.push(insertRule); applyInsertRules(vs, tank); expect(vs.rules).toHaveLength(0); expect(loggerSpy.getLastMessage('error')).toMatch( /ConceptRule.*ValueSet.*File: RuleSets\.fsh.*Line: 8.*Applied in File: VS\.fsh.*Line: 7\D*/s ); }); it('should log an error when a ConceptRule with a system is applied to a FshCodeSystem', () => { // RuleSet: Bar // * ZOO#bear "brown bear" // // CodeSystem: Foo // * insert Bar const cs = new FshCodeSystem('Foo'); doc.codeSystems.set(cs.name, cs); const concept = new ConceptRule('bear', 'brown bear') .withFile('RuleSets.fsh') .withLocation([7, 5, 7, 12]); concept.system = 'ZOO'; ruleSet1.rules.push(concept); const insertRule = new InsertRule('').withFile('CodeSystems.fsh').withLocation([3, 5, 3, 19]); insertRule.ruleSet = 'Bar'; cs.rules.push(insertRule); applyInsertRules(cs, tank); expect(cs.rules).toHaveLength(1); assertConceptRule(cs.rules[0], 'bear', 'brown bear', undefined, []); expect(loggerSpy.getLastMessage('error')).toMatch( /Do not include the system when listing concepts for a code system\..*File: RuleSets\.fsh.*Line: 7.*Applied in File: CodeSystems\.fsh.*Line: 3\D*/s ); }); it('should log an error when a ConceptRule is inserted at a path', () => { // RuleSet: Bar // * #bear "Bear" // // CodeSystem: MyCodeSystem // * somePath insert Bar const cs = new FshCodeSystem('MyCodeSystem'); doc.codeSystems.set(cs.name, cs); const concept = new ConceptRule('bear', 'Bear') .withFile('RuleSets.fsh') .withLocation([7, 5, 7, 12]); ruleSet1.rules.push(concept); const insertRule = new InsertRule('somePath') .withFile('CodeSystems.fsh') .withLocation([3, 5, 3, 19]); insertRule.ruleSet = 'Bar'; cs.rules.push(insertRule); applyInsertRules(cs, tank); expect(cs.rules).toHaveLength(1); assertConceptRule(cs.rules[0], 'bear', 'Bear', undefined, []); expect(loggerSpy.getLastMessage('error')).toMatch( /Do not insert a RuleSet at a path when the RuleSet adds a concept\..*File: RuleSets\.fsh.*Line: 7.*Applied in File: CodeSystems\.fsh.*Line: 3\D*/s ); }); it('should not convert a ConceptRule to a ValueSetConceptComponent when applying to a Profile', () => { // RuleSet: Bar // * ZOO#bear "brown bear" // // Profile: Foo // * insert Bar const concept = new ConceptRule('bear', 'brown bear') .withFile('Concept.fsh') .withLocation([1, 2, 3, 4]); concept.system = 'ZOO'; ruleSet1.rules.push(concept); const insertRule = new InsertRule('').withFile('Insert.fsh').withLocation([1, 2, 3, 4]); insertRule.ruleSet = 'Bar'; profile.rules.push(insertRule); applyInsertRules(profile, tank); expect(profile.rules).toHaveLength(0); expect(loggerSpy.getLastMessage('error')).toMatch( /ConceptRule.*Profile.*File: Concept\.fsh.*Line: 1 - 3.*Applied in File: Insert\.fsh.*Line: 1 - 3\D*/s ); }); it('should ignore insert rules that cause a circular dependency, and log an error', () => { // RuleSet: Bar // * insert Baz // RuleSet: Baz // * insert Bar // * subject 1.. // Profile: Foo // Parent: Observation // * insert Bar const subjectRule = new CardRule('subject'); subjectRule.min = 1; subjectRule.max = '1'; const insertBazRule = new InsertRule(''); insertBazRule.ruleSet = 'Baz'; const insertBarRule = new InsertRule('').withFile('Insert.fsh').withLocation([1, 2, 3, 4]); insertBarRule.ruleSet = 'Bar'; ruleSet1.rules.push(insertBazRule); ruleSet2.rules.push(insertBarRule, subjectRule); profile.rules.push(insertBarRule); applyInsertRules(profile, tank); expect(profile.rules).toHaveLength(1); assertCardRule(profile.rules[0], 'subject', 1, '1'); expect(loggerSpy.getLastMessage('error')).toMatch( /Bar will cause a circular dependency.*File: Insert\.fsh.*Line: 1 - 3.*/s ); }); it('should log an error when a ruleSet cannot be found', () => { // Profile: Foo // Parent: Observation // * insert Bam const cardRule = new CardRule('category'); cardRule.min = 1; cardRule.max = '1'; ruleSet1.rules.push(cardRule); const insertRule = new InsertRule('').withFile('NoBam.fsh').withLocation([1, 2, 3, 4]); insertRule.ruleSet = 'Bam'; profile.rules.push(insertRule); applyInsertRules(profile, tank); expect(profile.rules).toHaveLength(0); expect(loggerSpy.getLastMessage('error')).toMatch( /Unable to find definition for RuleSet Bam.*File: NoBam\.fsh.*Line: 1 - 3\D*/s ); }); it('should log an error when applying context to a . path', () => { // RuleSet: Bar // * . ^short = "foo" // Profile: Foo // Parent: Observation // * category insert Bar const caretValueRule = new CaretValueRule('.'); caretValueRule.caretPath = 'short'; caretValueRule.path = '.'; caretValueRule.value = 'foo'; ruleSet1.rules.push(caretValueRule); const insertRule = new InsertRule('category').withFile('Bar.fsh').withLocation([1, 2, 3, 4]); insertRule.ruleSet = 'Bar'; profile.rules.push(insertRule); applyInsertRules(profile, tank); expect(profile.rules).toHaveLength(1); assertCaretValueRule(profile.rules[0], '.', 'short', 'foo', undefined, []); expect(loggerSpy.getLastMessage('error')).toMatch( /The special '\.' path.*File: Bar\.fsh.*Line: 1 - 3\D*/s ); }); it('should apply add element rules from a single level insert rule', () => { // RuleSet: AddCoreElements // primaryId 1..1 SU uri "Primary ID" // primaryOrganization 1..1 SU Reference(Organization) "Primary Organization" // sharedNotes 0..* Annotation "Shared notes" // // Logical: Foo // * insert AddCoreElements const ruleSet = new RuleSet('AddCoreElements'); const addElementRule1 = new AddElementRule('primaryId'); addElementRule1.min = 1; addElementRule1.max = '1'; addElementRule1.summary = true; addElementRule1.types = [{ type: 'uri' }]; addElementRule1.short = 'Primary ID'; const addElementRule2 = new AddElementRule('primaryOrganization'); addElementRule2.min = 1; addElementRule2.max = '1'; addElementRule2.summary = true; addElementRule2.types = [{ type: 'Organization', isReference: true }]; addElementRule2.short = 'Primary Organization'; const addElementRule3 = new AddElementRule('sharedNotes'); addElementRule3.min = 0; addElementRule3.max = '*'; addElementRule3.types = [{ type: 'Annotation' }]; addElementRule3.short = 'Shared notes'; ruleSet.rules.push(addElementRule1, addElementRule2, addElementRule3); doc.ruleSets.set(ruleSet.name, ruleSet); const logical = new Logical('Foo').withFile('Logical.fsh').withLocation([5, 6, 7, 16]); doc.logicals.set(logical.name, logical); const insertRule = new InsertRule(''); insertRule.ruleSet = 'AddCoreElements'; logical.rules.push(insertRule); applyInsertRules(logical, tank); expect(logical.rules).toHaveLength(3); assertAddElementRule(logical.rules[0], 'primaryId', { card: { min: 1, max: '1' }, flags: { summary: true }, types: [{ type: 'uri' }], defs: { short: 'Primary ID' } }); assertAddElementRule(logical.rules[1], 'primaryOrganization', { card: { min: 1, max: '1' }, flags: { summary: true }, types: [{ type: 'Organization', isReference: true }], defs: { short: 'Primary Organization' } }); assertAddElementRule(logical.rules[2], 'sharedNotes', { card: { min: 0, max: '*' }, types: [{ type: 'Annotation' }], defs: { short: 'Shared notes' } }); }); describe('#appliedRuleSet', () => { it('should apply rules from a single level insert rule with parameters', () => { // RuleSet: SimpleRules (value, maxNote) // valueString = {value} // note 0..{maxNote} // // Profile: Foo // Parent: Observation // * insert SimpleRules ("Something", 5) const appliedSimpleRules = new RuleSet('SimpleRules'); const valueRule = new AssignmentRule('valueString'); valueRule.value = 'Something'; valueRule.exactly = false; valueRule.isInstance = false; const noteRule = new CardRule('note'); noteRule.min = 0; noteRule.max = '5'; appliedSimpleRules.rules.push(valueRule, noteRule); doc.appliedRuleSets.set( JSON.stringify(['SimpleRules', '"Something"', '5']), appliedSimpleRules ); const insertRule = new InsertRule(''); insertRule.ruleSet = 'SimpleRules'; insertRule.params = ['"Something"', '5']; profile.rules.push(insertRule); applyInsertRules(profile, tank); expect(profile.rules).toHaveLength(2); assertAssignmentRule(profile.rules[0], 'valueString', 'Something', false, false); assertCardRule(profile.rules[1], 'note', 0, 5); }); it('should ignore insert rules with parameters that cause a circular dependency, and log an error', () => { // RuleSet: SimpleRules (maxNote) // note 0..{maxNote} // insert FancyRules ({maxNote}) // // RuleSet: FancyRules (maxInterpretation) // interpretation 0..{maxInterpretation} // insert SimpleRules ({maxInterpretation}) // // Profile: Foo // Parent: Observation // * insert SimpleRules (5) const appliedSimpleRules = new RuleSet('SimpleRules'); const simpleCard = new CardRule('note'); simpleCard.min = 0; simpleCard.max = '5'; const insertFancy = new InsertRule(''); insertFancy.ruleSet = 'FancyRules'; insertFancy.params = ['5']; appliedSimpleRules.rules.push(simpleCard, insertFancy); const appliedFancyRules = new RuleSet('FancyRules'); const fancyCard = new CardRule('interpretation'); fancyCard.min = 0; fancyCard.max = '5'; const insertSimple = new InsertRule('').withFile('Fancy.fsh').withLocation([4, 9, 4, 29]); insertSimple.ruleSet = 'SimpleRules'; insertSimple.params = ['5']; appliedFancyRules.rules.push(fancyCard, insertSimple); doc.appliedRuleSets .set(JSON.stringify(['SimpleRules', '5']), appliedSimpleRules) .set(JSON.stringify(['FancyRules', '5']), appliedFancyRules); const insertRule = new InsertRule(''); insertRule.ruleSet = 'SimpleRules'; insertRule.params = ['5']; profile.rules.push(insertRule); applyInsertRules(profile, tank); expect(profile.rules).toHaveLength(2); assertCardRule(profile.rules[0], 'note', 0, 5); assertCardRule(profile.rules[1], 'interpretation', 0, 5); expect(loggerSpy.getLastMessage('error')).toMatch( /SimpleRules will cause a circular dependency/s ); expect(loggerSpy.getLastMessage('error')).toMatch(/File: Fancy\.fsh.*Line: 4\D*/s); }); }); });
the_stack
import * as ex from '@excalibur'; import { ExcaliburAsyncMatchers, ExcaliburMatchers } from 'excalibur-jasmine'; /** * */ function flushWebGLCanvasTo2D(source: HTMLCanvasElement): HTMLCanvasElement { const canvas = document.createElement('canvas'); canvas.width = source.width; canvas.height = source.height; const ctx = canvas.getContext('2d'); ctx.drawImage(source, 0, 0); return canvas; } describe('The ExcaliburGraphicsContext', () => { describe('2D', () => { beforeEach(() => { jasmine.addMatchers(ExcaliburMatchers); jasmine.addAsyncMatchers(ExcaliburAsyncMatchers); }); it('exists', () => { expect(ex.ExcaliburGraphicsContext2DCanvas).toBeDefined(); }); it('can be constructed', () => { const canvas = document.createElement('canvas'); const context = new ex.ExcaliburGraphicsContext2DCanvas({ canvasElement: canvas, backgroundColor: ex.Color.Red }); expect(context).toBeDefined(); }); it('has the same dimensions as the canvas', () => { const canvas = document.createElement('canvas'); canvas.width = 123; canvas.height = 456; const context = new ex.ExcaliburGraphicsContext2DCanvas({ canvasElement: canvas, backgroundColor: ex.Color.Red }); expect(context.width).toBe(canvas.width); expect(context.height).toBe(canvas.height); }); it('can draw a graphic', async () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContext2DCanvas({ canvasElement, enableTransparency: false, backgroundColor: ex.Color.White }); const rect = new ex.Rectangle({ width: 50, height: 50, color: ex.Color.Blue }); sut.clear(); sut.drawImage(rect._bitmap, 20, 20); await expectAsync(canvasElement).toEqualImage('src/spec/images/ExcaliburGraphicsContextSpec/2d-drawgraphic.png'); }); it('can draw debug point', async () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContext2DCanvas({ canvasElement, enableTransparency: false, backgroundColor: ex.Color.White }); sut.clear(); sut.debug.drawPoint(ex.vec(50, 50), { size: 20, color: ex.Color.Blue }); await expectAsync(canvasElement).toEqualImage('src/spec/images/ExcaliburGraphicsContextSpec/2d-drawpoint.png'); }); it('can draw debug line', async () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContext2DCanvas({ canvasElement, enableTransparency: false, backgroundColor: ex.Color.White }); sut.clear(); sut.debug.drawLine(ex.vec(0, 0), ex.vec(100, 100), { color: ex.Color.Blue }); await expectAsync(canvasElement).toEqualImage('src/spec/images/ExcaliburGraphicsContextSpec/2d-drawline.png'); }); it('can transform the context', async () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContext2DCanvas({ canvasElement, enableTransparency: false, backgroundColor: ex.Color.White }); const rect = new ex.Rectangle({ width: 50, height: 50, color: ex.Color.Blue }); sut.clear(); sut.save(); sut.opacity = 0.5; sut.translate(50, 50); sut.rotate(Math.PI / 4); sut.scale(0.5, 0.5); sut.drawImage(rect._bitmap, -25, -25); sut.restore(); await expectAsync(canvasElement).toEqualImage('src/spec/images/ExcaliburGraphicsContextSpec/2d-transform.png'); }); it('can draw rectangle', async () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContext2DCanvas({ canvasElement: canvasElement, enableTransparency: false, backgroundColor: ex.Color.White }); sut.clear(); sut.drawRectangle(ex.vec(10, 10), 80, 80, ex.Color.Blue); sut.flush(); await expectAsync(canvasElement).toEqualImage('src/spec/images/ExcaliburGraphicsContextSpec/webgl-solid-rect.png'); }); it('can draw circle', async () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContext2DCanvas({ canvasElement: canvasElement, enableTransparency: false, backgroundColor: ex.Color.White }); sut.clear(); sut.drawCircle(ex.vec(50, 50), 50, ex.Color.Blue); sut.flush(); await expectAsync(canvasElement).toEqualImage('src/spec/images/ExcaliburGraphicsContextSpec/2d-circle.png'); }); it('can draw a line', async () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContext2DCanvas({ canvasElement: canvasElement, enableTransparency: false, backgroundColor: ex.Color.White }); sut.clear(); sut.drawLine(ex.vec(0, 0), ex.vec(100, 100), ex.Color.Blue, 5); sut.flush(); await expectAsync(canvasElement).toEqualImage('src/spec/images/ExcaliburGraphicsContextSpec/2d-line.png'); }); it('can snap drawings to pixel', async () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContext2DCanvas({ canvasElement: canvasElement, enableTransparency: false, snapToPixel: true, backgroundColor: ex.Color.White }); const rect = new ex.Rectangle({ width: 50, height: 50, color: ex.Color.Blue }); sut.clear(); sut.drawImage(rect._bitmap, 1.9, 1.9); await expectAsync(canvasElement).toEqualImage('src/spec/images/ExcaliburGraphicsContextSpec/2d-snap-to-pixel.png'); }); it('can handle drawing a zero dimension image', () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContext2DCanvas({ canvasElement: canvasElement, enableTransparency: false, snapToPixel: true, backgroundColor: ex.Color.White }); const rect = new ex.Rectangle({ width: 0, height: 0, color: ex.Color.Blue }); sut.clear(); expect(() => { sut.drawImage(rect._bitmap, 0, 0); }).not.toThrow(); expect(() => { sut.drawImage(rect._bitmap, 0, 0, 0, 0); }).not.toThrow(); expect(() => { sut.drawImage(rect._bitmap, 0, 0, 10, 10, 0, 0, 0, 0); }).not.toThrow(); }); }); describe('WebGL', () => { beforeEach(() => { jasmine.addMatchers(ExcaliburMatchers); jasmine.addAsyncMatchers(ExcaliburAsyncMatchers); }); it('exists', () => { expect(ex.ExcaliburGraphicsContextWebGL).toBeDefined(); }); it('can be constructed', () => { const canvas = document.createElement('canvas'); const context = new ex.ExcaliburGraphicsContextWebGL({ canvasElement: canvas, backgroundColor: ex.Color.Red }); expect(context).toBeDefined(); }); it('has the same dimensions as the canvas', () => { const canvas = document.createElement('canvas'); canvas.width = 123; canvas.height = 456; const context = new ex.ExcaliburGraphicsContextWebGL({ canvasElement: canvas, backgroundColor: ex.Color.Red }); expect(context.width).toBe(canvas.width); expect(context.height).toBe(canvas.height); }); it('can draw a graphic', async () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContextWebGL({ canvasElement: canvasElement, enableTransparency: false, backgroundColor: ex.Color.White }); const rect = new ex.Rectangle({ width: 50, height: 50, color: ex.Color.Blue }); sut.clear(); sut.drawImage(rect._bitmap, 20, 20); // sut.opacity = .5; // sut.drawCircle(ex.vec(50, 50), 50, ex.Color.Green); // sut.drawLine(ex.vec(10, 10), ex.vec(90, 90), ex.Color.Red, 5); // sut.drawLine(ex.vec(90, 10), ex.vec(10, 90), ex.Color.Red, 5); // sut.drawRectangle(ex.vec(10, 10), 80, 80, ex.Color.Blue); sut.flush(); await expectAsync(flushWebGLCanvasTo2D(canvasElement)).toEqualImage( 'src/spec/images/ExcaliburGraphicsContextSpec/2d-drawgraphic.png' ); }); it('can draw debug point', async () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContextWebGL({ canvasElement: canvasElement, enableTransparency: false, backgroundColor: ex.Color.White }); sut.clear(); sut.debug.drawPoint(ex.vec(50, 50), { size: 20, color: ex.Color.Blue }); sut.flush(); await expectAsync(flushWebGLCanvasTo2D(canvasElement)).toEqualImage( 'src/spec/images/ExcaliburGraphicsContextSpec/webgl-drawpoint.png' ); }); it('can draw debug line', async () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContextWebGL({ canvasElement: canvasElement, enableTransparency: false, backgroundColor: ex.Color.White }); sut.clear(); sut.debug.drawLine(ex.vec(0, 0), ex.vec(100, 100), { color: ex.Color.Blue }); sut.flush(); await expectAsync(flushWebGLCanvasTo2D(canvasElement)).toEqualImage( 'src/spec/images/ExcaliburGraphicsContextSpec/webgl-drawline.png' ); }); it('can draw debug rectangle', async () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContextWebGL({ canvasElement: canvasElement, enableTransparency: false, backgroundColor: ex.Color.White }); sut.clear(); sut.debug.drawRect(10, 10, 80, 80, { color: ex.Color.Blue }); sut.flush(); await expectAsync(flushWebGLCanvasTo2D(canvasElement)).toEqualImage('src/spec/images/ExcaliburGraphicsContextSpec/webgl-rect.png'); }); it('can draw rectangle', async () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContextWebGL({ canvasElement: canvasElement, enableTransparency: false, backgroundColor: ex.Color.White }); sut.clear(); sut.drawRectangle(ex.vec(10, 10), 80, 80, ex.Color.Blue); sut.flush(); await expectAsync(flushWebGLCanvasTo2D(canvasElement)).toEqualImage( 'src/spec/images/ExcaliburGraphicsContextSpec/webgl-solid-rect.png' ); }); it('can draw circle', async () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContextWebGL({ canvasElement: canvasElement, enableTransparency: false, backgroundColor: ex.Color.White }); sut.clear(); sut.drawCircle(ex.vec(50, 50), 50, ex.Color.Blue); sut.flush(); await expectAsync(flushWebGLCanvasTo2D(canvasElement)).toEqualImage('src/spec/images/ExcaliburGraphicsContextSpec/webgl-circle.png'); }); it('can draw a line', async () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContextWebGL({ canvasElement: canvasElement, enableTransparency: false, backgroundColor: ex.Color.White }); sut.clear(); sut.drawLine(ex.vec(0, 0), ex.vec(100, 100), ex.Color.Blue, 5); sut.flush(); await expectAsync(flushWebGLCanvasTo2D(canvasElement)).toEqualImage('src/spec/images/ExcaliburGraphicsContextSpec/webgl-line.png'); }); it('can transform the context', async () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContextWebGL({ canvasElement: canvasElement, enableTransparency: false, backgroundColor: ex.Color.White }); const rect = new ex.Rectangle({ width: 50, height: 50, color: ex.Color.Blue }); sut.clear(); sut.save(); sut.opacity = 0.5; sut.translate(50, 50); sut.rotate(Math.PI / 4); sut.scale(0.5, 0.5); sut.drawImage(rect._bitmap, -25, -25); sut.restore(); sut.flush(); await expectAsync(flushWebGLCanvasTo2D(canvasElement)).toEqualImage( 'src/spec/images/ExcaliburGraphicsContextSpec/webgl-transform.png' ); }); it('can snap drawings to pixel', async () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContextWebGL({ canvasElement: canvasElement, enableTransparency: false, snapToPixel: true, backgroundColor: ex.Color.White }); const rect = new ex.Rectangle({ width: 50, height: 50, color: ex.Color.Blue }); sut.clear(); sut.drawImage(rect._bitmap, 1.9, 1.9); sut.flush(); await expectAsync(flushWebGLCanvasTo2D(canvasElement)).toEqualImage( 'src/spec/images/ExcaliburGraphicsContextSpec/2d-snap-to-pixel.png' ); }); it('can handle drawing a zero dimension image', () => { const canvasElement = document.createElement('canvas'); canvasElement.width = 100; canvasElement.height = 100; const sut = new ex.ExcaliburGraphicsContextWebGL({ canvasElement: canvasElement, enableTransparency: false, snapToPixel: true, backgroundColor: ex.Color.White }); const rect = new ex.Rectangle({ width: 0, height: 0, color: ex.Color.Blue }); sut.clear(); expect(() => { sut.drawImage(rect._bitmap, 0, 0); }).not.toThrow(); expect(() => { sut.drawImage(rect._bitmap, 0, 0, 0, 0); sut.flush(); }).not.toThrow(); expect(() => { sut.drawImage(rect._bitmap, 0, 0, 10, 10, 0, 0, 0, 0); sut.flush(); }).not.toThrow(); }); }); });
the_stack
import file = require("../FileUtil"); import xml = require("../xml/index"); import CodeUtil = require("./code_util"); import create_manifest = require("./createManifest"); var properties = {}; var stylesMap = {}; class EXMLConfig{ /** * Egret命名空间 */ public static E:string = "http://ns.egret-labs.org/egret"; /** * Wing命名空间 */ public static W:string = "http://ns.egret-labs.org/wing"; /** * 构造函数 */ public constructor() { var exmlPath: string = egret.root + "/tools/lib/exml/"; exmlPath = exmlPath.split("\\").join("/"); var str:string = file.read(exmlPath+"egret-manifest.xml"); var manifest:any = xml.parse(str); this.parseManifest(manifest); str = file.read(exmlPath+"properties.json"); properties = JSON.parse(str); this.findStyles(properties); } public static getInstance():EXMLConfig { if (!exmlConfig) { exmlConfig = new EXMLConfig(); } return exmlConfig; } private findStyles(properties:any):void{ var data:any = properties["styles"]; if(!data){ return; } for(var key in data){ var classData:any = properties[key]; if(!classData){ continue; } var list:Array<string> = data[key]; var length:number = list.length; for(var i:number=0;i<length;i++){ var prop:string = list[i]; var type:string = classData[prop]; if(type){ stylesMap[prop] = type; } } } } private _srcPath:string; public get srcPath():string{ return this._srcPath; } public set srcPath(value:string){ this._srcPath = value; this.classNameToPath = create_manifest.getClassToPathInfo(this.srcPath); this.parseModules(); } private classNameToPath:any; private classNameToModule:any; /** * 组件清单列表 */ public componentDic:any = {}; public idMap:any = {}; private parseModules():void{ this.classNameToModule = {}; for(var className in this.classNameToPath){ var index:number = className.lastIndexOf("."); var ns:string = ""; if(index!=-1){ ns = className.substring(0,index); className = className.substring(index+1); } var list:Array<string> = this.classNameToModule[className]; if(!list){ list = this.classNameToModule[className] = []; } if(ns&&list.indexOf(ns)==-1){ list.push(ns); } } } /** * 解析框架清单文件 */ public parseManifest(manifest:any):void{ var children:Array<any> = manifest.children; var length:number = children.length; for(var i:number=0;i<length;i++){ var item:any = children[i]; var component:Component = new Component(item); this.componentDic[component.className] = component; this.idMap[component.id] = component.className; } for(var className in this.componentDic){ var component:Component = this.componentDic[className]; if(!component.defaultProp) this.findProp(component); } } /** * 递归查找默认属性 */ private findProp(component:Component):string{ if(component.defaultProp) return component.defaultProp; var superComp:Component = this.componentDic[component.superClass]; if(superComp){ var prop:string = this.findProp(superComp); if(prop){ component.defaultProp = prop; } } return component.defaultProp; } /** * @inheritDoc */ public getClassNameById(id:string, ns:string):string{ var name:string = ""; if(this.basicTypes.indexOf(id)!=-1){ return id; } if(ns==EXMLConfig.W){ } else if(!ns||ns==EXMLConfig.E){ name = this.idMap[id]; } else{ name = ns.substring(0,ns.length-1)+id if(!this.classNameToPath[name]){ name = ""; } } return name; } /** * 检查一个类名是否存在 */ public checkClassName(className:string):boolean{ if(!className){ return false; } if(this.componentDic[className]){ return true; } if(this.classNameToPath[className]){ return true; } return false; } /** * @inheritDoc */ public getDefaultPropById(id:string, ns:string):string{ var className:string = this.getClassNameById(id,ns); var component:Component = this.componentDic[className]; if(!component&&className){ component = this.findDefaultProp(className); } if(!component) return ""; return component.defaultProp; } private findDefaultProp(className:string):Component{ var classData:any = properties[className]; if(!classData){ var path:string = this.classNameToPath[className]; var ext:string = file.getExtension(path).toLowerCase(); var text:string = file.read(path); if(ext=="ts"){ classData = this.getPropertiesFromTs(text,className,""); } else if(ext=="exml"){ classData = this.getPropertiesFromExml(text); } if(classData){ properties[className] = classData; } else{ return null; } } var superClass:string = classData["super"]; var component:Component = this.componentDic[superClass]; if(!component){ component = this.findDefaultProp(superClass); } return component; } /** * 指定的属性是否为样式属性 */ public isStyleProperty(prop:string,className:string):boolean { var type:String = this.findType(className,prop); return !type&&this.checkStyleProperty(prop,className); } private checkStyleProperty(prop:string,className:string):boolean { return (this.isInstanceOf(className,"egret.gui.IStyleClient")&&stylesMap[prop]); } /** * 获取指定类指定属性的类型 */ public getPropertyType(prop:string,className:string):string{ if(className=="Object"){ return "any"; } var type:string = this.findType(className,prop); if(!type){ if(this.checkStyleProperty(prop,className)){ return stylesMap[prop]; } } return type; } private findType(className:string,prop:string):string{ var classData:any = properties[className]; if(!classData){ var path:string = this.classNameToPath[className]; var ext:string = file.getExtension(path).toLowerCase(); var text:string = file.read(path); if(ext=="ts"){ text = CodeUtil.removeComment(text,path); classData = this.getPropertiesFromTs(text,className,""); } else if(ext=="exml"){ classData = this.getPropertiesFromExml(text); } if(classData){ properties[className] = classData; } else{ return ""; } } var type:string = classData[prop]; if(!type){ type = this.findType(classData["super"],prop); } return type; } /** * 读取一个exml文件引用的类列表 */ private getPropertiesFromExml(text:string):any{ var exml:any = xml.parse(text); if(!exml){ return null; } var superClass:string = this.getClassNameById(exml.localName,exml.namespace); if(superClass){ var data:any = {}; data["super"] = superClass; return data; } return null; } /** * 获取属性列表 */ private getPropertiesFromTs(text:string,className:string,nsPrefiex:string):any { index = className.lastIndexOf("."); var moduleName:string = ""; if (index != -1) { moduleName = className.substring(0, index); className = className.substring(index+1); } var data:any; if(moduleName){ while(text.length>0){ var index:number = CodeUtil.getFirstVariableIndex("module",text); if(index==-1){ break; } text = text.substring(index+6); index = text.indexOf("{"); if(index==-1){ continue; } var ns:string = text.substring(0,index).trim(); text = text.substring(index); index = CodeUtil.getBracketEndIndex(text); if(index==-1) { break; } var block:string = text.substring(0,index); text = text.substring(index); if(ns==moduleName){ if(nsPrefiex) { ns = nsPrefiex+"."+moduleName; } data = this.getPropFromBlock(block,className,ns); break; } else if(moduleName.indexOf(ns)==0&&moduleName.charAt(ns.length)=="."){ var tail:string = moduleName.substring(ns.length+1); var prefix:string = moduleName.substring(0,ns.length); if(nsPrefiex){ prefix = nsPrefiex+"."+prefix; } data = this.getPropertiesFromTs(block,tail+"."+className,prefix); if(data) { break; } } } } else{ data = this.getPropFromBlock(text,className,nsPrefiex); } return data; } private getPropFromBlock(block:string,targetClassName:string,ns:string):any{ var data:any; while(block.length>0){ var index:number = CodeUtil.getFirstVariableIndex("class",block); if(index==-1){ break; } block = block.substring(index+5); index = block.indexOf("{"); var preStr:string = block.substring(0,index); block = block.substring(index); var className:string = CodeUtil.getFirstVariable(preStr); if(className!=targetClassName){ continue; } data = {}; preStr = CodeUtil.removeFirstVariable(preStr,className); var word:string = CodeUtil.getFirstVariable(preStr); if(word=="extends"){ preStr = CodeUtil.removeFirstVariable(preStr); word = CodeUtil.getFirstWord(preStr); if(word){ word = this.getFullClassName(word,ns); data["super"] = word; } preStr = CodeUtil.removeFirstWord(preStr); word = CodeUtil.getFirstVariable(preStr); } if(word=="implements"){ preStr = CodeUtil.removeFirstVariable(preStr); var arr:Array<any> = preStr.split(","); for(var i:number = arr.length-1;i>=0;i--){ var inter:string = arr[i]; inter = inter.trim(); if(inter){ inter = this.getFullClassName(inter,ns); arr[i] = inter; } else{ arr.splice(i,1); } } data["implements"] = arr; } index = CodeUtil.getBracketEndIndex(block); if(index==-1) break; var text:string = block.substring(0,index+1); this.readProps(text,data,ns); break; } return data; } /** * 根据类类短名,和这个类被引用的时所在的module名来获取完整类名。 */ private getFullClassName(word:string,ns:string):string { if (!ns||!word) { return word; } var prefix:string = ""; var index:number = word.lastIndexOf("."); var nsList; if(index==-1){ nsList = this.classNameToModule[word]; } else{ prefix = word.substring(0,index); nsList = this.classNameToModule[word.substring(index+1)]; } if(!nsList){ return word; } var length = nsList.length; var targetNs = ""; for(var k=0;k<length;k++){ var superNs = nsList[k]; if(prefix){ var tail:string = superNs.substring(superNs.length-prefix.length); if(tail==prefix){ superNs = superNs.substring(0,superNs.length-prefix.length-1); } else{ continue; } } if(ns.indexOf(superNs)==0){ if(superNs.length>targetNs.length){ targetNs = superNs; } } } if(targetNs){ word = targetNs+"."+word; } return word; } private basicTypes:Array<any> = ["void","any","number","string","boolean","Object","Array","Function"]; private readProps(text:string,data:any,ns:string):void{ var lines:Array<any> = text.split("\n"); var length:number = lines.length; for(var i:number=0;i<length;i++){ var line:string = lines[i]; var index:number = CodeUtil.getFirstVariableIndex("public",line); if(index==-1) continue; line = line.substring(index+7); var word:string = CodeUtil.getFirstVariable(line); if(!word||word.charAt(0)=="_") continue; if(word=="get"){ continue; } else if(word=="set"){ line = CodeUtil.removeFirstVariable(line); word = CodeUtil.getFirstVariable(line); if(!word||word.charAt(0)=="_"){ continue; } line = CodeUtil.removeFirstVariable(line); line = line.trim(); if(line.charAt(0)=="("){ index = line.indexOf(":"); if(index!=-1){ line = line.substring(index+1); index = line.indexOf(")"); type = line.substring(0,index); index = type.indexOf("<"); if(index!=-1) { type = type.substring(0,index); } type = CodeUtil.trimVariable(type); if(this.basicTypes.indexOf(type)==-1){ type = this.getFullClassName(type,ns); } data[word] = type; } else{ data[word] = "any"; } } } else{ line = CodeUtil.removeFirstVariable(line); line = line.trim(); var firstChar:string = line.charAt(0); if(firstChar==":"){ var type:string = CodeUtil.getFirstWord(line.substring(1)); index = type.indexOf("="); if(index!=-1){ type = type.substring(0,index); } index = type.indexOf("<"); if(index!=-1) { type = type.substring(0,index); } type = CodeUtil.trimVariable(type); if(this.basicTypes.indexOf(type)==-1){ type = this.getFullClassName(type,ns); } data[word] = type; } else if(!line||firstChar==";"||firstChar=="="){ data[word] = "any"; } } } } /** * 检查classNameA是否是classNameB的子类或classNameA实现了接口classNameB */ public isInstanceOf(classNameA:string,classNameB:string):boolean{ if(classNameB=="any"||classNameB=="Class"){ return true; } if(classNameA==classNameB){ return true; } var dataA:any = properties[classNameA]; if(!dataA){ return false; } var list:Array<string> = dataA["implements"]; if(list){ var length:number = list.length; for(var i:number=0;i<length;i++){ if(list[i]==classNameB){ return true; } } } return this.isInstanceOf(dataA["super"],classNameB); } } class Component{ /** * 构造函数 */ public constructor(item?:any){ if(item){ this.id = item.$id; this.className = item["$module"] +"."+ this.id; if(item["$super"]) this.superClass = item.$super; if(item["$default"]) this.defaultProp = item.$default; } } /** * 短名ID */ public id:string; /** * 完整类名 */ public className:string; /** * 父级类名 */ public superClass:string = ""; /** * 默认属性 */ public defaultProp:string = ""; } var exmlConfig:EXMLConfig; export = EXMLConfig;
the_stack
import isEqual from 'lodash/isEqual'; import { getLatestSnapshot } from '@/core/contextmenu/export.menu'; import { Diff } from '@/core/diff'; import { createStoreCopy } from '@/core/file'; import { cloneDeep, getData, uuid } from '@/core/helper'; import { SIZE_MIN_WIDTH } from '@/core/layout'; import { Logger } from '@/core/logger'; import { createColumn, findByConstraintName, findByName, } from '@/core/parser/ParserToJson'; import { TableModel } from '@/engine/store/models/table.model'; import { IERDEditorContext } from '@/internal-types/ERDEditorContext'; import { Relationship } from '@@types/engine/store/relationship.state'; import { Snapshot } from '@@types/engine/store/snapshot'; import { Column } from '@@types/engine/store/table.state'; export function calculateLatestDiff(context: IERDEditorContext): Diff[] { Logger.log('calculateLatestDiff'); const newest = createStoreCopy(context.store); const snapshot = getLatestSnapshot(context); if (!snapshot) return []; Logger.log('got diff'); const diffs = calculateDiff(snapshot, { data: newest }); Logger.log(diffs); return diffs; } export function calculateDiff( { data: oldSnapshot }: Snapshot, { data: newSnapshot }: Snapshot ): Diff[] { const newTables = newSnapshot.table.tables; const oldTables = oldSnapshot.table.tables; const newRelationships = newSnapshot.relationship.relationships; const oldRelationships = oldSnapshot.relationship.relationships; const newIndexes = newSnapshot.table.indexes; const oldIndexes = oldSnapshot.table.indexes; const diffs: Diff[] = []; // TABLES newTables.forEach(newTable => { var oldTable = getData(oldTables, newTable.id); if (!oldTable) diffs.push({ type: 'table', changes: 'add', newTable: newTable, }); // table was modified else if (oldTable != newTable) { // check columns newTable.columns.forEach(newColumn => { var oldColumn = getData( oldTable ? oldTable?.columns : [], newColumn.id ); // column is new if (!oldColumn) diffs.push({ type: 'column', changes: 'add', table: newTable, newColumn: newColumn, }); // column was modified else if ( oldColumn?.dataType !== newColumn.dataType || oldColumn?.name !== newColumn.name || !isEqual(oldColumn?.option, newColumn.option) ) { diffs.push({ type: 'column', changes: 'modify', table: newTable, oldColumn: oldColumn, newColumn: newColumn, }); } }); // check for drop column oldTable?.columns.forEach(oldColumn => { var newColumn = getData(newTable.columns, oldColumn.id); // if drop column if (!newColumn && oldTable) { diffs.push({ type: 'column', changes: 'remove', table: oldTable, oldColumn: oldColumn, }); } }); // if rename table if (oldTable && oldTable.name !== newTable.name) { diffs.push({ type: 'table', changes: 'modify', oldTable: oldTable, newTable: newTable, }); } } }); // check for drop table oldTables.forEach(oldTable => { var newTable = getData(newTables, oldTable.id); // old table was dropped if (!newTable) diffs.push({ type: 'table', changes: 'remove', oldTable: oldTable, }); }); // INDEXES if (newIndexes != oldIndexes) { // check for new index newIndexes.forEach(newIndex => { const oldIndex = getData(oldIndexes, newIndex.id); // if new index if (oldIndex === undefined) { var newTable = getData(newTables, newIndex.tableId); if (newTable) diffs.push({ type: 'index', changes: 'add', newIndex: newIndex, table: newTable, }); } }); // check for drop index oldIndexes.forEach(oldIndex => { const newIndex = getData(newIndexes, oldIndex.id); // if drop index if (newIndex === undefined) { const oldTable = getData(oldTables, oldIndex.tableId); if (oldTable) diffs.push({ type: 'index', changes: 'remove', oldIndex: oldIndex, table: oldTable, }); } }); } // RELATIONSHIP if (newRelationships != oldRelationships) { // relationship drop oldRelationships.forEach(oldRelationship => { const newRelationship = getData(newRelationships, oldRelationship.id); if (!newRelationship) { const table = getData(oldTables, oldRelationship.end.tableId); if (!table) return; diffs.push({ type: 'relationship', changes: 'remove', oldRelationship: oldRelationship, table: table, }); } }); // add relationship newRelationships.forEach(newRelationship => { const oldRelationship = getData(oldRelationships, newRelationship.id); if (!oldRelationship) { const startTable = getData(newTables, newRelationship.start.tableId); const endTable = getData(newTables, newRelationship.end.tableId); if (!startTable || !endTable) return; diffs.push({ type: 'relationship', changes: 'add', newRelationship: newRelationship, startTable: startTable, endTable: endTable, }); } }); } return diffs; } export function mergeDiffs(...diffs: Diff[][]): Diff[] { let currentDiffs: Diff[] = []; diffs.reverse().forEach((changes, index) => { if (index === 0) { currentDiffs = changes; } else { changes.forEach(diff => { // TODO: add more checks // deduplication // -- add table ONE -> drop table ONE -> should result to: no change // -- add table ONE -> rename table ONE to TWO -> should result to: add table TWO if (diff.type === 'table' && diff.changes === 'remove') { currentDiffs = currentDiffs.filter( origDiff => !( origDiff.type === 'table' && origDiff.changes === 'add' && origDiff.newTable.name === diff.oldTable.name ) ); } else if (diff.type === 'column' && diff.changes === 'remove') { currentDiffs = currentDiffs.filter( origDiff => !( origDiff.type === 'column' && origDiff.changes === 'add' && origDiff.newColumn.name === diff.oldColumn.name ) ); } else { currentDiffs.push(diff); } }); } }); return currentDiffs; } export function statementsToDiff( snapshot: Snapshot, context: IERDEditorContext ): Diff[] { if (!snapshot.metadata?.statements) return []; const { helper } = context; const statements = snapshot.metadata.statements; const diffs: Diff[] = []; const { tables: snapTables, indexes: snapIndexes } = snapshot.data.table; const { relationships: snapRelationships } = snapshot.data.relationship; statements.forEach(statement => { switch (statement.type) { case 'create.table': const table = statement; const originalTable = findByName(snapTables || [], table.name); const columns = table.columns.map(column => { const newColumn: Column = { id: column.id || uuid(), name: column.name, comment: column.comment, dataType: column.dataType, default: column.default, option: { autoIncrement: column.autoIncrement, primaryKey: column.primaryKey, unique: column.unique, notNull: !column.nullable, }, ui: { active: false, pk: column.primaryKey, fk: false, pfk: false, widthName: SIZE_MIN_WIDTH, widthComment: SIZE_MIN_WIDTH, widthDataType: SIZE_MIN_WIDTH, widthDefault: SIZE_MIN_WIDTH, }, }; return newColumn; }); const loadTable = { id: table.id || uuid(), name: table.name, comment: table.comment, columns: columns, ui: originalTable ? originalTable.ui : { active: false, top: 0, left: 0, widthName: SIZE_MIN_WIDTH, widthComment: SIZE_MIN_WIDTH, zIndex: 2, }, }; const canvasState = context.store.canvasState; const newTable = new TableModel( { loadTable: loadTable }, canvasState.show ); diffs.push({ type: 'table', changes: 'add', newTable: newTable, }); break; case 'create.index': const index = statement; const duplicateIndex = findByName(snapIndexes, index.name); const targetTable = findByName(snapTables, index.tableName); if (duplicateIndex && targetTable) { diffs.push({ type: 'index', changes: 'add', newIndex: duplicateIndex, table: targetTable, }); break; } if (!targetTable) break; const indexColumns: any[] = []; index.columns.forEach(column => { const targetColumn = findByName(targetTable.columns, column.name); if (targetColumn) { indexColumns.push({ id: targetColumn.id, orderType: column.sort, }); } }); diffs.push({ type: 'index', changes: 'add', newIndex: { id: index.id || uuid(), name: index.name, tableId: targetTable.id, columns: indexColumns, unique: index.unique, }, table: targetTable, }); break; case 'alter.table.add.primaryKey': const primaryKey = statement; const pkTable = findByName(snapTables, primaryKey.name); if (!pkTable) break; primaryKey.columnNames.forEach(pkColumnName => { const oldPKColumn = findByName(pkTable.columns, pkColumnName); if (!oldPKColumn) return; const newPKColumn = cloneDeep(oldPKColumn) as Column; newPKColumn.option.primaryKey = true; diffs.push({ type: 'column', changes: 'modify', table: pkTable, oldColumn: oldPKColumn, newColumn: newPKColumn, }); }); break; case 'alter.table.add.foreignKey': const foreignKey = statement; const endTable = findByName(snapTables, foreignKey.name); const startTable = findByName(snapTables, foreignKey.refTableName); if (endTable && startTable) { const startColumns: any[] = []; const endColumns: any[] = []; foreignKey.refColumnNames.forEach(refColumnName => { const column = findByName(startTable.columns, refColumnName); if (column) { startColumns.push(column); } }); foreignKey.columnNames.forEach(columnName => { const column = findByName(endTable.columns, columnName); if (column) { endColumns.push(column); if (column.ui.pk) { column.ui.pk = false; column.ui.pfk = true; } else { column.ui.fk = true; } } }); if (startTable.visible && endTable.visible) { foreignKey.visible = true; } else { foreignKey.visible = false; } const newRelationship: Relationship = { id: foreignKey.id || uuid(), identification: !endColumns.some(column => !column.ui.pfk), relationshipType: 'ZeroOneN', start: { tableId: startTable.id, columnIds: startColumns.map(column => column.id), x: 0, y: 0, direction: 'top', }, end: { tableId: endTable.id, columnIds: endColumns.map(column => column.id), x: 0, y: 0, direction: 'top', }, constraintName: foreignKey.constraintName, visible: foreignKey.visible, }; diffs.push({ type: 'relationship', changes: 'add', newRelationship: newRelationship, startTable: startTable, endTable: endTable, }); } break; case 'alter.table.add.unique': const unique = statement; const uqTable = findByName(snapTables, unique.name); if (!uqTable) break; unique.columnNames.forEach(uqColumnName => { const oldUQColumn = findByName(uqTable.columns, uqColumnName); if (!oldUQColumn) return; const newUQColumn = cloneDeep(oldUQColumn) as Column; newUQColumn.option.unique = true; diffs.push({ type: 'column', changes: 'modify', table: uqTable, oldColumn: oldUQColumn, newColumn: newUQColumn, }); }); break; case 'alter.table.add.column': const addColumns = statement; const acTable = findByName(snapTables, addColumns.name); if (!acTable) break; addColumns.columns.forEach(col => { const addColumn = createColumn(helper, col); diffs.push({ type: 'column', changes: 'add', table: acTable, newColumn: addColumn, }); }); break; case 'alter.table.drop.column': const dropColumns = statement; const dcTable = findByName(snapTables, dropColumns.name); dcTable?.columns.forEach(col => { diffs.push({ type: 'column', changes: 'remove', table: dcTable, oldColumn: col, }); }); break; case 'drop.table': const { name: tableName } = statement; const dropTable = findByName(snapTables, tableName); if (dropTable) { diffs.push({ type: 'table', changes: 'remove', oldTable: dropTable, }); } break; case 'alter.table.drop.foreignKey': const dropForeignKey = statement; const duplicateDropFK = findByConstraintName( snapRelationships, dropForeignKey.name ); if (!duplicateDropFK) break; const dfkTable = getData(snapTables, duplicateDropFK.end.tableId); if (!dfkTable) break; diffs.push({ type: 'relationship', changes: 'remove', oldRelationship: duplicateDropFK, table: dfkTable, }); break; } }); return diffs; }
the_stack
import * as fetchMock from "fetch-mock"; import { shareItemWithGroup, ensureMembership, } from "../../src/sharing/share-item-with-group"; import { MOCK_USER_SESSION } from "../mocks/sharing/sharing"; import { TOMORROW } from "@esri/arcgis-rest-auth/test/utils"; import { ArcGISAuthError } from "@esri/arcgis-rest-request"; import { GroupNonMemberUserResponse, GroupMemberUserResponse, GroupAdminUserResponse, OrgAdminUserResponse, AnonUserResponse, } from "../mocks/users/user"; import { SearchResponse } from "../mocks/items/search"; import { ISharingResponse } from "../../src/sharing/helpers"; const SharingResponse = { notSharedWith: [] as any, itemId: "n3v", }; const FailedSharingResponse = { notSharedWith: ["t6b"], itemId: "n3v", }; const CachedSharingResponse = { notSharedWith: [] as any, itemId: "a5b", shortcut: true, }; const NoResultsSearchResponse = { query: "", total: 0, start: 0, num: 0, nextStart: 0, results: [] as any, }; export const GroupOwnerResponse = { id: "tb6", title: "fake group", userMembership: { memberType: "owner", }, }; export const GroupMemberResponse = { id: "tb6", title: "fake group", userMembership: { memberType: "member", }, }; export const GroupNonMemberResponse = { id: "tb6", title: "fake group", userMembership: { memberType: "none", }, }; export const GroupAdminResponse = { id: "tb6", title: "fake group", userMembership: { memberType: "admin", }, }; export const GroupNoAccessResponse = { error: { code: 400, messageCode: "COM_0003", message: "Group does not exist or is inaccessible.", details: [] as any[], }, }; describe("shareItemWithGroup() ::", () => { // make sure session doesnt cache metadata beforeEach((done) => { fetchMock.post("https://myorg.maps.arcgis.com/sharing/rest/generateToken", { token: "fake-token", expires: TOMORROW.getTime(), username: "jsmith", }); // make sure session doesnt cache metadata MOCK_USER_SESSION.refreshSession() .then(() => done()) .catch(); }); afterEach(fetchMock.restore); describe("share item as owner::", () => { it("should share an item with a group by owner", (done) => { // this is called when we try to determine if the item is already in the group fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/search", SearchResponse ); // the actual sharing request fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/content/users/jsmith/items/n3v/share", SharingResponse ); shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", }) .then((response) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); const [url, options]: [string, RequestInit] = fetchMock.lastCall( "https://myorg.maps.arcgis.com/sharing/rest/content/users/jsmith/items/n3v/share" ); expect(url).toBe( "https://myorg.maps.arcgis.com/sharing/rest/content/users/jsmith/items/n3v/share" ); expect(options.method).toBe("POST"); expect(response).toEqual(SharingResponse); expect(options.body).toContain("f=json"); expect(options.body).toContain("groups=t6b"); done(); }) .catch((e) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); fail(e); }); }); it("should share an item with a group by org administrator", (done) => { fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", OrgAdminUserResponse ); fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/casey?f=json&token=fake-token", { username: "casey", orgId: "qWAReEOCnD7eTxOe", groups: [] as any[], } ); fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/search", NoResultsSearchResponse ); // called when we determine if the user is a member of the group fetchMock.get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupOwnerResponse ); fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share", SharingResponse ); shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", }) .then((response) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); const [url, options]: [string, RequestInit] = fetchMock.lastCall( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share" ); expect(url).toBe( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share" ); expect(options.method).toBe("POST"); expect(response).toEqual(SharingResponse); expect(options.body).toContain("f=json"); expect(options.body).toContain("groups=t6b"); done(); }) .catch((e) => { fail(e); }); }); it("should share an item with a group by group owner/admin", (done) => { fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", GroupAdminUserResponse ); fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/otherguy?f=json&token=fake-token", { username: "otherguy", orgId: "qWAReEOCnD7eTxOe", groups: [] as any[], } ); fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/search", SearchResponse ); // called when we determine if the user is a member of the group fetchMock.get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupOwnerResponse ); fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/content/items/n3v/share", SharingResponse ); shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "otherguy", }) .then((response) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); const [url, options]: [string, RequestInit] = fetchMock.lastCall( "https://myorg.maps.arcgis.com/sharing/rest/content/items/n3v/share" ); expect(url).toBe( "https://myorg.maps.arcgis.com/sharing/rest/content/items/n3v/share" ); expect(options.method).toBe("POST"); expect(response).toEqual(SharingResponse); expect(options.body).toContain("f=json"); expect(options.body).toContain("groups=t6b"); done(); }) .catch((e) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); fail(e); }); }); it("should mock the response if an item was previously shared with a group", (done) => { fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", GroupAdminUserResponse ); fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/search", SearchResponse ); shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "a5b", groupId: "t6b", }) .then((response) => { // no web request to share at all expect(response).toEqual(CachedSharingResponse); done(); }) .catch((e) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); fail(e); }); }); it("should allow group owner/admin/member to share item they do not own", (done) => { fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", GroupMemberUserResponse ); fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/casey?f=json&token=fake-token", { username: "casey", orgId: "qWAReEOCnD7eTxOe", groups: [] as any[], } ); fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/search", SearchResponse ); // called when we determine if the user is a member of the group fetchMock.get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupMemberResponse ); fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/content/items/n3v/share", SharingResponse ); shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", }) .then((response) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); const [url, options]: [string, RequestInit] = fetchMock.lastCall( "https://myorg.maps.arcgis.com/sharing/rest/content/items/n3v/share" ); expect(url).toBe( "https://myorg.maps.arcgis.com/sharing/rest/content/items/n3v/share" ); expect(options.method).toBe("POST"); expect(response).toEqual(SharingResponse); expect(options.body).toContain("f=json"); expect(options.body).toContain("groups=t6b"); done(); }) .catch((e) => { fail(e); }); }); it("should throw if non-owner tries to share to shared editing group", (done) => { fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", GroupMemberUserResponse ); fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/casey?f=json&token=fake-token", { username: "casey", orgId: "qWAReEOCnD7eTxOe", groups: [] as any[], } ); fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/search", SearchResponse ); // called when we determine if the user is a member of the group fetchMock.get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupMemberResponse ); shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", confirmItemControl: true, }).catch((e) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); expect(e.message).toContain( "This item can not be shared to shared editing group t6b by jsmith as they not the item owner or org admin." ); done(); }); }); it("should throw if the response from the server is fishy", (done) => { fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/search", SearchResponse ); fetchMock.once( "https://myorg.maps.arcgis.com/sharing/rest/content/users/jsmith/items/n3v/share", FailedSharingResponse ); shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", }).catch((e) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); expect(e.message).toBe("Item n3v could not be shared to group t6b."); done(); }); }); }); describe("share item as org admin on behalf of other user ::", () => { it("should add user to group then share item", (done) => { fetchMock .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", OrgAdminUserResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/search", NoResultsSearchResponse ) .get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupOwnerResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/casey?f=json&token=fake-token", { username: "casey", orgId: "qWAReEOCnD7eTxOe", groups: [] as any[], } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/addUsers", { notAdded: [] } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share", { notSharedWith: [], itemId: "n3v" } ); shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", confirmItemControl: true, }) .then((result) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); // verify we added casey to t6b const addUsersOptions: RequestInit = fetchMock.lastOptions( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/addUsers" ); expect(addUsersOptions.body).toContain("admins=casey"); // verify we shared the item const shareOptions: RequestInit = fetchMock.lastOptions( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share" ); expect(shareOptions.body).toContain("groups=t6b"); expect(shareOptions.body).toContain("confirmItemControl=true"); done(); }) .catch((e) => { fail(); }); }); it("should add user to group the returned user lacks groups array", (done) => { // tbh, not 100% sure this can even happen, but... 100% coverage fetchMock .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", OrgAdminUserResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/search", NoResultsSearchResponse ) .get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupOwnerResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/casey?f=json&token=fake-token", { username: "casey", orgId: "qWAReEOCnD7eTxOe", } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/addUsers", { notAdded: [] } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share", { notSharedWith: [], itemId: "n3v" } ); shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", confirmItemControl: true, }) .then((result) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); // verify we added casey to t6b const addUsersOptions: RequestInit = fetchMock.lastOptions( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/addUsers" ); expect(addUsersOptions.body).toContain("admins=casey"); // verify we shared the item const shareOptions: RequestInit = fetchMock.lastOptions( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share" ); expect(shareOptions.body).toContain("groups=t6b"); expect(shareOptions.body).toContain("confirmItemControl=true"); done(); }) .catch((e) => { fail(); }); }); it("should upgrade user to admin then share item", (done) => { fetchMock .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", OrgAdminUserResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/search", NoResultsSearchResponse ) .get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupOwnerResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/casey?f=json&token=fake-token", { username: "casey", orgId: "qWAReEOCnD7eTxOe", groups: [ { id: "t6b", userMembership: { memberType: "member", }, }, ] as any[], } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/updateUsers", { results: [{ username: "casey", success: true }] } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share", { notSharedWith: [], itemId: "n3v" } ); shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", confirmItemControl: true, }) .then((result) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); // verify we added casey to t6b const addUsersOptions: RequestInit = fetchMock.lastOptions( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/updateUsers" ); expect(addUsersOptions.body).toContain("admins=casey"); // verify we shared the item const shareOptions: RequestInit = fetchMock.lastOptions( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share" ); expect(shareOptions.body).toContain("groups=t6b"); expect(shareOptions.body).toContain("confirmItemControl=true"); done(); }) .catch((e) => { fail(); }); }); it("should share item if user is already admin in group", (done) => { fetchMock .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", OrgAdminUserResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/search", NoResultsSearchResponse ) .get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupOwnerResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/casey?f=json&token=fake-token", { username: "casey", orgId: "qWAReEOCnD7eTxOe", groups: [ { id: "t6b", userMembership: { memberType: "admin", }, }, ] as any[], } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share", { notSharedWith: [], itemId: "n3v" } ); shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", confirmItemControl: true, }) .then((result) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); // verify we shared the item const shareOptions: RequestInit = fetchMock.lastOptions( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share" ); expect(shareOptions.body).toContain("groups=t6b"); expect(shareOptions.body).toContain("confirmItemControl=true"); done(); }) .catch((e) => { fail(); }); }); it("should throw if we can not upgrade user membership", (done) => { fetchMock .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", OrgAdminUserResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/search", NoResultsSearchResponse ) .get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupOwnerResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/casey?f=json&token=fake-token", { username: "casey", orgId: "qWAReEOCnD7eTxOe", groups: [ { id: "t6b", userMembership: { memberType: "member", }, }, ] as any[], } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/updateUsers", { results: [{ username: "casey", success: false }] } ); return shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", confirmItemControl: true, }) .then(() => { expect("").toBe("Should Throw, but it returned"); fail(); }) .catch((e) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); const addUsersOptions: RequestInit = fetchMock.lastOptions( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/updateUsers" ); expect(addUsersOptions.body).toContain("admins=casey"); expect(e.message).toBe( "Error promoting user casey to admin in edit group t6b. Consequently item n3v was not shared to the group." ); done(); }); }); it("should throw if we cannot add the user as a group admin", (done) => { fetchMock .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", { ...OrgAdminUserResponse, groups: [], } ) .once( "https://myorg.maps.arcgis.com/sharing/rest/search", NoResultsSearchResponse ) .get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupNonMemberUserResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/casey?f=json&token=fake-token", { username: "casey", orgId: "qWAReEOCnD7eTxOe", groups: [ { id: "t6b", userMembership: { memberType: "admin", }, }, ] as any[], } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/addUsers", { errors: [new ArcGISAuthError("my error", 717)] } ); return shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", confirmItemControl: true, }) .then(() => { expect("").toBe("Should Throw, but it returned"); fail(); }) .catch((e) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); expect(e.message).toBe( "Error adding jsmith as member to edit group t6b. Consequently item n3v was not shared to the group." ); done(); }); }); it("should throw when a non org admin, non group member attempts to share a view group", (done) => { fetchMock .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", { ...AnonUserResponse, orgId: "qWAReEOCnD7eTxOe" } ) .once( "https://myorg.maps.arcgis.com/sharing/rest/search", NoResultsSearchResponse ) .get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupNonMemberUserResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/casey?f=json&token=fake-token", { username: "casey", orgId: "qWAReEOCnD7eTxOe", groups: [ { id: "t6b", userMembership: { memberType: "member", }, }, ] as any[], } ); return shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", confirmItemControl: false, }) .then(() => { expect("").toBe("Should Throw, but it returned"); fail(); }) .catch((e) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); expect(e.message).toBe( "This item can not be shared by jsmith as they are not a member of the specified group t6b." ); done(); }); }); it("should throw if owner is in other org", (done) => { fetchMock .get( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", OrgAdminUserResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/search", NoResultsSearchResponse ) .get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupOwnerResponse ) .get( "https://myorg.maps.arcgis.com/sharing/rest/community/users/casey?f=json&token=fake-token", { username: "casey", orgId: "some-other-org", groups: [] as any[], } ); return shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", confirmItemControl: true, }) .then(() => { expect("").toBe("Should Throw, but it returned"); fail(); }) .catch((e) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); expect(e.message).toBe( "User casey is not a member of the same org as jsmith. Consequently they can not be added added to group t6b nor can item n3v be shared to the group." ); done(); }); }); it("should throw if owner has > 511 groups", (done) => { const caseyUser = { username: "casey", orgId: "qWAReEOCnD7eTxOe", groups: new Array(512), }; caseyUser.groups.fill({ id: "not-real-group" }); fetchMock .get( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", OrgAdminUserResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/search", NoResultsSearchResponse ) .get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupOwnerResponse ) .get( "https://myorg.maps.arcgis.com/sharing/rest/community/users/casey?f=json&token=fake-token", caseyUser ); return shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", confirmItemControl: true, }) .then(() => { expect("").toBe("Should Throw, but it returned"); fail(); }) .catch((e) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); expect(e.message).toBe( "User casey already has 512 groups, and can not be added to group t6b. Consequently item n3v can not be shared to the group." ); done(); }); }); it("should throw when updateUserMemberships fails", (done) => { fetchMock .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", OrgAdminUserResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/search", NoResultsSearchResponse ) .get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupOwnerResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/casey?f=json&token=fake-token", { username: "casey", orgId: "qWAReEOCnD7eTxOe", groups: [ { id: "t6b", userMembership: { memberType: "member", }, }, ] as any[], } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/updateUsers", { throws: true } ); return shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", confirmItemControl: true, }) .then(() => { expect("").toBe("Should Throw, but it returned"); fail(); }) .catch((e) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); const addUsersOptions: RequestInit = fetchMock.lastOptions( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/updateUsers" ); expect(addUsersOptions.body).toContain("admins=casey"); expect(e.message).toBe( "Error promoting user casey to admin in edit group t6b. Consequently item n3v was not shared to the group." ); done(); }); }); it("should add the admin user as a member, share the item, then remove the admin from the group", (done) => { fetchMock .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", { ...OrgAdminUserResponse, groups: [], } ) .once( "https://myorg.maps.arcgis.com/sharing/rest/search", NoResultsSearchResponse ) .get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupNonMemberUserResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/casey?f=json&token=fake-token", { username: "casey", orgId: "qWAReEOCnD7eTxOe", groups: [ { id: "t6b", userMembership: { memberType: "admin", }, }, ] as any[], } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/addUsers", { notAdded: [] } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share", { notSharedWith: [], itemId: "nv3" } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/removeUsers", { notRemoved: [] } ); return shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", confirmItemControl: true, }) .then((result) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); const shareOptions: RequestInit = fetchMock.lastOptions( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share" ); expect(shareOptions.body).toContain("groups=t6b"); expect(shareOptions.body).toContain("confirmItemControl=true"); done(); }) .catch((e) => { fail(); }); }); it("should add the admin user as a member, share the item, then suppress any removeUser errors", (done) => { fetchMock .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", { ...OrgAdminUserResponse, groups: [], } ) .once( "https://myorg.maps.arcgis.com/sharing/rest/search", NoResultsSearchResponse ) .get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupNonMemberUserResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/casey?f=json&token=fake-token", { username: "casey", orgId: "qWAReEOCnD7eTxOe", groups: [ { id: "t6b", userMembership: { memberType: "admin", }, }, ] as any[], } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/addUsers", { notAdded: [] } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share", { notSharedWith: [], itemId: "nv3" } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/removeUsers", { throws: true } ); return shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", confirmItemControl: true, }) .then((result) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); const shareOptions: RequestInit = fetchMock.lastOptions( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share" ); expect(shareOptions.body).toContain("groups=t6b"); expect(shareOptions.body).toContain("confirmItemControl=true"); done(); }) .catch((e) => { fail(); }); }); it("should upgrade user to group admin, add admin as member, then share item, then remove admin user", (done) => { fetchMock .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", { ...OrgAdminUserResponse, groups: [ { ...OrgAdminUserResponse.groups[0], userMembership: { ...OrgAdminUserResponse.groups[0].userMembership, memberType: "member", }, }, ], } ) .once( "https://myorg.maps.arcgis.com/sharing/rest/search", NoResultsSearchResponse ) .get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupNonMemberResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/casey?f=json&token=fake-token", { username: "casey", orgId: "qWAReEOCnD7eTxOe", groups: [ { id: "t6b", userMembership: { memberType: "member", }, }, ] as any[], } ) .once( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/updateUsers", { results: [{ username: "casey", success: true }] } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share", { notSharedWith: [], itemId: "n3v" } ); shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", confirmItemControl: true, }) .then((result) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); // verify we added casey to t6b const addUsersOptions: RequestInit = fetchMock.lastOptions( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/updateUsers" ); expect(addUsersOptions.body).toContain("admins=casey"); // verify we shared the item const shareOptions: RequestInit = fetchMock.lastOptions( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share" ); expect(shareOptions.body).toContain("groups=t6b"); expect(shareOptions.body).toContain("confirmItemControl=true"); done(); }) .catch((e) => { fail(); }); }); }); describe("ensureMembership", function () { it("should revert the user promotion and suppress resolved error", (done) => { fetchMock .once( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/updateUsers", { results: [{ username: "jsmith", success: true }] } ) .once( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/updateUsers", { results: [{ username: "jsmith", success: false }] } ); const { revert } = ensureMembership( GroupAdminUserResponse, GroupMemberUserResponse, true, "some error message", { authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", confirmItemControl: true, } ); revert({ notSharedWith: [] } as ISharingResponse) .then(() => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); done(); }) .catch((e) => { fail(); }); }); it("should revert the user promotion and suppress rejected error", (done) => { fetchMock .once( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/updateUsers", { results: [{ username: "jsmith", success: true }] } ) .once( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b/updateUsers", { throws: true } ); const { revert } = ensureMembership( GroupAdminUserResponse, GroupMemberUserResponse, true, "some error message", { authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", confirmItemControl: true, } ); revert({ notSharedWith: [] } as ISharingResponse) .then(() => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); done(); }) .catch((e) => { fail(); }); }); }); describe("share item to admin user's favorites group ::", () => { it("should share item", (done) => { fetchMock .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", { ...OrgAdminUserResponse, favGroupId: "t6b", } ) .once( "https://myorg.maps.arcgis.com/sharing/rest/search", NoResultsSearchResponse ) .get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupOwnerResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/casey?f=json&token=fake-token", { username: "casey", orgId: "qWAReEOCnD7eTxOe", groups: [] as any[], } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share", { notSharedWith: [], itemId: "n3v" } ); shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", }) .then((result) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); // verify we shared the item const shareOptions: RequestInit = fetchMock.lastOptions( "https://myorg.maps.arcgis.com/sharing/rest/content/users/casey/items/n3v/share" ); expect(shareOptions.body).toContain("groups=t6b"); done(); }) .catch((e) => { fail(); }); }); }); describe("share item from another org to admin user's favorites group ::", () => { it("should share item", (done) => { fetchMock .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/jsmith?f=json&token=fake-token", { ...OrgAdminUserResponse, favGroupId: "t6b", } ) .once( "https://myorg.maps.arcgis.com/sharing/rest/search", NoResultsSearchResponse ) .get( "https://myorg.maps.arcgis.com/sharing/rest/community/groups/t6b?f=json&token=fake-token", GroupOwnerResponse ) .once( "https://myorg.maps.arcgis.com/sharing/rest/community/users/casey?f=json&token=fake-token", { username: "casey", orgId: "SOMEOTHERORG", groups: [] as any[], } ) .post( "https://myorg.maps.arcgis.com/sharing/rest/content/items/n3v/share", { notSharedWith: [], itemId: "n3v" } ); shareItemWithGroup({ authentication: MOCK_USER_SESSION, id: "n3v", groupId: "t6b", owner: "casey", }) .then((result) => { expect(fetchMock.done()).toBeTruthy( "All fetchMocks should have been called" ); // verify we shared the item const shareOptions: RequestInit = fetchMock.lastOptions( "https://myorg.maps.arcgis.com/sharing/rest/content/items/n3v/share" ); expect(shareOptions.body).toContain("groups=t6b"); done(); }) .catch((e) => { fail(); }); }); }); });
the_stack
import i18next from "i18next"; import { action, computed, runInAction } from "mobx"; import { createTransformer } from "mobx-utils"; import URI from "urijs"; import isDefined from "../../../Core/isDefined"; import { JsonObject } from "../../../Core/Json"; import loadJson from "../../../Core/loadJson"; import ReferenceMixin from "../../../ModelMixins/ReferenceMixin"; import UrlMixin from "../../../ModelMixins/UrlMixin"; import { InfoSectionTraits } from "../../../Traits/TraitsClasses/CatalogMemberTraits"; import CkanItemReferenceTraits from "../../../Traits/TraitsClasses/CkanItemReferenceTraits"; import CkanResourceFormatTraits from "../../../Traits/TraitsClasses/CkanResourceFormatTraits"; import CkanSharedTraits from "../../../Traits/TraitsClasses/CkanSharedTraits"; import { RectangleTraits } from "../../../Traits/TraitsClasses/MappableTraits"; import ModelTraits from "../../../Traits/ModelTraits"; import CatalogMemberFactory from "../CatalogMemberFactory"; import CkanCatalogGroup, { createInheritedCkanSharedTraitsStratum } from "./CkanCatalogGroup"; import { CkanDataset, CkanDatasetServerResponse, CkanResource, CkanResourceServerResponse } from "./CkanDefinitions"; import CommonStrata from "../../Definition/CommonStrata"; import CreateModel from "../../Definition/CreateModel"; import createStratumInstance from "../../Definition/createStratumInstance"; import LoadableStratum from "../../Definition/LoadableStratum"; import { BaseModel } from "../../Definition/Model"; import ModelPropertiesFromTraits from "../../Definition/ModelPropertiesFromTraits"; import proxyCatalogItemUrl from "../proxyCatalogItemUrl"; import StratumFromTraits from "../../Definition/StratumFromTraits"; import StratumOrder from "../../Definition/StratumOrder"; import Terria from "../../Terria"; import WebMapServiceCatalogItem from "../Ows/WebMapServiceCatalogItem"; export class CkanDatasetStratum extends LoadableStratum( CkanItemReferenceTraits ) { static stratumName = "ckanDataset"; constructor( private readonly ckanItemReference: CkanItemReference, private readonly ckanCatalogGroup: CkanCatalogGroup | undefined ) { super(); } duplicateLoadableStratum(newModel: BaseModel): this { return new CkanDatasetStratum( this.ckanItemReference, this.ckanCatalogGroup ) as this; } static async load( ckanItemReference: CkanItemReference, ckanCatalogGroup: CkanCatalogGroup | undefined ) { if (ckanItemReference._ckanDataset === undefined) { // If we've got a dataset and no defined resource if ( ckanItemReference.datasetId !== undefined && ckanItemReference.resourceId !== undefined ) { ckanItemReference._ckanDataset = await loadCkanDataset( ckanItemReference ); ckanItemReference._ckanResource = findResourceInDataset( ckanItemReference._ckanDataset, ckanItemReference.resourceId ); ckanItemReference.setSupportedFormatFromResource( ckanItemReference._ckanResource ); } else if ( ckanItemReference.datasetId !== undefined && ckanItemReference.resourceId === undefined ) { ckanItemReference._ckanDataset = await loadCkanDataset( ckanItemReference ); const matched = ckanItemReference.findFirstValidResource( ckanItemReference._ckanDataset ); if (matched === undefined) return undefined; ckanItemReference._ckanResource = matched.ckanResource; ckanItemReference._supportedFormat = matched.supportedFormat; } else if ( ckanItemReference.datasetId === undefined && ckanItemReference.resourceId !== undefined ) { ckanItemReference._ckanResource = await loadCkanResource( ckanItemReference ); ckanItemReference._supportedFormat = ckanItemReference.isResourceInSupportedFormats( ckanItemReference._ckanResource ); } } return new CkanDatasetStratum(ckanItemReference, ckanCatalogGroup); } @computed get ckanDataset(): CkanDataset | undefined { return this.ckanItemReference._ckanDataset; } @computed get ckanResource(): CkanResource | undefined { return this.ckanItemReference._ckanResource; } @computed get url() { if (this.ckanResource === undefined) return undefined; if (this.ckanItemReference._supportedFormat !== undefined) { if ( this.ckanItemReference._supportedFormat.definition.type === "wms" && this.ckanResource.wms_api_url ) { return this.ckanResource.wms_api_url; } } return this.ckanResource.url; } @computed get name() { if (this.ckanResource === undefined) return undefined; if (this.ckanItemReference.useResourceName) return this.ckanResource.name; // via @steve9164 /** Switched the order [check `useCombinationNameWhereMultipleResources` * first ] that these are checked so the default is checked last. Otherwise * setting useCombinationNameWhereMultipleResources without setting * useDatasetNameAndFormatWhereMultipleResources to false doesn't do * anything */ if (this.ckanDataset) { if ( this.ckanItemReference.useCombinationNameWhereMultipleResources && this.ckanDataset.resources.length > 1 ) { return this.ckanDataset.title + " - " + this.ckanResource.name; } if ( this.ckanItemReference.useDatasetNameAndFormatWhereMultipleResources && this.ckanDataset.resources.length > 1 ) { return this.ckanDataset.title + " - " + this.ckanResource.format; } return this.ckanDataset.title; } return this.ckanResource.name; } @computed get rectangle() { if (this.ckanDataset === undefined) return undefined; if (this.ckanDataset.extras !== undefined) { const out: number[] = []; const bboxExtras = this.ckanDataset.extras.forEach(e => { if (e.key === "bbox-west-long") out[0] = parseFloat(e.value); if (e.key === "bbox-south-lat") out[1] = parseFloat(e.value); if (e.key === "bbox-north-lat") out[2] = parseFloat(e.value); if (e.key === "bbox-east-long") out[3] = parseFloat(e.value); }); if (out.length === 4) { return createStratumInstance(RectangleTraits, { west: out[0], south: out[1], east: out[2], north: out[3] }); } } if (this.ckanDataset.geo_coverage !== undefined) { var bboxString = this.ckanDataset.geo_coverage; var parts = bboxString.split(","); if (parts.length === 4) { return createStratumInstance(RectangleTraits, { west: parseInt(parts[0]), south: parseInt(parts[1]), east: parseInt(parts[2]), north: parseInt(parts[3]) }); } } if ( isDefined(this.ckanDataset.spatial) && this.ckanDataset.spatial !== "" ) { var gj = JSON.parse(this.ckanDataset.spatial); if (gj.type === "Polygon" && gj.coordinates[0].length === 5) { return createStratumInstance(RectangleTraits, { west: gj.coordinates[0][0][0], south: gj.coordinates[0][0][1], east: gj.coordinates[0][2][0], north: gj.coordinates[0][2][1] }); } } return undefined; } @computed get info() { function prettifyDate(date: string) { if (date.match(/^\d\d\d\d-\d\d-\d\d.*/)) { return date.substr(0, 10); } else return date; } const outArray: StratumFromTraits<InfoSectionTraits>[] = []; if (this.ckanDataset === undefined) return outArray; if (this.ckanDataset.license_url !== undefined) { outArray.push( createStratumInstance(InfoSectionTraits, { name: i18next.t("models.ckan.licence"), content: `[${this.ckanDataset.license_title || this.ckanDataset.license_url}](${this.ckanDataset.license_url})` }) ); } else if (this.ckanDataset.license_title !== undefined) { outArray.push( createStratumInstance(InfoSectionTraits, { name: i18next.t("models.ckan.licence"), content: this.ckanDataset.license_title }) ); } outArray.push( createStratumInstance(InfoSectionTraits, { name: i18next.t("models.ckan.contact_point"), content: this.ckanDataset.contact_point }), createStratumInstance(InfoSectionTraits, { name: i18next.t("models.ckan.datasetDescription"), content: this.ckanDataset.notes }), createStratumInstance(InfoSectionTraits, { name: i18next.t("models.ckan.author"), content: this.ckanDataset.author }) ); if (this.ckanDataset.organization) { outArray.push( createStratumInstance(InfoSectionTraits, { name: i18next.t("models.ckan.datasetCustodian"), content: this.ckanDataset.organization.description || this.ckanDataset.organization.title }) ); } outArray.push( createStratumInstance(InfoSectionTraits, { name: i18next.t("models.ckan.metadata_created"), content: prettifyDate(this.ckanDataset.metadata_created) }), createStratumInstance(InfoSectionTraits, { name: i18next.t("models.ckan.metadata_modified"), content: prettifyDate(this.ckanDataset.metadata_modified) }), createStratumInstance(InfoSectionTraits, { name: i18next.t("models.ckan.update_freq"), content: this.ckanDataset.update_freq }) ); return outArray; } } StratumOrder.addLoadStratum(CkanDatasetStratum.stratumName); export default class CkanItemReference extends UrlMixin( ReferenceMixin(CreateModel(CkanItemReferenceTraits)) ) { static readonly defaultSupportedFormats: StratumFromTraits< CkanResourceFormatTraits >[] = [ createStratumInstance(CkanResourceFormatTraits, { id: "WMS", formatRegex: "^wms$", definition: { type: "wms" } }), createStratumInstance(CkanResourceFormatTraits, { id: "CSV", formatRegex: "^csv-geo-", definition: { type: "csv" } }), createStratumInstance(CkanResourceFormatTraits, { id: "GeoJson", formatRegex: "^geojson$", definition: { type: "geojson" } }), createStratumInstance(CkanResourceFormatTraits, { id: "ArcGIS MapServer", formatRegex: "^esri rest$", definition: { type: "esri-mapServer" } }), createStratumInstance(CkanResourceFormatTraits, { id: "ArcGIS FeatureServer", formatRegex: "^esri rest$", definition: { type: "esri-featureServer" } }), createStratumInstance(CkanResourceFormatTraits, { id: "Kml", formatRegex: "^km[lz]$", definition: { type: "kml" } }), createStratumInstance(CkanResourceFormatTraits, { id: "Czml", formatRegex: "^czml$", definition: { type: "czml" } }) ]; static readonly type = "ckan-item"; get type() { return CkanItemReference.type; } get typeName() { return i18next.t("models.ckan.name"); } _ckanDataset: CkanDataset | undefined = undefined; _ckanResource: CkanResource | undefined = undefined; _ckanCatalogGroup: CkanCatalogGroup | undefined = undefined; _supportedFormat: PreparedSupportedFormat | undefined = undefined; constructor( id: string | undefined, terria: Terria, sourceReference?: BaseModel, strata?: Map<string, StratumFromTraits<ModelTraits>> ) { super(id, terria, sourceReference, strata); this.setTrait( CommonStrata.defaults, "supportedResourceFormats", CkanItemReference.defaultSupportedFormats ); } @computed get preparedSupportedFormats(): PreparedSupportedFormat[] { return ( this.supportedResourceFormats && this.supportedResourceFormats.map(prepareSupportedFormat) ); } isResourceInSupportedFormats( resource: CkanResource | undefined ): PreparedSupportedFormat | undefined { if (resource === undefined) return undefined; for (let i = 0; i < this.preparedSupportedFormats.length; ++i) { const format = this.preparedSupportedFormats[i]; if (format.formatRegex === undefined) continue; if (format.formatRegex.test(resource.format)) { return format; } } return undefined; } findFirstValidResource( dataset: CkanDataset | undefined ): CkanResourceWithFormat | undefined { if (dataset === undefined) return undefined; for (let i = 0; i < dataset.resources.length; ++i) { const r = dataset.resources[i]; const supportedFormat = this.isResourceInSupportedFormats(r); if (supportedFormat !== undefined) { return { ckanResource: r, supportedFormat: supportedFormat }; } } return undefined; } setDataset(ckanDataset: CkanDataset) { this._ckanDataset = ckanDataset; } setResource(ckanResource: CkanResource) { this._ckanResource = ckanResource; } setCkanCatalog(ckanCatalogGroup: CkanCatalogGroup) { this._ckanCatalogGroup = ckanCatalogGroup; } setSupportedFormatFromResource(resource: CkanResource | undefined) { this._supportedFormat = this.isResourceInSupportedFormats(resource); } @computed get cacheDuration(): string { if (isDefined(super.cacheDuration)) { return super.cacheDuration; } return "1d"; } // We will first attach this to the CkanItemReference // and then we'll attach it to the target model // I wonder if it needs to be on both? async setCkanStrata(model: BaseModel) { // not sure why this needs to be any const stratum = await CkanDatasetStratum.load(this, this._ckanCatalogGroup); if (stratum === undefined) return; runInAction(() => { model.strata.set(CkanDatasetStratum.stratumName, stratum); }); } @action setSharedStratum( inheritedPropertiesStratum: Readonly<StratumFromTraits<CkanSharedTraits>> ) { // The values in this stratum should not be updated as the same object is used // in all CkanItemReferences this.strata.set( createInheritedCkanSharedTraitsStratum.stratumName, inheritedPropertiesStratum ); } async forceLoadReference( previousTarget: BaseModel | undefined ): Promise<BaseModel | undefined> { await this.setCkanStrata(this); if (this._supportedFormat === undefined) return undefined; const model = CatalogMemberFactory.create( this._supportedFormat.definition.type as string, this.uniqueId, this.terria, this ); if (model === undefined) return; previousTarget = model; await this.setCkanStrata(model); const defintionStratum = this.strata.get(CommonStrata.definition); if (defintionStratum) { model.strata.set(CommonStrata.definition, defintionStratum); model.setTrait(CommonStrata.definition, "url", undefined); } // Overrides for specific catalog types if ( model instanceof WebMapServiceCatalogItem && this._ckanResource?.wms_layer ) { model.setTrait( CommonStrata.definition, "layers", this._ckanResource.wms_layer ); } // Tried to make this sequence an updateModelFromJson but wouldn't work? // updateModelFromJson(model, CommonStrata.override, {itemProperties: this.itemProperties}) // Also tried this other approach which works from the CkanCatalogGroup // this.setItemProperties(model, this.itemProperties) if (this.itemProperties !== undefined) { const ipKeys = Object.keys(this.itemProperties); ipKeys.forEach(p => { // @ts-ignore model.setTrait(CommonStrata.override, p, this.itemProperties[p]); }); } return model; } } interface CkanResourceWithFormat { supportedFormat: PreparedSupportedFormat; ckanResource: CkanResource; } interface PreparedSupportedFormat { formatRegex: RegExp | undefined; definition: JsonObject; } async function loadCkanDataset(ckanItem: CkanItemReference) { var uri = new URI(ckanItem.url) .segment("api/3/action/package_show") .addQuery({ id: ckanItem.datasetId }); const response: CkanDatasetServerResponse = await loadJson( proxyCatalogItemUrl(ckanItem, uri.toString()) ); if (response.result) return response.result; return undefined; } async function loadCkanResource(ckanItem: CkanItemReference) { var uri = new URI(ckanItem.url) .segment("api/3/action/resource_show") .addQuery({ id: ckanItem.resourceId }); const response: CkanResourceServerResponse = await loadJson( proxyCatalogItemUrl(ckanItem, uri.toString()) ); if (response.result) return response.result; return undefined; } function findResourceInDataset( ckanDataset: CkanDataset | undefined, resourceId: string ) { if (ckanDataset === undefined) return undefined; for (let i = 0; i < ckanDataset.resources.length; ++i) { if (ckanDataset.resources[i].id === resourceId) { return ckanDataset.resources[i]; } } return undefined; } const prepareSupportedFormat = createTransformer( (format: ModelPropertiesFromTraits<CkanResourceFormatTraits>) => { return { formatRegex: format.formatRegex ? new RegExp(format.formatRegex, "i") : undefined, definition: format.definition || {} }; } );
the_stack
namespace colibri.ui.controls { class CloseIconManager { private _iconControl: controls.IconControl; private _icon: IImage; private _overIcon: IImage; constructor() { this._iconControl = new controls.IconControl(); this._iconControl.getCanvas().classList.add("TabPaneLabelCloseIcon"); this._iconControl.getCanvas().addEventListener("mouseenter", e => { this._iconControl.setIcon(this._overIcon); }); this._iconControl.getCanvas().addEventListener("mouseleave", e => { this._iconControl.setIcon(this._icon); }); } static setManager(element: HTMLElement, manager: CloseIconManager) { element["__CloseIconManager"] = manager; } static getManager(element: HTMLElement): CloseIconManager { return element["__CloseIconManager"]; } setDefaultIcon(icon: IImage) { this._icon = icon; this._iconControl.setIcon(icon); } setOverIcon(icon: IImage) { this._overIcon = icon; } repaint() { this._iconControl.repaint(); } getElement() { return this._iconControl.getCanvas(); } } class TabIconManager { private _icon: IImage; private _canvas: HTMLCanvasElement; private constructor(canvas: HTMLCanvasElement, icon: IImage) { this._canvas = canvas; this._icon = icon; } static createElement(icon: IImage, size: number) { const canvas = document.createElement("canvas"); canvas.classList.add("TabIconImage"); const manager = new TabIconManager(canvas, icon); canvas["__TabIconManager"] = manager; manager.resize(size); return canvas; } resize(size: number) { size = Math.max(size, RENDER_ICON_SIZE); if (this._icon && this._icon instanceof IconImage) { size = RENDER_ICON_SIZE; } this._canvas.width = this._canvas.height = size; this._canvas.style.width = this._canvas.style.height = size + "px"; this.repaint(); } static getManager(canvas: HTMLCanvasElement): TabIconManager { return canvas["__TabIconManager"]; } setIcon(icon: IImage) { this._icon = icon; this.repaint(); } repaint() { Controls.adjustCanvasDPI(this._canvas); const ctx = this._canvas.getContext("2d"); ctx.imageSmoothingEnabled = false; ctx.clearRect(0, 0, this._canvas.width, this._canvas.height); if (!this._icon) { return; } const w = this._icon.getWidth(); const h = this._icon.getHeight(); const canvasWidth = this._canvas.width / DEVICE_PIXEL_RATIO; const canvasHeight = this._canvas.height / DEVICE_PIXEL_RATIO; if (w === ICON_SIZE && h === ICON_SIZE) { // is a real, fixed size icon image this._icon.paint( ctx, (canvasWidth - RENDER_ICON_SIZE) / 2, (canvasHeight - RENDER_ICON_SIZE) / 2, RENDER_ICON_SIZE, RENDER_ICON_SIZE, false ); } else { // is a scalable icon image this._icon.paint(ctx, 0, 0, canvasWidth, canvasHeight, true); } } } // export const EVENT_TAB_CLOSED = "tabClosed"; // export const EVENT_TAB_SELECTED = "tabSelected"; // export const EVENT_TAB_LABEL_RESIZED = "tabResized"; export class TabPane extends Control { public eventTabClosed = new ListenerList(); public eventTabSelected = new ListenerList(); public eventTabLabelResized = new ListenerList(); public eventTabSectionSelected = new ListenerList(); private _titleBarElement: HTMLElement; private _contentAreaElement: HTMLElement; private _iconSize: number; private static _selectedTimeCounter: number = 0; private _themeListener: any; constructor(...classList: string[]) { super("div", "TabPane", ...classList); this._titleBarElement = document.createElement("div"); this._titleBarElement.classList.add("TabPaneTitleBar"); this.getElement().appendChild(this._titleBarElement); this._contentAreaElement = document.createElement("div"); this._contentAreaElement.classList.add("TabPaneContentArea"); this.getElement().appendChild(this._contentAreaElement); this._iconSize = RENDER_ICON_SIZE; this.registerThemeListener(); } private registerThemeListener() { this._themeListener = () => { if (this.getElement().isConnected) { const result = this.getElement().getElementsByClassName("TabIconImage"); for (let i = 0; i < result.length; i++) { const e = result.item(i); const manager = TabIconManager.getManager(e as any); manager.repaint(); } } else { colibri.Platform.getWorkbench().eventThemeChanged.removeListener(this._themeListener); } }; colibri.Platform.getWorkbench().eventThemeChanged.addListener(this._themeListener); } private findSectionElement(label: HTMLElement, section: string) { const sectionElements = label.querySelectorAll(".TabPaneLabelSection"); for (let i = 0; i < sectionElements.length; i++) { const element = sectionElements.item(i) as HTMLDivElement; if (element.id === "section-" + section) { return element; } } return undefined; } removeTabSection(label: HTMLElement, section: string) { const element = this.findSectionElement(label, section); if (element) { element.remove(); this.eventTabSectionSelected.fire(undefined); } } removeAllSections(label: HTMLElement, notify = true) { const sectionsElement = label.querySelectorAll(".TabPaneLabelSections")[0] as HTMLDivElement; sectionsElement.innerHTML = ""; if (notify) { this.eventTabSectionSelected.fire(undefined); } } addTabSection(label: HTMLElement, section: string, tabId?: string) { const sectionsElement = label.querySelectorAll(".TabPaneLabelSections")[0] as HTMLDivElement; let visible = true; if (sectionsElement.children.length === 0) { const expandIcon = ColibriPlugin.getInstance().getIcon(ICON_CONTROL_SECTION_EXPAND); const collapseIcon = ColibriPlugin.getInstance().getIcon(ICON_CONTROL_SECTION_COLLAPSE_LEFT); const storageKey = `TabPane[${tabId}].expanded`; let icon = expandIcon; if (tabId) { visible = (localStorage.getItem(storageKey) || "expanded") === "expanded"; icon = visible ? expandIcon : collapseIcon; } const iconControl = new IconControl(icon); iconControl.getCanvas().classList.add("CollapseIcon"); iconControl["__expanded"] = visible; sectionsElement.appendChild(iconControl.getCanvas()); iconControl.getCanvas().addEventListener("click", e => { if (iconControl.getIcon() === expandIcon) { iconControl.setIcon(collapseIcon); } else { iconControl.setIcon(expandIcon); } visible = iconControl.getIcon() === expandIcon; iconControl["__expanded"] = visible; const sections = sectionsElement.querySelectorAll(".TabPaneLabelSection"); for (let i = 0; i < sections.length; i++) { const elem = sections.item(i) as HTMLElement; elem.style.display = visible ? "block" : "none"; } if (tabId) { localStorage.setItem(storageKey, visible ? "expanded" : "collapsed"); } }); } else { const iconControl = IconControl.getIconControlOf(sectionsElement.firstChild as HTMLElement); visible = iconControl["__expanded"]; } const sectionElement = document.createElement("div"); sectionElement.classList.add("TabPaneLabelSection"); sectionElement.id = "section-" + section; sectionElement.style.display = visible ? "block" : "none"; sectionElement.innerHTML = section; sectionsElement.appendChild(sectionElement); sectionElement.addEventListener("click", e => { if (sectionElement.classList.contains("selected")) { sectionElement.classList.remove("selected"); this.eventTabSectionSelected.fire(undefined); } else { for (let i = 0; i < sectionsElement.children.length; i++) { const elem = sectionsElement.children.item(i); elem.classList.remove("selected"); } sectionElement.classList.add("selected"); this.eventTabSectionSelected.fire(section); } }); } selectTabSection(label: HTMLElement, section: string) { const sectionElements = label.querySelectorAll(".TabPaneLabelSection"); let found = false; for (let i = 0; i < sectionElements.length; i++) { const element = sectionElements.item(i) as HTMLDivElement; element.classList.remove("selected"); if (section && element.id === "section-" + section) { element.classList.add("selected"); found = true; } } this.eventTabSectionSelected.fire(found ? section : undefined); } addTab(label: string, icon: IImage, content: Control, closeable = false, selectIt = true): void { const labelElement = this.makeLabel(label, icon, closeable); this._titleBarElement.appendChild(labelElement); labelElement.addEventListener("mousedown", e => { if (e.button !== 0) { e.preventDefault(); e.stopImmediatePropagation(); return; } if (TabPane.isTabCloseIcon(e.target as HTMLElement)) { return; } this.selectTab(labelElement); }); if (closeable) { labelElement.addEventListener("mouseup", e => { if (e.button === 1) { e.preventDefault(); e.stopImmediatePropagation(); this.closeTabLabel(labelElement); return; } }); } const contentArea = new Control("div", "ContentArea"); contentArea.add(content); this._contentAreaElement.appendChild(contentArea.getElement()); labelElement["__contentArea"] = contentArea.getElement(); if (selectIt) { if (this._titleBarElement.childElementCount === 1) { this.selectTab(labelElement); } } } getTabIconSize() { return this._iconSize; } setTabIconSize(size: number) { this._iconSize = Math.max(RENDER_ICON_SIZE, size); for (let i = 0; i < this._titleBarElement.children.length; i++) { const label = this._titleBarElement.children.item(i); const iconCanvas = label.firstChild as HTMLCanvasElement; TabIconManager.getManager(iconCanvas).resize(this._iconSize); this.layout(); } this.eventTabLabelResized.fire(); } incrementTabIconSize(amount: number) { this.setTabIconSize(this._iconSize + amount); } private makeLabel(label: string, icon: IImage, closeable: boolean): HTMLElement { const labelElement = document.createElement("div"); labelElement.classList.add("TabPaneLabel"); const tabIconElement = TabIconManager.createElement(icon, this._iconSize); labelElement.appendChild(tabIconElement); const textElement = document.createElement("span"); textElement.innerHTML = label; labelElement.appendChild(textElement); const sectionsElement = document.createElement("div"); sectionsElement.classList.add("TabPaneLabelSections"); labelElement.appendChild(sectionsElement); if (closeable) { const manager = new CloseIconManager(); manager.setDefaultIcon(ColibriPlugin.getInstance().getIcon(ICON_CONTROL_CLOSE)); manager.repaint(); manager.getElement().addEventListener("click", e => { e.stopImmediatePropagation(); this.closeTabLabel(labelElement); }); labelElement.appendChild(manager.getElement()); labelElement.classList.add("closeable"); CloseIconManager.setManager(labelElement, manager); } labelElement.addEventListener("contextmenu", e => this.showTabLabelMenu(e, labelElement)); return labelElement; } private showTabLabelMenu(e: MouseEvent, labelElement: HTMLElement) { e.preventDefault(); const menu = new Menu(); this.fillTabMenu(menu, labelElement); menu.createWithEvent(e); } protected fillTabMenu(menu: Menu, labelElement: HTMLElement) { // nothing } setTabCloseIcons(labelElement: HTMLElement, icon: IImage, overIcon: IImage) { const manager = CloseIconManager.getManager(labelElement); if (manager) { manager.setDefaultIcon(icon); manager.setOverIcon(overIcon); manager.repaint(); } } closeTab(content: controls.Control) { const label = this.getLabelFromContent(content); if (label) { this.closeTabLabel(label); } } closeAll() { this._titleBarElement.innerHTML = ""; this._contentAreaElement.innerHTML = ""; } protected closeTabLabel(labelElement: HTMLElement): void { { const content = TabPane.getContentFromLabel(labelElement); if (!this.eventTabClosed.fire(content)) { return; } } const selectedLabel = this.getSelectedLabelElement(); this._titleBarElement.removeChild(labelElement); const contentArea = labelElement["__contentArea"] as HTMLElement; this._contentAreaElement.removeChild(contentArea); if (selectedLabel === labelElement) { let toSelectLabel: HTMLElement = null; let maxTime = -1; for (let j = 0; j < this._titleBarElement.children.length; j++) { const label = this._titleBarElement.children.item(j); const time = label["__selected_time"] as number || 0; if (time > maxTime) { toSelectLabel = label as HTMLElement; maxTime = time; } } if (toSelectLabel) { this.selectTab(toSelectLabel); } } } setTabTitle(content: Control, title: string, icon?: IImage) { for (let i = 0; i < this._titleBarElement.childElementCount; i++) { const label = this._titleBarElement.children.item(i) as HTMLElement; const content2 = TabPane.getContentFromLabel(label); if (content2 === content) { const iconElement: HTMLCanvasElement = label.firstChild as HTMLCanvasElement; const textElement = iconElement.nextSibling as HTMLElement; const manager = TabIconManager.getManager(iconElement); manager.setIcon(icon); manager.repaint(); textElement.innerHTML = title; } } } static isTabCloseIcon(element: HTMLElement) { return element.classList.contains("TabPaneLabelCloseIcon"); } static isTabLabel(element: HTMLElement) { return element.classList.contains("TabPaneLabel"); } getLabelFromContent(content: Control) { for (let i = 0; i < this._titleBarElement.childElementCount; i++) { const label = this._titleBarElement.children.item(i) as HTMLElement; const content2 = TabPane.getContentFromLabel(label); if (content2 === content) { return label; } } return null; } private static getContentAreaFromLabel(labelElement: HTMLElement): HTMLElement { return labelElement["__contentArea"]; } static getContentFromLabel(labelElement: HTMLElement) { return Control.getControlOf(this.getContentAreaFromLabel(labelElement).firstChild as HTMLElement); } selectTabWithContent(content: Control) { const label = this.getLabelFromContent(content); if (label) { this.selectTab(label); } } protected selectTab(toSelectLabel: HTMLElement): void { if (toSelectLabel) { toSelectLabel["__selected_time"] = TabPane._selectedTimeCounter++; } const selectedLabelElement = this.getSelectedLabelElement(); if (selectedLabelElement) { if (selectedLabelElement === toSelectLabel) { return; } selectedLabelElement.classList.remove("selected"); const selectedContentArea = TabPane.getContentAreaFromLabel(selectedLabelElement); selectedContentArea.classList.remove("selected"); } toSelectLabel.classList.add("selected"); const toSelectContentArea = TabPane.getContentAreaFromLabel(toSelectLabel); toSelectContentArea.classList.add("selected"); toSelectLabel.scrollIntoView(); this.eventTabSelected.fire(TabPane.getContentFromLabel(toSelectLabel)); this.dispatchLayoutEvent(); } getSelectedTabContent(): Control { const label = this.getSelectedLabelElement(); if (label) { const area = TabPane.getContentAreaFromLabel(label); return Control.getControlOf(area.firstChild as HTMLElement); } return null; } isSelectedLabel(labelElement: HTMLElement) { return labelElement === this.getSelectedLabelElement(); } getContentList(): controls.Control[] { const list: controls.Control[] = []; for (let i = 0; i < this._titleBarElement.children.length; i++) { const label = this._titleBarElement.children.item(i) as HTMLElement; const content = TabPane.getContentFromLabel(label); list.push(content); } return list; } private getSelectedLabelElement(): HTMLElement { for (let i = 0; i < this._titleBarElement.childElementCount; i++) { const label = this._titleBarElement.children.item(i) as HTMLLabelElement; if (label.classList.contains("selected")) { return label; } } return undefined; } } }
the_stack
import * as Toolkit from 'chipmunk.client.toolkit'; import { Session, IStreamState } from '../../../controller/session/session'; import { ChartRequest } from '../../../controller/session/dependencies/search/dependencies/charts/controller.session.tab.search.charts.request'; import { FilterRequest } from '../../../controller/session/dependencies/search/dependencies/filters/controller.session.tab.search.filters.request'; import { IMapState, IMapPoint, } from '../../../controller/session/dependencies/map/controller.session.tab.map'; import { Observable, Subscription, Subject } from 'rxjs'; import { AChart } from './charts/charts'; import { IPC } from '../../../services/service.electron.ipc'; import { scheme_color_accent } from '../../../theme/colors'; import TabsSessionsService from '../../../services/service.sessions.tabs'; import ChartsControllers from './charts/charts'; export interface IRange { begin: number; end: number; } export interface IResults { dataset: Array<{ [key: string]: any }>; max: number | undefined; min: number | undefined; } export enum EScaleType { single = 'single', common = 'common', } export interface IScaleState { yAxisIDs: string[]; max: number[]; min: number[]; type: EScaleType; colors: Array<string | undefined>; } export interface IChartsResults { dataset: Array<{ [key: string]: any }>; scale: IScaleState; } export class ServiceData { private _sessionSubscriptions: { [key: string]: Subscription } = {}; private _sessionController: Session | undefined; private _stream: IStreamState | undefined; private _charts: IPC.TChartResults = {}; private _logger: Toolkit.Logger = new Toolkit.Logger(`Charts ServiceData`); private _scale: IScaleState = { min: [], max: [], type: EScaleType.common, yAxisIDs: [], colors: [], }; private _subjects: { onData: Subject<void>; onCharts: Subject<IPC.TChartResults>; onChartsScaleType: Subject<EScaleType>; } = { onData: new Subject<void>(), onCharts: new Subject<IPC.TChartResults>(), onChartsScaleType: new Subject<EScaleType>(), }; constructor() { this._init(); } public destroy() { this._stream = undefined; } public getObservable(): { onData: Observable<void>; onCharts: Observable<IPC.TChartResults>; onChartsScaleType: Observable<EScaleType>; } { return { onData: this._subjects.onData.asObservable(), onCharts: this._subjects.onCharts.asObservable(), onChartsScaleType: this._subjects.onChartsScaleType.asObservable(), }; } public getScaleType(): EScaleType { return this._scale.type; } public getScaleState(): IScaleState { return this._scale; } public getLabes(width: number, range?: IRange): string[] { if (this._stream === undefined) { return []; } if (this._stream.count === 0) { return []; } const countInRange: number = range === undefined ? this._stream.count : range.end - range.begin; let rate: number = width / countInRange; if (isNaN(rate) || !isFinite(rate)) { return []; } if (rate > 1) { rate = 1; width = countInRange; } const offset: number = range === undefined ? 0 : range.begin; const labels: string[] = new Array(width).fill('').map((value: string, i: number) => { const left: number = Math.round(i / rate) + offset; const right: number = Math.round((i + 1) / rate) + offset; return left !== right - 1 ? '' + left + ' - ' + right : left + ''; }); return labels; } public getDatasets(width: number, range?: IRange): Promise<IResults> { return new Promise((resolve, reject) => { if (this._sessionController === undefined) { return reject(new Error(this._logger.error(`Session controller isn't defined`))); } if (this._stream === undefined) { return resolve({ dataset: [], max: undefined, min: undefined }); } if (this._stream.count === 0) { return resolve({ dataset: [], max: undefined, min: undefined }); } if (range === undefined) { range = { begin: 0, end: this._stream.count, }; } this._sessionController .getStreamMap() .getMatchesMap(width, range) .then((map) => { const dss: any = {}; const indexes: number[] = Object.keys(map).map((k) => typeof k !== 'number' ? parseInt(k, 10) : k, ); const count: number = indexes.length; let max: number = -1; indexes.forEach((key: number) => { const matches: { [key: string]: number } = map[key]; Object.keys(matches).forEach((match: string) => { if (dss[match] === undefined) { dss[match] = new Array(Math.round(count)).fill(0); } dss[match][key] = matches[match]; if (matches[match] > max) { max = matches[match]; } }); }); const datasets: any[] = []; Object.keys(dss).forEach((filter: string) => { const smth: FilterRequest | ChartRequest | undefined = this._getFilterOrChart(filter); let color: string = scheme_color_accent; if (smth !== undefined) { color = smth instanceof FilterRequest ? smth.getBackground() : smth.getColor(); } const dataset = { barPercentage: 1, categoryPercentage: 1, label: filter, backgroundColor: color, showLine: false, data: dss[filter], }; datasets.push(dataset); }); resolve({ dataset: datasets, max: max, min: undefined }); }) .catch((err: Error) => { reject( new Error( this._logger.warn(`Fail to get dataset due error: ${err.message}`), ), ); }); }); } public getChartsDatasets( width: number, range?: IRange, preview: boolean = false, ): IChartsResults { if (this._stream === undefined || this._charts === undefined) { return { dataset: [], scale: { max: [], min: [], yAxisIDs: [], type: this._scale.type, colors: [], }, }; } if (this._stream.count === 0 || Object.keys(this._charts).length === 0) { return { dataset: [], scale: { max: [], min: [], yAxisIDs: [], type: this._scale.type, colors: [], }, }; } const datasets: any[] = []; const max: number[] = []; const min: number[] = []; const colors: Array<string | undefined> = []; const yAxisID: string[] = []; if (range === undefined) { range = { begin: 0, end: this._stream.count, }; } Object.keys(this._charts).forEach((filter: string) => { const chart: ChartRequest | undefined = this._getChartBySource(filter); if (chart === undefined) { this._logger.error(`[datasets] Fail to find a chart with source "${filter}"`); return; } const matches: IPC.IChartMatch[] = this._charts[filter]; const controller: AChart | undefined = ChartsControllers[chart.getType()]; if (controller === undefined) { this._logger.error(`Fail get controller for chart "${chart.getType()}"`); return; } const ds = controller.getDataset( filter, matches, { getColor: (source: string) => { const _chart: ChartRequest | undefined = this._getChartBySource(source); return _chart === undefined ? undefined : chart.getColor(); }, getOptions: (source: string) => { const _chart: ChartRequest | undefined = this._getChartBySource(source); return _chart === undefined ? undefined : chart.getOptions(); }, getLeftPoint: this._getLeftBorderChartDS.bind(this), getRightPoint: this._getRightBorderChartDS.bind(this), }, width, range as IRange, preview, ); datasets.push(ds.dataset); max.push(ds.max); min.push(ds.min); colors.push( (() => { const _chart: ChartRequest | undefined = this._getChartBySource(filter); return _chart === undefined ? undefined : chart.getColor(); })(), ); yAxisID.push(ds.dataset.yAxisID); }); this._scale = { min: min, max: max, yAxisIDs: yAxisID, type: this._scale.type, colors: colors, }; return { dataset: datasets, scale: { max: max, min: min, yAxisIDs: yAxisID, type: this._scale.type, colors: colors, }, }; } public getStreamSize(): number | undefined { if (this._stream === undefined) { return undefined; } return this._stream.count; } public hasData(): boolean { if (this._sessionController === undefined) { this._logger.error(`Session controller isn't defined`); return false; } if (this._stream === undefined || this._stream.count === 0) { return false; } if (this._sessionController.getSessionSearch().getOutputStream().getRowsCount() > 0) { return true; } if (this._charts === undefined) { return false; } if (this._charts !== undefined && Object.keys(this._charts).length === 0) { return false; } return true; } public getSessionGuid(): string | undefined { if (this._sessionController === undefined) { return; } return this._sessionController.getGuid(); } public setChartsScaleType(sType: EScaleType) { if (this._scale.type === sType) { return; } this._scale.type = sType; this._subjects.onChartsScaleType.next(sType); } private _getChartBySource(source: string): ChartRequest | undefined { if (this._sessionController === undefined) { return undefined; } return this._sessionController .getSessionSearch() .getChartsAPI() .getStorage() .getBySource(source); } private _getFilterBySource(source: string): FilterRequest | undefined { if (this._sessionController === undefined) { return undefined; } return this._sessionController .getSessionSearch() .getFiltersAPI() .getStorage() .getBySource(source); } private _getFilterOrChart(source: string): FilterRequest | ChartRequest | undefined { const chart: ChartRequest | undefined = this._getChartBySource(source); return chart === undefined ? this._getFilterBySource(source) : chart; } private _init(controller?: Session) { controller = controller === undefined ? TabsSessionsService.getActive() : controller; if (controller === undefined) { return; } // Store controller this._sessionController = controller; // Unbound from events of prev session Object.keys(this._sessionSubscriptions).forEach((key: string) => { this._sessionSubscriptions[key].unsubscribe(); }); // Subscribe this._sessionSubscriptions.onSearchMapStateUpdate = controller .getStreamMap() .getObservable() .onStateUpdate.subscribe(this._onSearchMapStateUpdate.bind(this)); this._sessionSubscriptions.onStreamStateUpdated = controller .getStreamOutput() .getObservable() .onStateUpdated.subscribe(this._onStreamStateUpdated.bind(this)); this._sessionSubscriptions.onRequestsUpdated = controller .getSessionSearch() .getFiltersAPI() .getObservable() .updated.subscribe(this._onRequestsUpdated.bind(this)); this._sessionSubscriptions.onSearchStateUpdated = controller .getSessionSearch() .getOutputStream() .getObservable() .onStateUpdated.subscribe(this._onSearchStateUpdated.bind(this)); this._sessionSubscriptions.onRequestsUpdated = controller .getSessionSearch() .getFiltersAPI() .getStorage() .getObservable() .changed.subscribe(this._onRequestsUpdated.bind(this)); this._sessionSubscriptions.onChartsResultsUpdated = controller .getSessionSearch() .getChartsAPI() .getObservable() .onChartsResultsUpdated.subscribe(this._onChartsResultsUpdated.bind(this)); this._sessionSubscriptions.onChartsUpdated = controller .getSessionSearch() .getChartsAPI() .getObservable() .onChartsUpdated.subscribe(this._onChartsUpdated.bind(this)); // Get default data this._stream = controller.getStreamOutput().getState(); this._charts = controller.getSessionSearch().getChartsAPI().getChartsData(); this._subjects.onData.next(); this._subjects.onCharts.next({}); } private _onSearchMapStateUpdate(state: IMapState) { this._subjects.onData.next(); } private _onSearchStateUpdated() { this._subjects.onData.next(); } private _onStreamStateUpdated(state: IStreamState) { this._stream = state; this._subjects.onData.next(); } private _onRequestsUpdated() { // Some things like colors was changed. Trigger an update this._subjects.onData.next(); } private _onChartsResultsUpdated(charts: IPC.TChartResults) { this._charts = charts; this._subjects.onCharts.next({}); } private _onChartsUpdated(charts: ChartRequest[]) { // Some things like colors was changed. Trigger an update this._subjects.onCharts.next({}); } private _getLeftBorderChartDS(reg: string, begin: number): number | undefined { const matches: IPC.IChartMatch[] | undefined = this._charts[reg]; if (matches === undefined) { return undefined; } try { let prev: IPC.IChartMatch | undefined; matches.forEach((match: IPC.IChartMatch) => { if (match.row === begin) { throw match; } if (match.row > begin) { if (prev === undefined) { throw match; } else { throw prev; } } prev = match; }); if (matches[0].value === undefined) { return undefined; } else { return this._getValidNumberValue(matches[0].value[0]); } } catch (target: any) { if (typeof target === 'object' && target !== null && target.row && target.value) { const value: number = parseInt(target.value[0], 10); if (isNaN(value) || !isFinite(value)) { return; } return this._getValidNumberValue(target.value[0]); } } return undefined; } private _getRightBorderChartDS( reg: string, end: number, previous: boolean, ): number | undefined { const matches: IPC.IChartMatch[] | undefined = this._charts[reg]; if (matches === undefined || matches.length === 0) { return undefined; } try { let prev: IPC.IChartMatch | undefined; matches.forEach((match: IPC.IChartMatch) => { if (match.row === end) { throw match; } if (match.row > end) { if (!previous) { throw match; } if (prev === undefined) { throw match; } else { throw prev; } } prev = match; }); if (matches[matches.length - 1].value === undefined) { return undefined; } else { return this._getValidNumberValue((matches[matches.length - 1].value as any)[0]); } } catch (target: any) { if (typeof target === 'object' && target !== null && target.row && target.value) { return this._getValidNumberValue(target.value[0]); } } return undefined; } private _getValidNumberValue(val: string): number | undefined { const value: number = parseFloat(val); if (isNaN(value) || !isFinite(value)) { return undefined; } return value; } }
the_stack
import bowser from 'bowser'; import { AppUserConfigNotifyButton, BellSize, BellPosition, BellText } from "../models/Prompts"; import { NotificationPermission } from "../models/NotificationPermission"; import OneSignalEvent from '../Event'; import MainHelper from '../helpers/MainHelper'; import { ResourceLoadState } from '../services/DynamicResourceLoader'; import { addCssClass, addDomElement, contains, decodeHtmlEntities, delay, nothing, once, removeDomElement, isUsingSubscriptionWorkaround } from '../utils'; import Badge from './Badge'; import Button from './Button'; import Dialog from './Dialog'; import Launcher from './Launcher'; import Message from './Message'; import Log from '../libraries/Log'; import OneSignal from "../OneSignal"; import { DismissHelper } from '../helpers/DismissHelper'; import { DismissPrompt } from '../models/Dismiss'; var logoSvg = `<svg class="onesignal-bell-svg" xmlns="http://www.w3.org/2000/svg" width="99.7" height="99.7" viewBox="0 0 99.7 99.7"><circle class="background" cx="49.9" cy="49.9" r="49.9"/><path class="foreground" d="M50.1 66.2H27.7s-2-.2-2-2.1c0-1.9 1.7-2 1.7-2s6.7-3.2 6.7-5.5S33 52.7 33 43.3s6-16.6 13.2-16.6c0 0 1-2.4 3.9-2.4 2.8 0 3.8 2.4 3.8 2.4 7.2 0 13.2 7.2 13.2 16.6s-1 11-1 13.3c0 2.3 6.7 5.5 6.7 5.5s1.7.1 1.7 2c0 1.8-2.1 2.1-2.1 2.1H50.1zm-7.2 2.3h14.5s-1 6.3-7.2 6.3-7.3-6.3-7.3-6.3z"/><ellipse class="stroke" cx="49.9" cy="49.9" rx="37.4" ry="36.9"/></svg>`; type BellState = 'uninitialized' | 'subscribed' | 'unsubscribed' | 'blocked'; export default class Bell { public options: AppUserConfigNotifyButton; public state: BellState = Bell.STATES.UNINITIALIZED; public _ignoreSubscriptionState: boolean = false; public hovering: boolean = false; public initialized: boolean = false; public _launcher: Launcher | undefined; public _button: any; public _badge: any; public _message: any; public _dialog: any; private DEFAULT_SIZE: BellSize = "medium"; private DEFAULT_POSITION: BellPosition = "bottom-right"; private DEFAULT_THEME: string = "default"; static get EVENTS() { return { STATE_CHANGED: 'notifyButtonStateChange', LAUNCHER_CLICK: 'notifyButtonLauncherClick', BELL_CLICK: 'notifyButtonButtonClick', SUBSCRIBE_CLICK: 'notifyButtonSubscribeClick', UNSUBSCRIBE_CLICK: 'notifyButtonUnsubscribeClick', HOVERING: 'notifyButtonHovering', HOVERED: 'notifyButtonHover' }; } static get STATES() { return { UNINITIALIZED: 'uninitialized' as BellState, SUBSCRIBED: 'subscribed' as BellState, UNSUBSCRIBED: 'unsubscribed' as BellState, BLOCKED: 'blocked' as BellState, }; } static get TEXT_SUBS() { return { 'prompt.native.grant': { default: 'Allow', chrome: 'Allow', firefox: 'Always Receive Notifications', safari: 'Allow' } }; } constructor(config: Partial<AppUserConfigNotifyButton>, launcher?: Launcher) { this.options = { enable: config.enable || false, size: config.size || this.DEFAULT_SIZE, position: config.position || this.DEFAULT_POSITION, theme: config.theme || this.DEFAULT_THEME, showLauncherAfter: config.showLauncherAfter || 10, showBadgeAfter: config.showBadgeAfter || 300, text: this.setDefaultTextOptions(config.text || {}), prenotify: config.prenotify, showCredit: config.showCredit, colors: config.colors, offset: config.offset, }; if (launcher) { this._launcher = launcher; } if (!this.options.enable) return; this.validateOptions(this.options); this.state = Bell.STATES.UNINITIALIZED; this._ignoreSubscriptionState = false; this.installEventHooks(); this.updateState(); } showDialogProcedure() { if (!this.dialog.shown) { this.dialog.show() .then(() => { once(document, 'click', (e: Event, destroyEventListener: Function) => { const wasDialogClicked = this.dialog.element.contains(e.target); if (wasDialogClicked) { } else { destroyEventListener(); if (this.dialog.shown) { this.dialog.hide() .then(() => { this.launcher.inactivateIfWasInactive(); }); } } }, true); }); } } private validateOptions(options: AppUserConfigNotifyButton) { if (!options.size || !contains(['small', 'medium', 'large'], options.size)) throw new Error(`Invalid size ${options.size} for notify button. Choose among 'small', 'medium', or 'large'.`); if (!options.position || !contains(['bottom-left', 'bottom-right'], options.position)) throw new Error(`Invalid position ${options.position} for notify button. Choose either 'bottom-left', or 'bottom-right'.`); if (!options.theme || !contains(['default', 'inverse'], options.theme)) throw new Error(`Invalid theme ${options.theme} for notify button. Choose either 'default', or 'inverse'.`); if (!options.showLauncherAfter || options.showLauncherAfter < 0) throw new Error(`Invalid delay duration of ${this.options.showLauncherAfter} for showing the notify button. Choose a value above 0.`); if (!options.showBadgeAfter || options.showBadgeAfter < 0) throw new Error(`Invalid delay duration of ${this.options.showBadgeAfter} for showing the notify button's badge. Choose a value above 0.`); } private setDefaultTextOptions(text: Partial<BellText>): BellText { const finalText: BellText = { 'tip.state.unsubscribed': text['tip.state.unsubscribed'] || 'Subscribe to notifications', 'tip.state.subscribed': text['tip.state.subscribed'] || "You're subscribed to notifications", 'tip.state.blocked': text['tip.state.blocked'] || "You've blocked notifications", 'message.prenotify': text['message.prenotify'] || "Click to subscribe to notifications", 'message.action.subscribed': text['message.action.subscribed'] || "Thanks for subscribing!", 'message.action.resubscribed': text['message.action.resubscribed'] || "You're subscribed to notifications", 'message.action.subscribing': text['message.action.subscribing'] || "Click <strong>{{prompt.native.grant}}</strong> to receive notifications", 'message.action.unsubscribed': text['message.action.unsubscribed'] || "You won't receive notifications again", 'dialog.main.title': text['dialog.main.title'] || 'Manage Site Notifications', 'dialog.main.button.subscribe': text['dialog.main.button.subscribe'] || 'SUBSCRIBE', 'dialog.main.button.unsubscribe': text['dialog.main.button.unsubscribe'] || 'UNSUBSCRIBE', 'dialog.blocked.title': text['dialog.blocked.title'] || 'Unblock Notifications', 'dialog.blocked.message': text['dialog.blocked.message'] || 'Follow these instructions to allow notifications:', }; return finalText; } private installEventHooks() { // Install event hooks OneSignal.emitter.on(Bell.EVENTS.SUBSCRIBE_CLICK, () => { this.dialog.subscribeButton.disabled = true; this._ignoreSubscriptionState = true; OneSignal.setSubscription(true) .then(() => { this.dialog.subscribeButton.disabled = false; return this.dialog.hide(); }) .then(() => { return this.message.display( Message.TYPES.MESSAGE, this.options.text['message.action.resubscribed'], Message.TIMEOUT); }) .then(() => { this._ignoreSubscriptionState = false; this.launcher.clearIfWasInactive(); return this.launcher.inactivate(); }) .then(() => { return this.updateState(); }); }); OneSignal.emitter.on(Bell.EVENTS.UNSUBSCRIBE_CLICK, () => { this.dialog.unsubscribeButton.disabled = true; OneSignal.setSubscription(false) .then(() => { this.dialog.unsubscribeButton.disabled = false; return this.dialog.hide(); }) .then(() => { this.launcher.clearIfWasInactive(); return this.launcher.activate(); }) .then(() => { return this.message.display( Message.TYPES.MESSAGE, this.options.text['message.action.unsubscribed'], Message.TIMEOUT); }) .then(() => { return this.updateState(); }); }); OneSignal.emitter.on(Bell.EVENTS.HOVERING, () => { this.hovering = true; this.launcher.activateIfInactive(); // If there's already a message being force shown, do not override if (this.message.shown || this.dialog.shown) { this.hovering = false; return; } // If the message is a message and not a tip, don't show it (only show tips) // Messages will go away on their own if (this.message.contentType === Message.TYPES.MESSAGE) { this.hovering = false; return; } new Promise<void>(resolve => { // If a message is being shown if (this.message.queued.length > 0) { return this.message.dequeue().then((msg: any) => { this.message.content = msg; this.message.contentType = Message.TYPES.QUEUED; resolve(); }); } else { this.message.content = decodeHtmlEntities(this.message.getTipForState()); this.message.contentType = Message.TYPES.TIP; resolve(); } }).then(() => { return this.message.show(); }) .then(() => { this.hovering = false; }); }); OneSignal.emitter.on(Bell.EVENTS.HOVERED, () => { // If a message is displayed (and not a tip), don't control it. Visitors have no control over messages if (this.message.contentType === Message.TYPES.MESSAGE) { return; } if (!this.dialog.hidden) { // If the dialog is being brought up when clicking button, don't shrink return; } if (this.hovering) { this.hovering = false; // Hovering still being true here happens on mobile where the message could still be showing (i.e. animating) when a HOVERED event fires // In other words, you tap on mobile, HOVERING fires, and then HOVERED fires immediately after because of the way mobile click events work // Basically only happens if HOVERING and HOVERED fire within a few milliseconds of each other this.message.waitUntilShown() .then(() => delay(Message.TIMEOUT)) .then(() => this.message.hide()) .then(() => { if (this.launcher.wasInactive && this.dialog.hidden) { this.launcher.inactivate(); this.launcher.wasInactive = false; } }); } if (this.message.shown) { this.message.hide() .then(() => { if (this.launcher.wasInactive && this.dialog.hidden) { this.launcher.inactivate(); this.launcher.wasInactive = false; } }); } }); OneSignal.emitter.on(OneSignal.EVENTS.SUBSCRIPTION_CHANGED, async isSubscribed => { if (isSubscribed == true) { if (this.badge.shown && this.options.prenotify) { this.badge.hide(); } if (this.dialog.notificationIcons === null) { const icons = await MainHelper.getNotificationIcons(); this.dialog.notificationIcons = icons; } } OneSignal.getNotificationPermission((permission: NotificationPermission) => { let bellState: BellState; if (isSubscribed) { bellState = Bell.STATES.SUBSCRIBED; } else if (permission === NotificationPermission.Denied) { bellState = Bell.STATES.BLOCKED; } else { bellState = Bell.STATES.UNSUBSCRIBED; } this.setState(bellState, this._ignoreSubscriptionState); }); }); OneSignal.emitter.on(Bell.EVENTS.STATE_CHANGED,state => { if (!this.launcher.element) { // Notify button doesn't exist return; } if (state.to === Bell.STATES.SUBSCRIBED) { this.launcher.inactivate(); } else if (state.to === Bell.STATES.UNSUBSCRIBED || Bell.STATES.BLOCKED) { this.launcher.activate(); } }); OneSignal.emitter.on(OneSignal.EVENTS.NATIVE_PROMPT_PERMISSIONCHANGED, () => { this.updateState(); }); } private addDefaultClasses() { // Add default classes const container = this.container; if (this.options.position === 'bottom-left') { if (container) { addCssClass(container, 'onesignal-bell-container-bottom-left'); } addCssClass(this.launcher.selector, 'onesignal-bell-launcher-bottom-left'); } else if (this.options.position === 'bottom-right') { if (container) { addCssClass(container, 'onesignal-bell-container-bottom-right'); } addCssClass(this.launcher.selector, 'onesignal-bell-launcher-bottom-right'); } else { throw new Error('Invalid OneSignal notify button position ' + this.options.position); } if (this.options.theme === 'default') { addCssClass(this.launcher.selector, 'onesignal-bell-launcher-theme-default'); } else if (this.options.theme === 'inverse') { addCssClass(this.launcher.selector, 'onesignal-bell-launcher-theme-inverse'); } else { throw new Error('Invalid OneSignal notify button theme ' + this.options.theme); } } async create() { if (!this.options.enable) return; const sdkStylesLoadResult = await OneSignal.context.dynamicResourceLoader.loadSdkStylesheet(); if (sdkStylesLoadResult !== ResourceLoadState.Loaded) { Log.debug('Not showing notify button because styles failed to load.'); return; } // Remove any existing bell if (this.container) { removeDomElement('#onesignal-bell-container'); } // Insert the bell container addDomElement('body', 'beforeend', '<div id="onesignal-bell-container" class="onesignal-bell-container onesignal-reset"></div>'); if (this.container) { // Insert the bell launcher addDomElement(this.container, 'beforeend', '<div id="onesignal-bell-launcher" class="onesignal-bell-launcher"></div>'); } // Insert the bell launcher button addDomElement(this.launcher.selector, 'beforeend', '<div class="onesignal-bell-launcher-button"></div>'); // Insert the bell launcher badge addDomElement(this.launcher.selector, 'beforeend', '<div class="onesignal-bell-launcher-badge"></div>'); // Insert the bell launcher message addDomElement(this.launcher.selector, 'beforeend', '<div class="onesignal-bell-launcher-message"></div>'); addDomElement(this.message.selector, 'beforeend', '<div class="onesignal-bell-launcher-message-body"></div>'); // Insert the bell launcher dialog addDomElement(this.launcher.selector, 'beforeend', '<div class="onesignal-bell-launcher-dialog"></div>'); addDomElement(this.dialog.selector, 'beforeend', '<div class="onesignal-bell-launcher-dialog-body"></div>'); // Install events // Add visual elements addDomElement(this.button.selector, 'beforeend', logoSvg); const isPushEnabled = await OneSignal.isPushNotificationsEnabled(); const notOptedOut = await OneSignal.getSubscription(); const doNotPrompt = DismissHelper.wasPromptOfTypeDismissed(DismissPrompt.Push); // Resize to small instead of specified size if enabled, otherwise there's a jerking motion where the bell, at a different size than small, jerks sideways to go from large -> small or medium -> small const resizeTo = (isPushEnabled ? 'small' : (this.options.size || this.DEFAULT_SIZE)); await this.launcher.resize(resizeTo); this.addDefaultClasses(); this.applyOffsetIfSpecified(); this.setCustomColorsIfSpecified(); this.patchSafariSvgFilterBug(); Log.info('Showing the notify button.'); await (isPushEnabled ? this.launcher.inactivate() : nothing()) .then(() => OneSignal.getSubscription()) .then((isNotOptedOut: boolean) => { if ((isPushEnabled || !isNotOptedOut) && this.dialog.notificationIcons === null) { return MainHelper.getNotificationIcons().then(icons => { this.dialog.notificationIcons = icons; }); } else return nothing(); }) .then(() => delay(this.options.showLauncherAfter || 0)) .then(() => { if (isUsingSubscriptionWorkaround() && notOptedOut && doNotPrompt !== true && !isPushEnabled && (OneSignal.config.userConfig.promptOptions.autoPrompt === true) && !MainHelper.isHttpPromptAlreadyShown() ) { Log.debug('Not showing notify button because slidedown will be shown.'); return nothing(); } else { return this.launcher.show(); } }) .then(() => { return delay(this.options.showBadgeAfter || 0); }) .then(() => { if (this.options.prenotify && !isPushEnabled && OneSignal._isNewVisitor) { return this.message.enqueue(this.options.text['message.prenotify']) .then(() => this.badge.show()); } else return nothing(); }) .then(() => this.initialized = true); } patchSafariSvgFilterBug() { if (!(bowser.safari && Number(bowser.version) >= 9.1)) { const bellShadow = `drop-shadow(0 2px 4px rgba(34,36,38,0.35));`; const badgeShadow = `drop-shadow(0 2px 4px rgba(34,36,38,0));`; const dialogShadow = `drop-shadow(0px 2px 2px rgba(34,36,38,.15));`; this.graphic.setAttribute('style', `filter: ${bellShadow}; -webkit-filter: ${bellShadow};`); this.badge.element.setAttribute('style', `filter: ${badgeShadow}; -webkit-filter: ${badgeShadow};`); this.dialog.element.setAttribute('style', `filter: ${dialogShadow}; -webkit-filter: ${dialogShadow};`); } if (bowser.safari) { this.badge.element.setAttribute('style', `display: none;`); } } applyOffsetIfSpecified() { const offset = this.options.offset; if (offset) { const element = this.launcher.element as HTMLElement; if (!element) { Log.error("Could not find bell dom element"); return; } // Reset styles first element.style.cssText = ''; if (offset.bottom) { element.style.cssText += `bottom: ${offset.bottom};`; } if (this.options.position === 'bottom-right') { if (offset.right) { element.style.cssText += `right: ${offset.right};`; } } else if (this.options.position === 'bottom-left') { if (offset.left) { element.style.cssText += `left: ${offset.left};`; } } } } setCustomColorsIfSpecified() { // Some common vars first const dialogButton = this.dialog.element.querySelector('button.action'); const pulseRing = this.button.element.querySelector('.pulse-ring'); // Reset added styles first this.graphic.querySelector('.background').style.cssText = ''; const foregroundElements = this.graphic.querySelectorAll('.foreground'); for (let i = 0; i < foregroundElements.length; i++) { const element = foregroundElements[i]; element.style.cssText = ''; } this.graphic.querySelector('.stroke').style.cssText = ''; this.badge.element.style.cssText = ''; if (dialogButton) { dialogButton.style.cssText = ''; dialogButton.style.cssText = ''; } if (pulseRing) { pulseRing.style.cssText = ''; } // Set new styles if (this.options.colors) { const colors = this.options.colors; if (colors['circle.background']) { this.graphic.querySelector('.background').style.cssText += `fill: ${colors['circle.background']}`; } if (colors['circle.foreground']) { const foregroundElements = this.graphic.querySelectorAll('.foreground'); for (let i = 0; i < foregroundElements.length; i++) { const element = foregroundElements[i]; element.style.cssText += `fill: ${colors['circle.foreground']}`; } this.graphic.querySelector('.stroke').style.cssText += `stroke: ${colors['circle.foreground']}`; } if (colors['badge.background']) { this.badge.element.style.cssText += `background: ${colors['badge.background']}`; } if (colors['badge.bordercolor']) { this.badge.element.style.cssText += `border-color: ${colors['badge.bordercolor']}`; } if (colors['badge.foreground']) { this.badge.element.style.cssText += `color: ${colors['badge.foreground']}`; } if (dialogButton) { if (colors['dialog.button.background']) { this.dialog.element.querySelector('button.action').style.cssText += `background: ${colors['dialog.button.background']}`; } if (colors['dialog.button.foreground']) { this.dialog.element.querySelector('button.action').style.cssText += `color: ${colors['dialog.button.foreground']}`; } if (colors['dialog.button.background.hovering']) { this.addCssToHead('onesignal-background-hover-style', `#onesignal-bell-container.onesignal-reset .onesignal-bell-launcher .onesignal-bell-launcher-dialog button.action:hover { background: ${colors['dialog.button.background.hovering']} !important; }`); } if (colors['dialog.button.background.active']) { this.addCssToHead('onesignal-background-active-style', `#onesignal-bell-container.onesignal-reset .onesignal-bell-launcher .onesignal-bell-launcher-dialog button.action:active { background: ${colors['dialog.button.background.active']} !important; }`); } } if (pulseRing) { if (colors['pulse.color']) { this.button.element.querySelector('.pulse-ring').style.cssText = `border-color: ${colors['pulse.color']}`; } } } } addCssToHead(id: string, css: string) { const existingStyleDom = document.getElementById(id); if (existingStyleDom) return; const styleDom = document.createElement('style'); styleDom.id = id; styleDom.type = 'text/css'; styleDom.appendChild(document.createTextNode(css)); document.head.appendChild(styleDom); } /** * Updates the current state to the correct new current state. Returns a promise. */ updateState() { Promise.all([ OneSignal.privateIsPushNotificationsEnabled(), OneSignal.privateGetNotificationPermission() ]) .then(([isEnabled, permission]) => { this.setState(isEnabled ? Bell.STATES.SUBSCRIBED : Bell.STATES.UNSUBSCRIBED); if (permission === NotificationPermission.Denied) { this.setState(Bell.STATES.BLOCKED); } }); } /** * Updates the current state to the specified new state. * @param newState One of ['subscribed', 'unsubscribed']. */ setState(newState: BellState, silent = false) { const lastState = this.state; this.state = newState; if (lastState !== newState && !silent) { OneSignalEvent.trigger(Bell.EVENTS.STATE_CHANGED, { from: lastState, to: newState }); // Update anything that should be changed here in the new state } // Update anything that should be reset to the same state } get container() { return document.querySelector('#onesignal-bell-container'); } get graphic() { return this.button.element.querySelector('svg'); } get launcher() { if (!this._launcher) this._launcher = new Launcher(this); return this._launcher; } get button() { if (!this._button) this._button = new Button(this); return this._button; } get badge() { if (!this._badge) this._badge = new Badge(); return this._badge; } get message() { if (!this._message) this._message = new Message(this); return this._message; } get dialog() { if (!this._dialog) this._dialog = new Dialog(this); return this._dialog; } get subscribed() { return this.state === Bell.STATES.SUBSCRIBED; } get unsubscribed() { return this.state === Bell.STATES.UNSUBSCRIBED; } get blocked() { return this.state === Bell.STATES.BLOCKED; } }
the_stack
import React = require("react"); import ReactDOM = require("react-dom"); import * as csx from '../base/csx'; import {BaseComponent} from "../ui"; import * as ui from "../ui"; import Modal = require('react-modal'); import * as styles from "../styles/styles"; import {debounce,createMap,rangeLimited,getFileName} from "../../common/utils"; import {cast, server, Types} from "../../socket/socketClient"; import * as commands from "../commands/commands"; import {match, filter as fuzzyFilter} from "fuzzaldrin"; import {Icon} from "../components/icon"; import {TypedEvent} from "../../common/events"; import * as state from "../state/state"; import * as types from "../../common/types"; import {AvailableProjectConfig} from "../../common/types"; import {Robocop} from "../components/robocop"; import * as utils from "../../common/utils"; import {tabState} from "../tabs/v2/appTabsContainer"; import * as typestyle from "typestyle"; const inputClassName = typestyle.style(styles.modal.inputStyleBase); /** Stuff shared by the select list view */ import {renderMatchedSegments, getFilteredItems} from ".././selectListView"; export interface Props { } export interface State { } enum SearchMode { /** * Use if the user does something like `👎>` i.e. invalid mode key * This is also used to search for a mode */ Unknown, File, Command, Project, Symbol, FilesInProject, } let selectedStyle = { background: '#545454', color: 'white' }; let listItemStyle = { fontFamily: 'monospace', boxSizing: 'content-box' /** Otherwise the items don't expand to encapsulate children */ }; let searchingNameStyle = { marginTop: '0px', marginBottom: '0px', marginLeft: '10px', border: '1px solid grey', padding: '4px 4px', background: 'black' }; export class OmniSearch extends BaseComponent<Props, State>{ mode: SearchMode = SearchMode.File; searchState = new SearchState(); constructor(props: Props) { super(props); this.searchState.stateChanged.on(() => this.forceUpdate()); this.searchState.setParentUiRawFilterValue = (value) => { this.setRawFilterValue(value); }; this.state = this.propsToState(props); } propsToState(props: Props): State { return { }; } componentWillReceiveProps(props: Props) { this.setState(this.propsToState(props)); } refs: { [string: string]: any; omniSearch: any; omniSearchInput: any; searchScroll: Element; selected: Element; } componentDidMount() { commands.omniFindFile.on(() => { this.searchState.openOmniSearch(SearchMode.File); }); commands.omniFindCommand.on(() => { this.searchState.openOmniSearch(SearchMode.Command); }); commands.omniSelectProject.on(() => { this.searchState.openOmniSearch(SearchMode.Project); }); commands.omniProjectSymbols.on(() => { this.searchState.openOmniSearch(SearchMode.Symbol); }); commands.omniProjectSourcefile.on(() => { this.searchState.openOmniSearch(SearchMode.FilesInProject); }); } wasShown = false; componentWillUpdate(){ this.wasShown = this.searchState.isShown; } componentDidUpdate() { // get the dom node that is selected // make sure its parent scrolls to make this visible setTimeout(()=>{ if (this.refs.selected) { let selected = this.refs.selected as HTMLDivElement; selected.scrollIntoViewIfNeeded(false); } // also keep the input in focus if (this.searchState.isShown) { let input = this.refs.omniSearchInput as HTMLInputElement input.focus(); // and scroll to the end if its just been shown if (!this.wasShown){ let len = input.value.length; input.setSelectionRange(len, len); this.wasShown = true; } } }); } render() { let renderedResults: JSX.Element[] = this.searchState.renderResults(); let searchingName = this.searchState.getSearchingName(); return <Modal isOpen={this.searchState.isShown} onRequestClose={this.searchState.closeOmniSearch}> <div style={csx.extend(csx.vertical, csx.flex)}> <div style={csx.extend(csx.content, csx.horizontal,csx.center)}> <h4 style={{marginTop:'1rem', marginBottom: '1rem'}}>Omni Search <Icon name="search"/></h4> {searchingName ? <h5 style={searchingNameStyle}>{searchingName}</h5> : ''} <div style={csx.flex}></div> <div style={{fontSize:'0.9rem', color:'grey'}}><code style={styles.modal.keyStrokeStyle}>Esc</code> to exit <code style={styles.modal.keyStrokeStyle}>Enter</code> to select</div> </div> <div style={csx.extend(csx.content, styles.padded1TopBottom,csx.vertical)}> <input defaultValue={this.searchState.rawFilterValue} className={inputClassName} type="text" ref="omniSearchInput" placeholder="Filter" onChange={this.onChangeFilter} onKeyDown={this.onChangeSelected} /> </div> {this.searchState.optionalMessage()} <div ref="searchScroll" className="scrollContainer" style={csx.extend(csx.vertical,csx.flex,{overflow:'auto'})}> {renderedResults} </div> </div> </Modal> } setRawFilterValue = (value:string) => { // also scroll to the end of the input after loading let input = (ReactDOM.findDOMNode(this.refs.omniSearchInput) as HTMLInputElement) if (!input) return; input.value = value; let len = value.length; input.setSelectionRange(len, len) }; onChangeFilter = debounce((e)=>{ let filterValue = (ReactDOM.findDOMNode(this.refs.omniSearchInput) as HTMLInputElement).value; this.searchState.newValue(filterValue); },50); incrementSelected = debounce(() => { this.searchState.incrementSelected(); }, 0, true); decrementSelected = debounce(() => { this.searchState.decrementSelected(); },0,true); onChangeSelected = (event) => { let keyStates = ui.getKeyStates(event); if (keyStates.up || keyStates.tabPrevious) { event.preventDefault(); this.decrementSelected(); } if (keyStates.down || keyStates.tabNext) { event.preventDefault(); this.incrementSelected(); } if (keyStates.enter) { event.preventDefault(); this.searchState.choseIndex(this.searchState.selectedIndex); } }; } interface SearchModeDescription { mode: SearchMode; description : string; searchingName: string; shortcut: string; keyboardShortcut: string; } /** * Omni search has a lot of UI work (debouncing and whatnot) in it, * don't want to sprinkel in all the MODE selection stuff in there as well * So ... created this class * Responsible for taking user input > parsing it and then > returning the rendered search results * Also maintains the selected index within the search results and takes approriate action if user commits to it * * functions marched with "mode" contain mode specific logic */ class SearchState { /** * Current raw user input value */ rawFilterValue: string = ''; parsedFilterValue: string = ''; /** * Various search lists */ /** filepath */ filePaths: string [] = []; filePathsCompleted: boolean = false; /** project */ availableProjects: AvailableProjectConfig[] = []; /** commands */ commands = commands.commandRegistry; /** symols */ symbols: types.NavigateToItem[] = []; /** source code files */ filesPathsInProject: string[] = []; /** Modes can use this to store their results */ filteredValues:any[] = []; /** * Current mode */ mode: SearchMode = SearchMode.File; modeDescriptions: SearchModeDescription[] = []; // set in ctor modeMap: { [key: string]: SearchMode } = {}; // set in ctor /** * showing search results */ isShown: boolean = false; /** * The currently selected search result */ selectedIndex: number = 0; /** * if there are new search results the user might care about, or user selection changed or whatever */ stateChanged = new TypedEvent<{} >( ); /** If we change the raw user value */ setParentUiRawFilterValue = (rawFilterValue:string)=>null; /** for performance reasons */ maxShowCount = 20; constructor() { commands.esc.on(()=>{ this.closeOmniSearch(); }); this.filePaths = state.getState().filePaths.filter(fp=> fp.type == types.FilePathType.File).map(fp=> fp.filePath); state.subscribeSub(state=> state.filePaths, (filePaths) => { this.filePaths = filePaths.filter(fp=> fp.type == types.FilePathType.File).map(fp=> fp.filePath); this.updateIfUserIsSearching(SearchMode.File); }); this.filePathsCompleted = state.getState().filePathsCompleted; state.subscribeSub(state=> state.filePathsCompleted, (filePathsCompleted) => { this.filePathsCompleted = filePathsCompleted; this.updateIfUserIsSearching(SearchMode.File); }); server.availableProjects({}).then(res => { this.availableProjects = res; }); cast.availableProjectsUpdated.on(res => { this.availableProjects = res; }); this.modeDescriptions = [ { mode: SearchMode.File, description: 'Search for a File in the working directory', shortcut: 'f', searchingName: "Files", keyboardShortcut: commands.omniFindFile.config.keyboardShortcut }, { mode: SearchMode.Command, description: 'Search for a Command', shortcut: 'c', searchingName: "Commands", keyboardShortcut: commands.omniFindCommand.config.keyboardShortcut }, { mode: SearchMode.Project, description: 'Search for a TypeScript Project to work on', shortcut: 'p', searchingName: "Projects", keyboardShortcut: commands.omniSelectProject.config.keyboardShortcut }, { mode: SearchMode.Symbol, description: 'Search for Symbols (Hieroglyphs) in active project', shortcut: 'h', searchingName: "Symbols", keyboardShortcut: commands.omniProjectSymbols.config.keyboardShortcut }, { mode: SearchMode.FilesInProject, description: 'Search for TypeScript file in active project', shortcut: 't', searchingName: "Files In Project", keyboardShortcut: commands.omniProjectSourcefile.config.keyboardShortcut } ]; // setup mode map this.modeDescriptions.forEach(md => this.modeMap[md.shortcut] = md.mode); } /** Mode */ renderResults(): JSX.Element[] { let renderedResults: JSX.Element[] = []; if (this.mode == SearchMode.File){ let fileList: string[] = this.filteredValues; renderedResults = this.createRenderedForList(fileList,(filePath)=>{ // Create rendered let queryFilePath = utils.getFilePathLine(this.parsedFilterValue).filePath; let renderedPath = renderMatchedSegments(filePath, queryFilePath); let renderedFileName = renderMatchedSegments(getFileName(filePath), queryFilePath); return ( <div> <div>{renderedFileName}</div> {renderedPath} </div> ); }); } if (this.mode == SearchMode.FilesInProject){ let fileList: string[] = this.filteredValues; renderedResults = this.createRenderedForList(fileList,(filePath)=>{ // Create rendered let queryFilePath = utils.getFilePathLine(this.parsedFilterValue).filePath; let renderedPath = renderMatchedSegments(filePath, queryFilePath); let renderedFileName = renderMatchedSegments(getFileName(filePath), queryFilePath); return ( <div> <div>{renderedFileName}</div> {renderedPath} </div> ); }); } if (this.mode == SearchMode.Command){ let filtered: commands.UICommand[] = this.filteredValues; renderedResults = this.createRenderedForList(filtered,(command)=>{ // Create rendered let matched = renderMatchedSegments(command.config.description,this.parsedFilterValue); return ( <div style={csx.horizontal}> <span>{matched}</span> <span style={csx.flex}></span> {command.config.keyboardShortcut && <div style={commandKeyStrokeStyle}>{commandShortcutToDisplayName(command.config.keyboardShortcut)}</div>} </div> ); }); } if (this.mode == SearchMode.Project){ let filteredProjects: AvailableProjectConfig[] = this.filteredValues; renderedResults = this.createRenderedForList(filteredProjects,(project)=>{ // Create rendered let matched = renderMatchedSegments(project.name,this.parsedFilterValue); return ( <div> {matched} </div> ); }); } if (this.mode == SearchMode.Symbol){ let filtered: types.NavigateToItem[] = this.filteredValues; renderedResults = this.createRenderedForList(filtered,(symbol)=>{ // Create rendered // NOTE: Code duplicated in `gotoTypeScriptSymbol.tsx` let matched = renderMatchedSegments(symbol.name,this.parsedFilterValue); const color = ui.kindToColor(symbol.kind); const icon = ui.kindToIcon(symbol.kind); return ( <div> <div style={csx.horizontal}> <span>{matched}</span> <span style={csx.flex}></span> <strong style={{color}}>{symbol.kind}</strong> &nbsp; <span style={csx.extend({color, fontFamily:'FontAwesome'})}>{icon}</span> </div> <div>{symbol.fileName}:{symbol.position.line+1}</div> </div> ); }); } if (this.mode == SearchMode.Unknown) { let filtered: SearchModeDescription[] = this.filteredValues; renderedResults = this.createRenderedForList(filtered,(modeDescription)=>{ // Create rendered let matched = renderMatchedSegments(modeDescription.description, this.parsedFilterValue); return ( <div style={csx.extend(csx.horizontal)}> <div> {modeDescription.shortcut}{'>'} {matched} </div> <span style={csx.flex}></span> <div style={commandKeyStrokeStyle}>{commandShortcutToDisplayName(modeDescription.keyboardShortcut)}</div> </div> ); }); } return renderedResults; } /** Mode */ optionalMessage(): JSX.Element { if (this.mode == SearchMode.File && !this.filePathsCompleted){ let messageStyle = { fontSize: '.6rem', textAlign: 'center', background: '#333', color: "#ddd", padding: '5px', fontWeight: 'bold', boxShadow: 'inset 0 0 6px black', }; return ( <div style={csx.content}> <div style={messageStyle as any}>Indexing ({this.filePaths.length})</div> <Robocop/> </div> ); } return null; } /** Mode */ choseIndex = (index: number) => { if (this.mode == SearchMode.Unknown) { let modeDescription: SearchModeDescription = this.filteredValues[index]; this.rawFilterValue = modeDescription.shortcut + '>'; this.newValue(this.rawFilterValue); this.setParentUiRawFilterValue(this.rawFilterValue); return; } if (this.mode == SearchMode.File) { let filePath = this.filteredValues[index]; let {line} = utils.getFilePathLine(this.parsedFilterValue); if (filePath) { commands.doOpenFile.emit({ filePath: filePath, position: { line: line, ch: 0 } }); } this.closeOmniSearch(); return; } if (this.mode == SearchMode.Command) { let command: commands.UICommand = this.filteredValues[index]; if (command) { command.emit({}); } if (command !== commands.omniFindFile && command !== commands.omniFindCommand && command !== commands.omniSelectProject) { this.closeOmniSearch(); } return; } if (this.mode == SearchMode.Project) { let activeProject: AvailableProjectConfig = this.filteredValues[index]; if (activeProject) { server.setActiveProjectConfigDetails(activeProject); state.setActiveProject(activeProject); state.setFilePathsInActiveProject([]); } this.closeOmniSearch(); return; } if (this.mode == SearchMode.Symbol) { let symbol: types.NavigateToItem = this.filteredValues[index]; if (symbol) { commands.doOpenOrFocusFile.emit({ filePath: symbol.filePath, position: symbol.position }); } this.closeOmniSearch(); return; } if (this.mode == SearchMode.FilesInProject) { let filePath = this.filteredValues[index]; let {line} = utils.getFilePathLine(this.parsedFilterValue); if (filePath) { commands.doOpenFile.emit({ filePath: filePath, position: { line: line, ch: 0 } }); } this.closeOmniSearch(); return; } } /** Mode */ /** This is the heart of the processing .. ensuring state consistency */ newValue(value:string, wasShownBefore = true, modeChanged = false){ this.rawFilterValue = value; let oldMode = this.mode; // Parse the query to see what type it is this.parsedFilterValue = '' let trimmed = value.trim(); if (trimmed.length > 1 && trimmed[1] == '>') { let mode = this.modeMap[trimmed[0]]; if (!mode){ this.mode = SearchMode.Unknown this.parsedFilterValue = trimmed; } else { this.mode = mode; this.parsedFilterValue = trimmed.substr(2); } } else { // if not explicit fall back to modes this.mode = SearchMode.Unknown; this.parsedFilterValue = trimmed; } modeChanged = modeChanged || this.mode !== oldMode; let modeChangedOrJustOpened = modeChanged || !wasShownBefore; let potentiallyRefreshModeData = modeChangedOrJustOpened ? this.refreshModeData() : Promise.resolve({}); potentiallyRefreshModeData.then(()=>{ if (this.mode == SearchMode.Unknown) { this.filteredValues = this.parsedFilterValue ? getFilteredItems<SearchModeDescription>({ items: this.modeDescriptions, textify: (c) => c.description, filterValue: this.parsedFilterValue }) : this.modeDescriptions; } if (this.mode == SearchMode.File) { let {filePath} = utils.getFilePathLine(this.parsedFilterValue); this.filteredValues = fuzzyFilter(this.filePaths, filePath); this.filteredValues = this.filteredValues.slice(0,this.maxShowCount); } if (this.mode == SearchMode.FilesInProject) { let {filePath} = utils.getFilePathLine(this.parsedFilterValue); this.filteredValues = fuzzyFilter(this.filesPathsInProject, filePath); } if (this.mode == SearchMode.Command) { this.filteredValues = this.parsedFilterValue ? getFilteredItems<commands.UICommand>({ items: this.commands, textify: (c) => c.config.description, filterValue: this.parsedFilterValue }) : this.commands; } if (this.mode == SearchMode.Project) { // only add a virtual project if the active file path is a .ts or .js file that isn't in active project const availableProjects = this.availableProjects.slice(); let tab = tabState.getSelectedTab(); let filePath = tab && utils.getFilePathFromUrl(tab.url); if (filePath && utils.isJsOrTs(filePath) && !state.inActiveProjectUrl(tab.url)) { availableProjects.unshift({ name: "Virtual: " + utils.getFileName(filePath), isVirtual: true, tsconfigFilePath: filePath }); } this.filteredValues = this.parsedFilterValue ? getFilteredItems<AvailableProjectConfig>({ items: availableProjects, textify: (p) => p.name, filterValue: this.parsedFilterValue }) : availableProjects; } if (this.mode == SearchMode.Symbol) { this.filteredValues = this.parsedFilterValue ? getFilteredItems<types.NavigateToItem>({ items: this.symbols, textify: (p) => p.name, filterValue: this.parsedFilterValue }) : this.symbols; this.filteredValues = this.filteredValues.slice(0,this.maxShowCount); } this.selectedIndex = 0; this.stateChanged.emit({}); if (modeChangedOrJustOpened){ this.setParentUiRawFilterValue(this.rawFilterValue); } }); } /** Mode */ openOmniSearch = (mode: SearchMode) => { let wasAlreadyShown = this.isShown; this.isShown = true; let oldMode = this.mode; let oldRawFilterValue = this.rawFilterValue; this.mode = mode; let description = this.modeDescriptions.filter(x=>x.mode == mode)[0]; this.rawFilterValue = description?description.shortcut+'>':''; // If already shown would be nice to preserve current user input // And if the new mode is different // And if the new mode is not *search* search mode if (wasAlreadyShown && oldMode !== this.mode && oldMode !== SearchMode.Unknown) { this.rawFilterValue = this.rawFilterValue + oldRawFilterValue.trim().substr(2); } this.newValue(this.rawFilterValue, wasAlreadyShown, oldMode !== this.mode); } /** Mode */ refreshModeData(): Promise<any> { // If the new mode requires a search we do that here if (this.mode == SearchMode.Symbol) { return server.getNavigateToItems({}).then((res) => { this.symbols = res.items; }); } if (this.mode == SearchMode.FilesInProject) { this.filesPathsInProject = state.getState().filePathsInActiveProject; } return Promise.resolve(); } getSearchingName(): string { if (this.mode == SearchMode.Unknown){ return 'Modes'; } let description = this.modeDescriptions.filter(x=>x.mode == this.mode)[0]; if (!description) return ''; else return description.searchingName; } private createRenderedForList<T>(items: T[], itemToRender: (item: T) => JSX.Element): JSX.Element[] { return items.map((item, index) => { let rendered = itemToRender(item); let selected = this.selectedIndex === index; let style = selected ? selectedStyle : {}; let ref = selected && "selected"; return ( <div key={index} style={csx.extend(style, styles.padded2, styles.hand, listItemStyle)} onClick={() => this.choseIndex(index) } ref={ref}> {rendered} </div> ); }); } private updateIfUserIsSearching(mode:SearchMode){ if (this.mode == mode && this.isShown){ this.newValue(this.rawFilterValue); } } incrementSelected = () => { this.selectedIndex = rangeLimited({ num: this.selectedIndex + 1, min: 0, max: this.filteredValues.length - 1, loopAround: true }); this.stateChanged.emit({}); } decrementSelected = () => { this.selectedIndex = rangeLimited({ num: this.selectedIndex - 1, min: 0, max: this.filteredValues.length - 1, loopAround: true }); this.stateChanged.emit({}); } closeOmniSearch = () => { this.isShown = false; this.rawFilterValue = ''; this.stateChanged.emit({}); }; } var commandKeyStrokeStyle = { fontSize: '.7rem', color: '#DDD', background: '#111', paddingLeft: '4px', paddingRight: '4px', border: '2px solid', borderRadius: '4px', }; /** Utility function for command display */ function commandShortcutToDisplayName(shortcut: string): string { let basic = shortcut .replace(/mod/g,commands.modName) .replace(/alt/g,'Alt') .replace(/shift/g,'Shift'); let onPlus = basic.split('+'); onPlus[onPlus.length - 1] = onPlus[onPlus.length - 1].toUpperCase(); return onPlus.join(' + '); }
the_stack
/// <reference path="../utils/registerProperty.ts" /> /// <reference path="../utils/registerBindable.ts" /> namespace eui { /** * The ArrayCollection class is a wrapper class that exposes an <code>any[]</code> as a collection that can be * accessed and manipulated using the methods and properties of the <code>ICollection</code> interfaces. * ArrayCollection can notify the view to update item when data source changed. * * @event eui.CollectionEvent.COLLECTION_CHANGE Dispatched when the ArrayCollection has been updated in some way. * * @defaultProperty source * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @includeExample extension/eui/collections/ArrayCollectionExample.ts * @language en_US */ /** * ArrayCollection 类是数组的集合类数据结构包装器,可使用<code>ICollection</code>接口的方法和属性对其进行访问和处理。 * 使用这种数据结构包装普通数组,能在数据源发生改变的时候主动通知视图刷新变更数据项。 * * @event eui.CollectionEvent.COLLECTION_CHANGE 当 ArrayCollection 更新的的时候会派发此事件。 * * @defaultProperty source * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @includeExample extension/eui/collections/ArrayCollectionExample.ts * @language zh_CN */ export class ArrayCollection extends egret.EventDispatcher implements ICollection { /** * Constructor. <p/> * Creates a new ArrayCollection using the specified source array. * If no array is specified an empty array will be used. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 构造函数。<p/> * 用指定的原始数组创建一个 ArrayCollection 实例。 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public constructor(source?:any[]) { super(); if (source) { this._source = source; } else { this._source = []; } } /** * @private */ private _source:any[]; /** * The source of data in the ArrayCollection. * The ArrayCollection object does not represent any changes that you make * directly to the source array. Always use the ICollection methods to view the collection. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 数据源 * 通常情况下请不要直接调用Array的方法操作数据源,否则对应的视图无法收到数据改变的通知。通常都是通过ICollection的接口方法来查看数据。 * 若对数据源进行了修改,请手动调用refresh()方法刷新数据。 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public get source():any[] { return this._source; } public set source(value:any[]) { if (!value) value = []; this._source = value; this.dispatchCoEvent(CollectionEventKind.RESET); } /** * Applies the sort and filter to the view. * The ArrayCollection does not detect source data changes automatically, * so you must call the <code>refresh()</code> * method to update the view after changing the source data. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 在对数据源进行排序或过滤操作后可以手动调用此方法刷新所有数据,以更新视图。 * ArrayCollection 不会自动检原始数据进行了改变,所以你必须调用<code>refresh()</code>方法去更新显示。 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public refresh():void { this.dispatchCoEvent(CollectionEventKind.REFRESH); } //-------------------------------------------------------------------------- // // ICollection接口实现方法 // //-------------------------------------------------------------------------- /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public get length():number { return this._source.length; } /** * Adds the specified item to the end of the list. * Equivalent to <code>addItemAt(item, length)</code>. * @param item The item to add. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 向列表末尾添加指定项目。等效于 <code>addItemAt(item, length)</code>。 * @param item 要被添加的项。 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public addItem(item:any):void { this._source.push(item); this.dispatchCoEvent(CollectionEventKind.ADD, this._source.length - 1, -1, [item]); } /** * Adds the item at the specified index. * The index of any item greater than the index of the added item is increased by one. * If the the specified index is less than zero or greater than the length * of the list, a Error which code is 1007 is thrown. * @param item The item to place at the index. * @param index The index at which to place the item. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 在指定的索引处添加项目。 * 任何大于已添加项目的索引的项目索引都会增加 1。 * 如果指定的索引比0小或者比最大长度要大。则会抛出1007异常。 * @param item 要添加的项 * @param index 要添加的指定索引位置 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public addItemAt(item:any, index:number):void { if (index < 0 || index > this._source.length) { DEBUG && egret.$error(1007); } this._source.splice(index, 0, item); this.dispatchCoEvent(CollectionEventKind.ADD, index, -1, [item]); } /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public getItemAt(index:number):any { return this._source[index]; } /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ public getItemIndex(item:any):number { let length:number = this._source.length; for (let i:number = 0; i < length; i++) { if (this._source[i] === item) { return i; } } return -1; } /** * Notifies the view that an item has been updated. * @param item The item within the view that was updated. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 通知视图,某个项目的属性已更新。 * @param item 视图中需要被更新的项。 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public itemUpdated(item:any):void { let index:number = this.getItemIndex(item); if (index != -1) { this.dispatchCoEvent(CollectionEventKind.UPDATE, index, -1, [item]); } } /** * Removes all items from the list. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 删除列表中的所有项目。 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public removeAll():void { let items:any[] = this._source.concat(); this._source = []; this.dispatchCoEvent(CollectionEventKind.REMOVE, 0, -1, items); } /** * Removes the item at the specified index and returns it. * Any items that were after this index are now one index earlier. * @param index The index from which to remove the item. * @return The item that was removed. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 删除指定索引处的项目并返回该项目。原先位于此索引之后的所有项目的索引现在都向前移动一个位置。 * @param index 要被移除的项的索引。 * @return 被移除的项。 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public removeItemAt(index:number):any { if (index < 0 || index >= this._source.length) { DEBUG && egret.$error(1007); return; } let item:any = this._source.splice(index, 1)[0]; this.dispatchCoEvent(CollectionEventKind.REMOVE, index, -1, [item]); return item; } /** * Replaces the item at the specified index. * @param item The new item to be placed at the specified index. * @param index The index at which to place the item. * @return The item that was replaced, or <code>null</code> if none. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 替换在指定索引处的项目,并返回该项目。 * @param item 要在指定索引放置的新的项。 * @param index 要被替换的项的索引位置。 * @return 被替换的项目,如果没有该项则返回<code>null</code> 。 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public replaceItemAt(item:any, index:number):any { if (index < 0 || index >= this._source.length) { DEBUG && egret.$error(1007); return; } let oldItem:any = this._source.splice(index, 1, item)[0]; this.dispatchCoEvent(CollectionEventKind.REPLACE, index, -1, [item], [oldItem]); return oldItem; } /** * Replaces all items with a new source data, this method can not reset the scroller position of view. * @param newSource new source data. * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 用新数据源替换原始数据源,此方法与直接设置source不同,它不会导致目标视图重置滚动位置。 * @param newSource 新数据。 * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public replaceAll(newSource:any[]):void { if (!newSource) newSource = []; let newLength = newSource.length; let oldLength = this._source.length; for (let i = newLength; i < oldLength; i++) { this.removeItemAt(newLength); } for (let i = 0; i < newLength; i++) { if (i >= oldLength) this.addItemAt(newSource[i], i); else this.replaceItemAt(newSource[i], i); } this._source = newSource; } /** * @private * 抛出事件 */ private dispatchCoEvent(kind:string, location?:number, oldLocation?:number, items?:any[], oldItems?:any[]):void { CollectionEvent.dispatchCollectionEvent(this, CollectionEvent.COLLECTION_CHANGE, kind, location, oldLocation, items, oldItems); } } registerProperty(ArrayCollection,"source","Array",true); }
the_stack
import { SelectedWord } from "../models/SelectedWord"; import { SelectedWordXmlElement } from "../models/SelectedWordXmlElement"; import * as vscode from 'vscode'; import { FileData } from "../ReferenceProvider"; const DOMParser = require('xmldom').DOMParser; import fs = require('fs'); import { TextDocument, Position, Range } from "vscode"; export default class XmlHelper { static GetSelectedWordData( selectedWord: SelectedWord, position: vscode.Position, document: vscode.TextDocument) { // Load the XML file var xmlDoc = new DOMParser().parseFromString(document.getText().toLowerCase()); // Get all XML nodes var nodeList = xmlDoc.getElementsByTagName("*"); // var nsAttr = xmlDoc.getElementsByTagName(word.toLowerCase()); // var i: number; // for (i = 0; i < nsAttr.length; i++) { // if (nsAttr[i].lineNumber == position.line || nsAttr[i].lineNumber == (position.line - 1) || nsAttr[i].lineNumber == (position.line + 1)) { // break; // } // } // Try to get the XML element in the selected range for (var i = 0; i < nodeList.length; i++) { var node = nodeList[i]; // TBD: check the column as well if (node.lineNumber == (position.line + 1)) { let tempNode = node; while (tempNode) { selectedWord.Parents.push(XmlHelper.getElementData(tempNode)); if (tempNode.parentNode) tempNode = tempNode.parentNode; if (tempNode.nodeName === "#document" || tempNode.nodeName === "trustframeworkpolicy") break; } break; } } return selectedWord; } static getElementData(node) { var selectedWordXmlElement: SelectedWordXmlElement = new SelectedWordXmlElement(); // Get information regarding the element selectedWordXmlElement.ElementNodeName = node.nodeName; if (node.hasAttribute("id")) selectedWordXmlElement.ElementID = node.getAttribute("id"); // Get more element info if (selectedWordXmlElement.ElementNodeName === "claimstransformation" && node.hasAttribute("transformationmethod")) selectedWordXmlElement.ElementType = node.getAttribute("transformationmethod"); else if (selectedWordXmlElement.ElementNodeName === "technicalprofile") { var docLookupList = node.getElementsByTagName("protocol"); if (docLookupList.length == 1) { if (docLookupList[0].hasAttribute("name") && docLookupList[0].getAttribute("name") === "proprietary" && docLookupList[0].hasAttribute("handler") && docLookupList[0].getAttribute("handler").length > 60 && docLookupList[0].getAttribute("handler").indexOf(",") > 25) { // Extract the provider name selectedWordXmlElement.ElementType = docLookupList[0].getAttribute("handler").substring(0, docLookupList[0].getAttribute("handler").indexOf(",")); } else if (docLookupList[0].hasAttribute("name")) { // Get the protocol name selectedWordXmlElement.ElementType = docLookupList[0].getAttribute("name"); } } } return selectedWordXmlElement; } public static GetXmlFilesWithCurrentFile(document: vscode.TextDocument): Thenable<FileData[]> { var files: FileData[] = []; // Add the current selected file while skipping the deployment output environments files if (document.uri.fsPath.toLowerCase().indexOf("/environments/") == (-1)) { files.push(new FileData(document.uri, document.getText().replace(/( )(Id=|Id =|Id =)/gi, " id="))); } // Add the rest of open files for (const doc of vscode.workspace.textDocuments) { // Skip deployment output environments files if (doc.uri.fsPath.toLowerCase().indexOf("/environments/")) continue; // Skip selected file if (doc.uri != document.uri && doc.uri.scheme != "git") files.push(new FileData(doc.uri, doc.getText().replace(/( )(Id=|Id =|Id =)/gi, " id="))) } // Run this code only if user open a directory workspace. // Get files from the file system if (vscode.workspace.rootPath) { var promise = vscode.workspace.findFiles(new vscode.RelativePattern(vscode.workspace.rootPath as string, '*.{xml}')) .then((uris) => { uris.forEach((uri) => { if (uri.fsPath.indexOf("?") <= 0) { // Check if the file is open. If yes, take precedence over the saved version var openedFile = files.filter(x => x.Uri.fsPath == uri.fsPath) if (openedFile == null || openedFile.length == 0) { var data = fs.readFileSync(uri.fsPath, 'utf8'); files.push(new FileData(uri, data.toString().replace(/( )(Id=|Id =|Id =)/gi, " id="))); } } }); }).then(() => { return files }); return promise; } else return new Promise(resolve => { resolve(files);; }); } public static GetFileHierarchy(files: FileData[], file: FileData, hierarchyFiles: FileData[], level: number): FileData[] { if (level == 1) { file.Level = level; hierarchyFiles.push(file); } var parentPolicy: FileData[] = files.filter(x => x.Policy == file.ParentPolicy); if (parentPolicy != null && parentPolicy.length > 0) { level++; parentPolicy[0].Level = level; hierarchyFiles.push(parentPolicy[0]); hierarchyFiles = XmlHelper.GetFileHierarchy(files, parentPolicy[0], hierarchyFiles, level); } return hierarchyFiles.sort(x => x.Level).reverse(); } // Check if current selection is next to a XML attribute public static IsCloseToAttribute(attributeName: string, line: string, position: vscode.Position): boolean { let index = line.toLowerCase().lastIndexOf(attributeName.toLowerCase()) if (index == (-1)) return false; index = position.character - (index + attributeName.length + 2); return (index >= 0 && index < 15); } public static IsInNodeAndCloseToAttribute(nodeName: string, attributeName: string, line: string, position: vscode.Position): boolean { return (XmlHelper.IsCloseToAttribute(attributeName, line, position) && (line.toLowerCase().indexOf(nodeName.toLowerCase()) > 0) && line.toLowerCase().indexOf(nodeName.toLowerCase()) < position.character); } public static GetElementIDsByNodeName(nodeName: string, files: FileData[]): string[] { var items: string[] = []; for (const file of files) { var xmlDoc = new DOMParser().parseFromString(file.Data); var docLookupList = xmlDoc.getElementsByTagName(nodeName); for (let i = 0; i < docLookupList.length; i++) { if (docLookupList[i].hasAttribute("id")) { let Id = docLookupList[i].getAttribute("id"); if (items.indexOf(Id) == (-1)) { items.push(Id); } } } } return items; } public static IsStartOfOpeningElement(document: TextDocument, position: Position): boolean { return XmlHelper.IsTextBeforeTypedWordEqualTo(document, position, '<'); } public static IsStartOfClosingElement(document: TextDocument, position: Position): boolean { return XmlHelper.IsTextBeforeTypedWordEqualTo(document, position, '</'); } public static IsEndOfElement(document: TextDocument, position: Position): boolean { return XmlHelper.IsTextBeforeTypedWordEqualTo(document, position, '>'); } public static IsCurlyBrackets(document: TextDocument, position: Position): boolean { return XmlHelper.IsTextBeforeTypedWordEqualTo(document, position, '{'); } public static IsTextBeforeTypedWordEqualTo(document: TextDocument, position: Position, textToMatch: string) { let wordRange = document.getWordRangeAtPosition(position); let wordStart = wordRange ? wordRange.start : position; if (wordStart.character < textToMatch.length) { // Not enough room to match return false; } let charBeforeWord = document.getText(new Range(new Position(wordStart.line, wordStart.character - textToMatch.length), wordStart)); return charBeforeWord === textToMatch; } public static IsNodeClosed(document: TextDocument, position: Position) { let wordRange = document.getWordRangeAtPosition(position); let wordStart = wordRange ? wordRange.start : position; let charAfterWord = document.getText(new Range(new Position(wordStart.line, wordStart.character + 1), wordStart)); return charAfterWord === '>'; } public static IsStartOfAttribute(document: TextDocument, position: Position): boolean { let wordRange = document.getWordRangeAtPosition(position); let wordStartPosition = wordRange ? wordRange.start : position; let text = document.getText(); let wordStartIndex: number = document.offsetAt(wordStartPosition) let beforeStartBracket: number = text.lastIndexOf('<', wordStartIndex - 1); let beforeStartBracketIsAnEndTak: number = text.lastIndexOf('</', wordStartIndex - 1); let beforeCloseBracket: number = text.lastIndexOf('>', wordStartIndex - 1); let afterStartBracket: number = text.indexOf('<', wordStartIndex); let afterCloseBracket: number = text.indexOf('>', wordStartIndex); // Check whether the cursor is inside a property let insideQuotation: boolean = false; let beforeQuotation: number = text.lastIndexOf('"', wordStartIndex - 1); if (beforeQuotation > beforeStartBracket) for (let i = beforeQuotation + 1; i <= (wordStartIndex -1); i++) { if (text[i] != " ") {insideQuotation = true; break;} } // The cursor must be immediately after START, but not after CLOSE and // immediately before CLOSE, but not after START return XmlHelper.IsTextBeforeTypedWordEqualTo(document, position, ' ') && ((beforeStartBracket > beforeCloseBracket) || beforeCloseBracket == -1) && ((afterCloseBracket < afterStartBracket) || afterStartBracket == -1) && beforeStartBracket != beforeStartBracketIsAnEndTak && wordStartIndex >= beforeStartBracket && wordStartIndex <= afterCloseBracket && (!insideQuotation); } // Check if the cursor is about complete the value of an attribute. public static IsStartOfAttributeValue(document: TextDocument, position: Position): boolean { let wordRange = document.getWordRangeAtPosition(position); let wordStart = wordRange ? wordRange.start : position; let wordEnd = wordRange ? wordRange.end : position; if (wordStart.character === 0 || wordEnd.character > document.lineAt(wordEnd.line).text.length - 1) { return false; } // TODO: This detection is very limited, only if the char before the word is ' or " let rangeBefore = new Range(wordStart.line, wordStart.character - 1, wordStart.line, wordStart.character); if (document.getText(rangeBefore).match(/'|"/)) { return true; } return false; } public static GetCloseAttributeName(document: TextDocument, position: Position): string | any { // Get the attribute name let wordRange = document.getWordRangeAtPosition(position); let wordStart = wordRange ? wordRange.start : position; let line = document.getText(new Range(wordStart.line, 0, wordStart.line, wordStart.character)); let attrNamePattern = /[\.\-:_a-zA-Z0-9]+=/g; let match = line.match(attrNamePattern); if (match) { let attrName = match.reverse()[0]; attrName = attrName.slice(0, -1); return attrName; } } // Get the full XPath to the current tag. public static GetXPath(document: TextDocument, position: Position): string[] { // For every row, checks if it's an open, close, or autoopenclose tag and // update a list of all the open tags. //{row, column} = bufferPosition let xpath: string[] = []; let skipList: string[] = []; let waitingStartTag = false; let waitingStartComment = false; // This will catch: // * Start tags: <tagName // * End tags: </tagName // * Auto close tags: /> let startTagPattern = '<\s*[\\.\\-:_a-zA-Z0-9]+'; let endTagPattern = '<\\/\s*[\\.\\-:_a-zA-Z0-9]+'; let autoClosePattern = '\\/>'; let startCommentPattern = '\s*<!--'; let endCommentPattern = '\s*-->'; let fullPattern = new RegExp("(" + startTagPattern + "|" + endTagPattern + "|" + autoClosePattern + "|" + startCommentPattern + "|" + endCommentPattern + ")", "g"); // For the first line read, excluding the word the cursor is over let wordRange = document.getWordRangeAtPosition(position); let wordStart = wordRange ? wordRange.start : position; let line = document.getText(new Range(position.line, 0, position.line, wordStart.character)); let row = position.line; while (row >= 0) { //and (!maxDepth or xpath.length < maxDepth) row--; // Apply the regex expression, read from right to left. let matches = line.match(fullPattern); if (matches) { matches.reverse(); for (let i = 0; i < matches.length; i++) { let match = matches[i]; let tagName; // Start comment if (match === "<!--") { waitingStartComment = false; } // End comment else if (match === "-->") { waitingStartComment = true; } // Omit comment content else if (waitingStartComment) { continue; } // Auto tag close else if (match === "/>") { waitingStartTag = true; } // End tag else if (match[0] === "<" && match[1] === "/") { skipList.push(match.slice(2)); } // This should be a start tag else if (match[0] === "<" && waitingStartTag) { waitingStartTag = false; } else if (match[0] == "<") { tagName = match.slice(1); // Omit XML definition. if (tagName === "?xml") { continue; } let idx = skipList.lastIndexOf(tagName); if (idx != -1) { skipList.splice(idx, 1); } else { xpath.push(tagName); } } }; } // Get next line if (row >= 0) { line = document.lineAt(row).text; } } return xpath.reverse(); } }
the_stack
import VideoSettings from '../VideoSettings'; import ScreenInfo from '../ScreenInfo'; import Rect from '../Rect'; import Size from '../Size'; import Util from '../Util'; import { TypedEmitter } from '../../common/TypedEmitter'; import { DisplayInfo } from '../DisplayInfo'; interface BitrateStat { timestamp: number; bytes: number; } interface FramesPerSecondStats { avgInput: number; avgDecoded: number; avgDropped: number; avgSize: number; } export interface PlaybackQuality { decodedFrames: number; droppedFrames: number; inputFrames: number; inputBytes: number; timestamp: number; } export interface PlayerEvents { 'video-view-resize': Size; 'input-video-resize': ScreenInfo; 'video-settings': VideoSettings; } export interface PlayerClass { playerFullName: string; playerCodeName: string; storageKeyPrefix: string; isSupported(): boolean; getPreferredVideoSetting(): VideoSettings; getFitToScreenStatus(deviceName: string, displayInfo?: DisplayInfo): boolean; loadVideoSettings(deviceName: string, displayInfo?: DisplayInfo): VideoSettings; saveVideoSettings( deviceName: string, videoSettings: VideoSettings, fitToScreen: boolean, displayInfo?: DisplayInfo, ): void; new (udid: string, displayInfo?: DisplayInfo): BasePlayer; } export abstract class BasePlayer extends TypedEmitter<PlayerEvents> { private static readonly STAT_BACKGROUND: string = 'rgba(0, 0, 0, 0.5)'; private static readonly STAT_TEXT_COLOR: string = 'hsl(24, 85%, 50%)'; public static readonly DEFAULT_SHOW_QUALITY_STATS = false; public static STATE: Record<string, number> = { PLAYING: 1, PAUSED: 2, STOPPED: 3, }; private static STATS_HEIGHT = 12; protected screenInfo?: ScreenInfo; protected videoSettings: VideoSettings; protected parentElement?: HTMLElement; protected touchableCanvas: HTMLCanvasElement; protected inputBytes: BitrateStat[] = []; protected perSecondQualityStats?: FramesPerSecondStats; protected momentumQualityStats?: PlaybackQuality; protected bounds: Size | null = null; private totalStats: PlaybackQuality = { decodedFrames: 0, droppedFrames: 0, inputFrames: 0, inputBytes: 0, timestamp: 0, }; private totalStatsCounter = 0; private dirtyStatsWidth = 0; private state: number = BasePlayer.STATE.STOPPED; private qualityAnimationId?: number; private showQualityStats = BasePlayer.DEFAULT_SHOW_QUALITY_STATS; protected receivedFirstFrame = false; private statLines: string[] = []; public readonly supportsScreenshot: boolean = false; public static storageKeyPrefix = 'BaseDecoder'; public static playerFullName = 'BasePlayer'; public static playerCodeName = 'baseplayer'; public static preferredVideoSettings: VideoSettings = new VideoSettings({ lockedVideoOrientation: -1, bitrate: 524288, maxFps: 24, iFrameInterval: 5, bounds: new Size(480, 480), sendFrameMeta: false, }); constructor( public readonly udid: string, protected displayInfo?: DisplayInfo, protected name: string = 'BasePlayer', protected storageKeyPrefix: string = 'Dummy', protected tag: HTMLElement = document.createElement('div'), ) { super(); this.touchableCanvas = document.createElement('canvas'); this.touchableCanvas.className = 'touch-layer'; this.touchableCanvas.oncontextmenu = function (e: MouseEvent): void { e.preventDefault(); }; const preferred = this.getPreferredVideoSetting(); this.videoSettings = BasePlayer.getVideoSettingFromStorage(preferred, this.storageKeyPrefix, udid, displayInfo); } protected static isIFrame(frame: Uint8Array): boolean { // last 5 bits === 5: Coded slice of an IDR picture // https://www.ietf.org/rfc/rfc3984.txt // 1.3. Network Abstraction Layer Unit Types // https://www.itu.int/rec/T-REC-H.264-201906-I/en // Table 7-1 – NAL unit type codes, syntax element categories, and NAL unit type classes return frame && frame.length > 4 && (frame[4] & 31) === 5; } private static getStorageKey(storageKeyPrefix: string, udid: string): string { const { innerHeight, innerWidth } = window; return `${storageKeyPrefix}:${udid}:${innerWidth}x${innerHeight}`; } private static getFullStorageKey(storageKeyPrefix: string, udid: string, displayInfo?: DisplayInfo): string { const { innerHeight, innerWidth } = window; let base = `${storageKeyPrefix}:${udid}:${innerWidth}x${innerHeight}`; if (displayInfo) { const { displayId, size } = displayInfo; base = `${base}:${displayId}:${size.width}x${size.height}`; } return base; } public static getFromStorageCompat(prefix: string, udid: string, displayInfo?: DisplayInfo): string | null { const shortKey = this.getStorageKey(prefix, udid); const savedInShort = window.localStorage.getItem(shortKey); if (!displayInfo) { return savedInShort; } const isDefaultDisplay = displayInfo.displayId === DisplayInfo.DEFAULT_DISPLAY; const fullKey = this.getFullStorageKey(prefix, udid, displayInfo); const savedInFull = window.localStorage.getItem(fullKey); if (savedInFull) { if (savedInShort && isDefaultDisplay) { window.localStorage.removeItem(shortKey); } return savedInFull; } if (isDefaultDisplay) { return savedInShort; } return null; } public static getFitToScreenFromStorage( storageKeyPrefix: string, udid: string, displayInfo?: DisplayInfo, ): boolean { if (!window.localStorage) { return false; } let parsedValue = false; const key = `${this.getFullStorageKey(storageKeyPrefix, udid, displayInfo)}:fit`; const saved = window.localStorage.getItem(key); if (!saved) { return false; } try { parsedValue = JSON.parse(saved); } catch (e) { console.error(`[${this.name}]`, 'Failed to parse', saved); } return parsedValue; } public static getVideoSettingFromStorage( preferred: VideoSettings, storageKeyPrefix: string, udid: string, displayInfo?: DisplayInfo, ): VideoSettings { if (!window.localStorage) { return preferred; } const saved = this.getFromStorageCompat(storageKeyPrefix, udid, displayInfo); if (!saved) { return preferred; } const parsed = JSON.parse(saved); const { displayId, crop, bitrate, iFrameInterval, sendFrameMeta, lockedVideoOrientation, codecOptions, encoderName, } = parsed; // REMOVE `frameRate` const maxFps = isNaN(parsed.maxFps) ? parsed.frameRate : parsed.maxFps; // REMOVE `maxSize` let bounds: Size | null = null; if (typeof parsed.bounds !== 'object' || isNaN(parsed.bounds.width) || isNaN(parsed.bounds.height)) { if (!isNaN(parsed.maxSize)) { bounds = new Size(parsed.maxSize, parsed.maxSize); } } else { bounds = new Size(parsed.bounds.width, parsed.bounds.height); } return new VideoSettings({ displayId: typeof displayId === 'number' ? displayId : 0, crop: crop ? new Rect(crop.left, crop.top, crop.right, crop.bottom) : preferred.crop, bitrate: !isNaN(bitrate) ? bitrate : preferred.bitrate, bounds: bounds !== null ? bounds : preferred.bounds, maxFps: !isNaN(maxFps) ? maxFps : preferred.maxFps, iFrameInterval: !isNaN(iFrameInterval) ? iFrameInterval : preferred.iFrameInterval, sendFrameMeta: typeof sendFrameMeta === 'boolean' ? sendFrameMeta : preferred.sendFrameMeta, lockedVideoOrientation: !isNaN(lockedVideoOrientation) ? lockedVideoOrientation : preferred.lockedVideoOrientation, codecOptions, encoderName, }); } protected static putVideoSettingsToStorage( storageKeyPrefix: string, udid: string, videoSettings: VideoSettings, fitToScreen: boolean, displayInfo?: DisplayInfo, ): void { if (!window.localStorage) { return; } const key = this.getFullStorageKey(storageKeyPrefix, udid, displayInfo); window.localStorage.setItem(key, JSON.stringify(videoSettings)); const fitKey = `${key}:fit`; window.localStorage.setItem(fitKey, JSON.stringify(fitToScreen)); } public abstract getImageDataURL(): string; public createScreenshot(deviceName: string): void { const a = document.createElement('a'); a.href = this.getImageDataURL(); a.download = `${deviceName} ${new Date().toLocaleString()}.png`; a.click(); } public play(): void { if (this.needScreenInfoBeforePlay() && !this.screenInfo) { return; } this.state = BasePlayer.STATE.PLAYING; } public pause(): void { this.state = BasePlayer.STATE.PAUSED; } public stop(): void { this.state = BasePlayer.STATE.STOPPED; } public getState(): number { return this.state; } public pushFrame(frame: Uint8Array): void { if (!this.receivedFirstFrame) { this.receivedFirstFrame = true; if (typeof this.qualityAnimationId !== 'number') { this.qualityAnimationId = requestAnimationFrame(this.updateQualityStats); } } this.inputBytes.push({ timestamp: Date.now(), bytes: frame.byteLength, }); } public abstract getPreferredVideoSetting(): VideoSettings; protected abstract calculateMomentumStats(): void; public getTouchableElement(): HTMLCanvasElement { return this.touchableCanvas; } public setParent(parent: HTMLElement): void { this.parentElement = parent; parent.appendChild(this.tag); parent.appendChild(this.touchableCanvas); } protected needScreenInfoBeforePlay(): boolean { return true; } public getVideoSettings(): VideoSettings { return this.videoSettings; } public setVideoSettings(videoSettings: VideoSettings, fitToScreen: boolean, saveToStorage: boolean): void { this.videoSettings = videoSettings; if (saveToStorage) { BasePlayer.putVideoSettingsToStorage( this.storageKeyPrefix, this.udid, videoSettings, fitToScreen, this.displayInfo, ); } this.resetStats(); this.emit('video-settings', VideoSettings.copy(videoSettings)); } public getScreenInfo(): ScreenInfo | undefined { return this.screenInfo; } public setScreenInfo(screenInfo: ScreenInfo): void { if (this.needScreenInfoBeforePlay()) { this.pause(); } this.receivedFirstFrame = false; this.screenInfo = screenInfo; const { width, height } = screenInfo.videoSize; this.touchableCanvas.width = width; this.touchableCanvas.height = height; if (this.parentElement) { this.parentElement.style.height = `${height}px`; this.parentElement.style.width = `${width}px`; } const size = new Size(width, height); this.emit('video-view-resize', size); } public getName(): string { return this.name; } protected resetStats(): void { this.receivedFirstFrame = false; this.totalStatsCounter = 0; this.totalStats = { droppedFrames: 0, decodedFrames: 0, inputFrames: 0, inputBytes: 0, timestamp: 0, }; this.perSecondQualityStats = { avgDecoded: 0, avgDropped: 0, avgInput: 0, avgSize: 0, }; } private updateQualityStats = (): void => { const now = Date.now(); const oneSecondBefore = now - 1000; this.calculateMomentumStats(); if (!this.momentumQualityStats) { return; } if (this.totalStats.timestamp < oneSecondBefore) { this.totalStats = { timestamp: now, decodedFrames: this.totalStats.decodedFrames + this.momentumQualityStats.decodedFrames, droppedFrames: this.totalStats.droppedFrames + this.momentumQualityStats.droppedFrames, inputFrames: this.totalStats.inputFrames + this.momentumQualityStats.inputFrames, inputBytes: this.totalStats.inputBytes + this.momentumQualityStats.inputBytes, }; if (this.totalStatsCounter !== 0) { this.perSecondQualityStats = { avgDecoded: this.totalStats.decodedFrames / this.totalStatsCounter, avgDropped: this.totalStats.droppedFrames / this.totalStatsCounter, avgInput: this.totalStats.inputFrames / this.totalStatsCounter, avgSize: this.totalStats.inputBytes / this.totalStatsCounter, }; } this.totalStatsCounter++; } this.drawStats(); if (this.state !== BasePlayer.STATE.STOPPED) { this.qualityAnimationId = requestAnimationFrame(this.updateQualityStats); } }; private drawStats(): void { if (!this.showQualityStats) { return; } const ctx = this.touchableCanvas.getContext('2d'); if (!ctx) { return; } const newStats = []; if (this.perSecondQualityStats && this.momentumQualityStats) { const { decodedFrames, droppedFrames, inputBytes, inputFrames } = this.momentumQualityStats; const { avgDecoded, avgDropped, avgSize, avgInput } = this.perSecondQualityStats; const padInput = inputFrames.toString().padStart(3, ' '); const padDecoded = decodedFrames.toString().padStart(3, ' '); const padDropped = droppedFrames.toString().padStart(3, ' '); const padAvgDecoded = avgDecoded.toFixed(1).padStart(5, ' '); const padAvgDropped = avgDropped.toFixed(1).padStart(5, ' '); const padAvgInput = avgInput.toFixed(1).padStart(5, ' '); const prettyBytes = Util.prettyBytes(inputBytes).padStart(8, ' '); const prettyAvgBytes = Util.prettyBytes(avgSize).padStart(8, ' '); newStats.push(`Input bytes: ${prettyBytes} (avg: ${prettyAvgBytes}/s)`); newStats.push(`Input FPS: ${padInput} (avg: ${padAvgInput})`); newStats.push(`Dropped FPS: ${padDropped} (avg: ${padAvgDropped})`); newStats.push(`Decoded FPS: ${padDecoded} (avg: ${padAvgDecoded})`); } else { newStats.push(`Not supported`); } let changed = this.statLines.length !== newStats.length; let i = 0; while (!changed && i++ < newStats.length) { if (newStats[i] !== this.statLines[i]) { changed = true; } } if (changed) { this.statLines = newStats; this.updateCanvas(false); } } private updateCanvas(onlyClear: boolean): void { const ctx = this.touchableCanvas.getContext('2d'); if (!ctx) { return; } const y = this.touchableCanvas.height; const height = BasePlayer.STATS_HEIGHT; const lines = this.statLines.length; const spaces = lines + 1; const p = height / 2; const d = p * 2; const totalHeight = height * lines + p * spaces; ctx.clearRect(0, y - totalHeight, this.dirtyStatsWidth + d, totalHeight); this.dirtyStatsWidth = 0; if (onlyClear) { return; } ctx.save(); ctx.font = `${height}px monospace`; this.statLines.forEach((text) => { const textMetrics = ctx.measureText(text); const dirty = Math.abs(textMetrics.actualBoundingBoxLeft) + Math.abs(textMetrics.actualBoundingBoxRight); this.dirtyStatsWidth = Math.max(dirty, this.dirtyStatsWidth); }); ctx.fillStyle = BasePlayer.STAT_BACKGROUND; ctx.fillRect(0, y - totalHeight, this.dirtyStatsWidth + d, totalHeight); ctx.fillStyle = BasePlayer.STAT_TEXT_COLOR; this.statLines.forEach((text, line) => { ctx.fillText(text, p, y - p - line * (height + p)); }); ctx.restore(); } public setShowQualityStats(value: boolean): void { this.showQualityStats = value; if (!value) { this.updateCanvas(true); } else { this.drawStats(); } } public getShowQualityStats(): boolean { return this.showQualityStats; } public setBounds(bounds: Size): void { this.bounds = Size.copy(bounds); } public getDisplayInfo(): DisplayInfo | undefined { return this.displayInfo; } public setDisplayInfo(displayInfo: DisplayInfo): void { this.displayInfo = displayInfo; } public abstract getFitToScreenStatus(): boolean; public abstract loadVideoSettings(): VideoSettings; public static loadVideoSettings(udid: string, displayInfo?: DisplayInfo): VideoSettings { return this.getVideoSettingFromStorage(this.preferredVideoSettings, this.storageKeyPrefix, udid, displayInfo); } public static getFitToScreenStatus(udid: string, displayInfo?: DisplayInfo): boolean { return this.getFitToScreenFromStorage(this.storageKeyPrefix, udid, displayInfo); } public static getPreferredVideoSetting(): VideoSettings { return this.preferredVideoSettings; } public static saveVideoSettings( udid: string, videoSettings: VideoSettings, fitToScreen: boolean, displayInfo?: DisplayInfo, ): void { this.putVideoSettingsToStorage(this.storageKeyPrefix, udid, videoSettings, fitToScreen, displayInfo); } }
the_stack
import assert from 'assert'; import _ from 'lodash'; import sinon from 'sinon'; import React from 'react'; import PropTypes from 'prop-types'; import { mount } from 'enzyme'; import { getDeepPaths, omitFunctionPropsDeep, bindReducerToState, bindReducersToState, getStatefulPropsContext, reduceSelectors, safeMerge, buildHybridComponent, } from './state-management'; import { createClass } from './component-types'; describe('#getDeepPaths', () => { it('should return an empty array when arg is empty object, null, or undefined', () => { assert(_.isEqual([], getDeepPaths({}))); assert(_.isEqual([], getDeepPaths())); assert(_.isEqual([], getDeepPaths(null))); }); it('should return an array of paths for each node with non-plain object value if arg is object', () => { const pagedTableObj = { rows: ['data0', 'data1'], paginator: { selectedPageIndex: 0, selectedPageSize: 10, dropselector: { selectedIndex: 1, options: [5, 10, 20], }, }, }; const deepPaths = getDeepPaths(pagedTableObj); const xorPaths = _.xorWith( deepPaths, [ ['rows'], ['paginator', 'selectedPageIndex'], ['paginator', 'selectedPageSize'], ['paginator', 'dropselector', 'selectedIndex'], ['paginator', 'dropselector', 'options'], ], _.isEqual ); assert(_.isEqual([], xorPaths)); }); it('should return an array of paths for each node with non-plain object value if arg is array', () => { const deepPaths = getDeepPaths(['zero', { one: 1 }, 2]); const xorPaths = _.xorWith(deepPaths, [[0], [1, 'one'], [2]], _.isEqual); assert(_.isEqual([], xorPaths)); }); }); describe('#omitFunctionPropsDeep', () => { it('should return an empty object when arg is empty object, null, or undefined', () => { assert(_.isEqual({}, omitFunctionPropsDeep({}))); assert(_.isEqual({}, omitFunctionPropsDeep(null))); assert(_.isEqual({}, omitFunctionPropsDeep())); }); it('should transform to object without function properties', () => { const pagedTableObj = { rows: ['data0', 'data1'], onRowSelect: _.noop, paginator: { selectedPageIndex: 0, selectedPageSize: 10, onPageSizeSelect: _.noop, onPageSelect: _.noop, dropselector: { selectedIndex: 1, options: [5, 10, 20], onSelect: _.noop, }, }, }; const result = omitFunctionPropsDeep(pagedTableObj); assert( _.isEqual(result, { rows: ['data0', 'data1'], paginator: { selectedPageIndex: 0, selectedPageSize: 10, dropselector: { selectedIndex: 1, options: [5, 10, 20], }, }, }) ); }); }); describe('#bindReducerToState', () => { it('should bind a single reducer function to a state management interface', () => { let state = { value: null, }; const stateManager = { getState() { return state; }, setState(nextState: any) { state = nextState; }, }; function setValue(state: any, value: any) { return _.assign({}, state, { value }); } const boundSetValue = bindReducerToState(setValue, stateManager); assert.equal(state.value, null); boundSetValue('foo'); assert.equal(state.value, 'foo'); }); it('should bind a single, nested reducer function to a state management interface', () => { let state = { sub: { value: null, }, }; const stateManager = { getState() { return state; }, setState(nextState: any) { state = nextState; }, }; function setValue(state: any, value: any) { return _.assign({}, state, { value }); } const boundSetValue = bindReducerToState(setValue, stateManager, [ 'sub', 'setValue', ]); assert.equal(state.sub.value, null); boundSetValue('foo'); assert.equal(state.sub.value, 'foo'); }); }); describe('#bindReducersToState', () => { it('should bind an object of reducers functions to a state management interface', () => { let state = { counter: 0, }; const stateManager = { getState() { return state; }, setState(nextState: any) { state = nextState; }, }; const reducers = { increaseCounter: (state: any) => _.assign({}, state, { counter: state.counter + 1, }), decreaseCounter: (state: any) => _.assign({}, state, { counter: state.counter - 1, }), setCounter: (state: any, x: any) => _.assign({}, state, { counter: x, }), }; const boundReducers: any = bindReducersToState(reducers, stateManager); assert.equal(state.counter, 0); boundReducers.increaseCounter(); assert.equal(state.counter, 1); boundReducers.setCounter(32); assert.equal(state.counter, 32); boundReducers.decreaseCounter(); assert.equal(state.counter, 31); }); it('should bind an object of nested reducers functions to a state management interface', () => { let state = { name: '', count: { counter: 0, }, }; const stateManager = { getState() { return state; }, setState(nextState: any) { state = nextState; }, }; const reducers = { setName: (state: any, newName: any) => _.assign({}, state, { name: newName, }), count: { increaseCounter: (state: any) => _.assign({}, state, { counter: state.counter + 1, }), decreaseCounter: (state: any) => _.assign({}, state, { counter: state.counter - 1, }), setCounter: (state: any, x: any) => _.assign({}, state, { counter: x, }), }, }; const boundReducers: any = bindReducersToState(reducers, stateManager); assert.equal(state.name, ''); assert.equal(state.count.counter, 0); boundReducers.setName('Neumann'); assert.equal(state.name, 'Neumann'); boundReducers.count.increaseCounter(); assert.equal(state.count.counter, 1); boundReducers.count.setCounter(32); assert.equal(state.count.counter, 32); boundReducers.count.decreaseCounter(); assert.equal(state.count.counter, 31); assert( _.isEqual(state, { name: 'Neumann', count: { counter: 31, }, }) ); }); }); describe('#getStatefulPropsContext', () => { function isFunctions(objValue: any, othValue: any) { if (_.isFunction(objValue) && _.isFunction(othValue)) { return true; } } it('should return an object with two functions on it', () => { const statefulPropsContext = getStatefulPropsContext({}, {} as any); const getPropReplaceReducers = _.get( statefulPropsContext, 'getPropReplaceReducers' ); const getProps = _.get(statefulPropsContext, 'getProps'); assert(_.isFunction(getPropReplaceReducers)); assert(_.isFunction(getProps)); }); describe('statefulPropsContext', () => { let state: any; let stateManager: any; let reducers: any; let statefulPropsContext: any; beforeEach(() => { state = { name: '', count: { counter: 0, }, }; stateManager = { getState() { return state; }, setState(nextState: any) { state = nextState; }, }; reducers = { setName: (state: any, newName: any) => _.assign({}, state, { name: newName, }), count: { increaseCounter: (state: any) => _.assign({}, state, { counter: state.counter + 1, }), decreaseCounter: (state: any) => _.assign({}, state, { counter: state.counter - 1, }), setCounter: (state: any, x: any) => _.assign({}, state, { counter: x, }), }, }; sinon.spy(reducers, 'setName'); sinon.spy(reducers.count, 'increaseCounter'); sinon.spy(reducers.count, 'decreaseCounter'); sinon.spy(reducers.count, 'setCounter'); statefulPropsContext = getStatefulPropsContext(reducers, stateManager); }); describe('.getProps', () => { it('should return an object with reducers and current state merged', () => { const props = statefulPropsContext.getProps(); assert(_.isEqualWith(props, _.merge({}, state, reducers), isFunctions)); }); it('should return an object with reducers and current state merged with prop arg overrides', () => { const overrides = { name: 'Neumann', dead: 0xbeef, }; const props = statefulPropsContext.getProps(overrides); assert( _.isEqualWith( props, _.merge({}, state, reducers, overrides), isFunctions ) ); }); it('should return an object with current state applied after function call modifies state', () => { const overrides = { name: 'Neumann', }; let props; props = statefulPropsContext.getProps(overrides); assert.equal(props.count.counter, 0); props.count.increaseCounter(); props = statefulPropsContext.getProps(overrides); assert.equal(props.count.counter, 1); props.count.setCounter(16); props = statefulPropsContext.getProps(overrides); assert.equal(props.count.counter, 16); props.count.decreaseCounter(); props = statefulPropsContext.getProps(overrides); assert.equal(props.count.counter, 15); }); it('should call override function after the same reducer function', () => { const overrides = { setName: sinon.spy(), }; let props; props = statefulPropsContext.getProps(overrides); assert.equal(props.name, ''); props.setName('Neumann'); props = statefulPropsContext.getProps(overrides); assert.equal(props.name, 'Neumann'); assert(reducers.setName.calledOnce); assert(overrides.setName.calledOnce); assert(reducers.setName.calledBefore(overrides.setName)); }); // Test written because of a perf issue related to cloning we ran into // with lodash@4.7.0 -- https://github.com/appnexus/lucid/issues/181 it('should not clone arrays when the source object is undefined', () => { const overrides = { fresh: [{ a: 1 }], }; const props = statefulPropsContext.getProps(overrides); assert(overrides.fresh[0] === props.fresh[0]); }); }); describe('.getPropReplaceReducers', () => { it('should return an object with reducers and current state merged', () => { const props = statefulPropsContext.getPropReplaceReducers(); assert(_.isEqualWith(props, _.merge({}, state, reducers), isFunctions)); }); it('should return an object with reducers and current state merged with prop arg overrides', () => { const overrides = { name: 'Neumann', dead: 0xbeef, }; const props = statefulPropsContext.getPropReplaceReducers(overrides); assert( _.isEqualWith( props, _.merge({}, state, reducers, overrides), isFunctions ) ); }); it('should return an object with current state applied after function call modifies state', () => { const overrides = { name: 'Neumann', }; let props; props = statefulPropsContext.getPropReplaceReducers(overrides); assert.equal(props.count.counter, 0); props.count.increaseCounter(); props = statefulPropsContext.getPropReplaceReducers(overrides); assert.equal(props.count.counter, 1); props.count.setCounter(16); props = statefulPropsContext.getPropReplaceReducers(overrides); assert.equal(props.count.counter, 16); props.count.decreaseCounter(); props = statefulPropsContext.getPropReplaceReducers(overrides); assert.equal(props.count.counter, 15); }); it('should call override function instead of the reducer function', () => { const overrides = { setName: sinon.spy((state, name) => _.assign({}, state, { name: _.toUpper(name) }) ), }; let props; props = statefulPropsContext.getPropReplaceReducers(overrides); assert.equal(props.name, ''); props.setName('Neumann'); props = statefulPropsContext.getPropReplaceReducers(overrides); assert.equal(props.name, 'NEUMANN'); assert(!reducers.setName.called); assert(overrides.setName.calledOnce); }); }); }); }); describe('#reduceSelectors', () => { const selectors = { fooAndBar: ({ foo, bar }: any) => `${foo} and ${bar}`, incrementedBaz: ({ baz }: any) => baz + 1, nested: { nestedFooAndBar: ({ foo, bar }: any) => `${foo} & ${bar}`, nestedIncrementedBaz: ({ baz }: any) => baz + 1, moreNested: { moreNestedFooAndBar: ({ foo, bar }: any) => `${foo} & ${bar}`, }, }, }; const state = { foo: 'foo', bar: 'bar', baz: 0, nested: { foo: 'nestedFoo', bar: 'nestedBar', baz: 10, moreNested: { foo: 'foo', bar: 'bar', }, }, }; const selector = reduceSelectors(selectors); it('should create a single selector function from selector tree', () => { const expected = { foo: 'foo', bar: 'bar', baz: 0, fooAndBar: 'foo and bar', incrementedBaz: 1, nested: { foo: 'nestedFoo', bar: 'nestedBar', baz: 10, nestedFooAndBar: 'nestedFoo & nestedBar', nestedIncrementedBaz: 11, moreNested: { foo: 'foo', bar: 'bar', moreNestedFooAndBar: 'foo & bar', }, }, }; assert.deepEqual(selector(state), expected, 'must be deeply equal'); }); it('should maintain referential equality if source does', () => { assert.equal(selector(state), selector(state)); }); it('should maintain referential equality of branches if source does', () => { assert.equal( selector(state).nested, selector({ ...state, foo: 'bar', bar: 'foo' }).nested ); assert.equal( selector(state).nested.moreNested, selector({ ...state, nested: { ...state.nested, foo: 'bar', bar: 'foo', }, }).nested.moreNested ); }); it('should throw if the selector is not an object', () => { expect(() => { reduceSelectors(['foo']); }).toThrow(); }); it('should not throw if the selector is a babel esModule', () => { /* babel no longer creates plain javascript objects when transpiling imports like `import * as foo from 'someSelectorFile';`. What babel imports has a prototype and a defined `__esModule` property. A common pattern used by consumers is to create a module of selector pure functions, import them all, and directly pass those selectors to the stateful component. */ // eslint-disable-next-line @typescript-eslint/no-empty-function function mockBabelModule() {} mockBabelModule.prototype.foo = 'bar'; // @ts-ignore const someModule: any = new mockBabelModule(); someModule.someSelector = () => {}; Object.defineProperty(someModule, '__esModule', { value: true, enumerable: false, writable: false, }); expect(() => { reduceSelectors(someModule); }).not.toThrow(); }); }); describe('#safeMerge', () => { it('should not merge arrays', () => { const objValue = ['foo']; const srcValue = ['bar']; const value = safeMerge(objValue, srcValue); assert.deepEqual(value, srcValue, 'must be ["bar"]'); }); it('should return valid react elements', () => { const srcValue = <div>foo</div>; const value = safeMerge({}, srcValue); assert.equal(value, srcValue, 'must be srcValue'); }); it('should return arrays that contain react elements', () => { const srcValue = [<div key='1'>foo</div>]; const value = safeMerge({}, srcValue); assert.equal(value, srcValue, 'must be srcValue'); }); it('should return srcValue array if objValue is undefined', () => { const srcValue: any = []; const value = safeMerge(undefined, srcValue); assert.equal(value, srcValue, 'must be srcValue'); }); }); describe('#buildHybridComponent', () => { const CounterDumb = createClass({ displayName: 'Counter', propTypes: { count: PropTypes.number, onIncrement: PropTypes.func, onDecrement: PropTypes.func, countDisplay: PropTypes.string, countModThree: PropTypes.number, } as any, getDefaultProps() { return { count: 0, } as any; }, reducers: { onIncrement(state: any) { return _.assign({}, state, { count: state.count + 1 }) as any; }, onDecrement(state: any) { return _.assign({}, state, { count: state.count - 1 }); }, } as any, selectors: { countDisplay: (state: any) => `count: ${state.count}`, countModThree: (state: any) => state.count % 3, }, render() { const { count, countDisplay, countModThree, onIncrement, onDecrement } = this.props as any; return ( <section> <button className='minus' onClick={onDecrement}> - </button> <span className='count'>{count}</span> <span className='count-display'>{countDisplay}</span> <span className='count-mod-three'>{countModThree}</span> <button className='plus' onClick={onIncrement}> + </button> </section> ); }, }); it('should generate a stateful component from stateless component + reducers', () => { const StatefulCounter = buildHybridComponent(CounterDumb); const wrapper = mount(<StatefulCounter />); const minusButton = wrapper.find('button.minus'); const countSpan = wrapper.find('.count'); const countDisplaySpan = wrapper.find('.count-display'); const countModThreeSpan = wrapper.find('.count-mod-three'); const plusButton = wrapper.find('button.plus'); assert.equal(countSpan.text(), '0'); assert.equal(countDisplaySpan.text(), 'count: 0'); assert.equal(countModThreeSpan.text(), '0'); plusButton.simulate('click'); assert.equal(countSpan.text(), '1'); assert.equal(countDisplaySpan.text(), 'count: 1'); assert.equal(countModThreeSpan.text(), '1'); plusButton.simulate('click'); assert.equal(countSpan.text(), '2'); assert.equal(countDisplaySpan.text(), 'count: 2'); assert.equal(countModThreeSpan.text(), '2'); plusButton.simulate('click'); assert.equal(countSpan.text(), '3'); assert.equal(countDisplaySpan.text(), 'count: 3'); assert.equal(countModThreeSpan.text(), '0'); minusButton.simulate('click'); assert.equal(countSpan.text(), '2'); assert.equal(countDisplaySpan.text(), 'count: 2'); assert.equal(countModThreeSpan.text(), '2'); minusButton.simulate('click'); assert.equal(countSpan.text(), '1'); assert.equal(countDisplaySpan.text(), 'count: 1'); assert.equal(countModThreeSpan.text(), '1'); }); describe('wrapped component', () => { /* eslint-disable no-console */ let warn: any; beforeEach(() => { warn = console.warn; console.warn = jest.fn(); }); it('should not wrap a wrapped component', () => { const StatefulCounter = buildHybridComponent(CounterDumb); assert.equal(StatefulCounter, buildHybridComponent(StatefulCounter)); expect(console.warn).toHaveBeenCalledWith( 'Lucid: you are trying to apply buildHybridComponent to Counter, which is already a hybrid component. Lucid exports hybrid components by default. To access the dumb components, use the -Dumb suffix, e.g. "ComponentDumb"' ); }); afterEach(() => { console.warn = warn; }); /* eslint-enable no-console */ }); it('should prioritize passed-in prop values over internal state', () => { const StatefulCounter = buildHybridComponent(CounterDumb); const wrapper = mount(<StatefulCounter count={36} />); const minusButton = wrapper.find('button.minus'); const countSpan = wrapper.find('.count'); const plusButton = wrapper.find('button.plus'); assert.equal(countSpan.text(), '36'); plusButton.simulate('click'); assert.equal(countSpan.text(), '36'); plusButton.simulate('click'); assert.equal(countSpan.text(), '36'); plusButton.simulate('click'); assert.equal(countSpan.text(), '36'); minusButton.simulate('click'); assert.equal(countSpan.text(), '36'); minusButton.simulate('click'); assert.equal(countSpan.text(), '36'); }); it('should override initial default state with data from the `initialState` prop', () => { const StatefulCounter = buildHybridComponent(CounterDumb); const wrapper = mount(<StatefulCounter initialState={{ count: 36 }} />); const minusButton = wrapper.find('button.minus'); const countSpan = wrapper.find('.count'); const plusButton = wrapper.find('button.plus'); assert.equal(countSpan.text(), '36'); plusButton.simulate('click'); assert.equal(countSpan.text(), '37'); plusButton.simulate('click'); assert.equal(countSpan.text(), '38'); plusButton.simulate('click'); assert.equal(countSpan.text(), '39'); minusButton.simulate('click'); assert.equal(countSpan.text(), '38'); minusButton.simulate('click'); assert.equal(countSpan.text(), '37'); }); it('should call functions passed in thru props with same name as invoked reducers', () => { const onIncrement = sinon.spy(); const onDecrement = sinon.spy(); const StatefulCounter = buildHybridComponent(CounterDumb); const wrapper = mount( <StatefulCounter onIncrement={onIncrement} onDecrement={onDecrement} /> ); const minusButton = wrapper.find('button.minus'); const countSpan = wrapper.find('.count'); const plusButton = wrapper.find('button.plus'); assert(!onIncrement.called); assert(!onDecrement.called); assert.equal(countSpan.text(), '0'); plusButton.simulate('click'); assert(onIncrement.calledOnce); assert(!onDecrement.called); assert.equal(countSpan.text(), '1'); minusButton.simulate('click'); assert(onIncrement.calledOnce); assert(onDecrement.calledOnce); assert.equal(countSpan.text(), '0'); plusButton.simulate('click'); assert(onIncrement.calledTwice); assert(onDecrement.calledOnce); assert.equal(countSpan.text(), '1'); }); it('should allow the consumer to override reducers', () => { const onIncrement = sinon.spy(); const onDecrement = sinon.spy(); const StatefulCounter = buildHybridComponent(CounterDumb, { reducers: { onIncrement, onDecrement }, }); const wrapper = mount(<StatefulCounter />); const minusButton = wrapper.find('button.minus'); const plusButton = wrapper.find('button.plus'); assert(!onIncrement.called); assert(!onDecrement.called); plusButton.simulate('click'); assert(onIncrement.calledOnce); assert(!onDecrement.called); minusButton.simulate('click'); assert(onIncrement.calledOnce); assert(onDecrement.calledOnce); }); });
the_stack
const Service = require('egg').Service; import { ForbiddenError } from 'apollo-server'; import _ = require('lodash'); import urlencode = require('urlencode'); module.exports = class DisposeService extends Service { ctx: any; app: any; constructor(ctx) { super(ctx); } async wechat(input) { const { ctx } = this; const { Item, WechatAccount, Store, Coupon, Order, User, Config, Address, OrderItem, } = ctx.model; console.log('DisposeService input', input); // 找到店铺 const store = await Store.findByPk(input.storeId); // 找到用户权限 const user = await User.findByPk(ctx.state.user.sub); const items: any = []; const orderItem: any = []; if (user.role==='member') { // 循环创建订单内的商品 for (const iterator of input.itemIds) { const item = await Item.findByPk(iterator.itemId); await orderItem.push({ fileKey: item.imageKey, title: item.name, price: item.memberPrice, commission: item.commission, amount: iterator.number * item.memberPrice, number: iterator.number, itemCode: item.code, }); await items.push({ price: item.memberPrice, pointDiscount: item.pointDiscountPrice, number: iterator.number, }); } }else{ // 循环创建订单内的商品 for (const iterator of input.itemIds) { const item = await Item.findByPk(iterator.itemId); await orderItem.push({ fileKey: item.imageKey, title: item.name, price: item.price, commission: item.commission, amount: iterator.number * item.price, number: iterator.number, itemCode: item.code, }); await items.push({ price: item.price, pointDiscount: item.pointDiscountPrice, number: iterator.number, }); } } // 找到当前用户的 openId const wechatAccount = await WechatAccount.findOne({ where: { userId: ctx.state.user.sub, }, }); // 整合订单所需参数 const data: any = { userId: wechatAccount.userId, storeId: store.id, time: input.time, price: items.reduce( (total, { price, number }) => total + price * number, 0, ), amount: items.reduce( (total, { price, number }) => total + price * number, 0, ), // 支付类型 type: input.type, discount: 0, pointDiscount: 0, }; let code = ''; for (let i = 0; i < 8; i++) { const num = Math.floor(Math.random() * 10); code += num; } data.code = code; if (input.couponId) { // 找到所传优惠券 const coupon = await Coupon.findByPk(input.couponId); // 判断优惠券是否存在 且价格是否大于等于优惠券需求的价格 if (coupon && data.amount >= coupon.require) { data.discount += coupon.amount; data.amount -= coupon.amount; } } if (input.pointDiscount) { console.log('input.pointDiscount === true'); // 积分比例为: 消费1元得100积分 100积分可兑换0.01元 // 计算出总可以抵扣的金额(钱 非积分) const pointDiscountAmount = items.reduce( (total, { pointDiscount, number }) => total + pointDiscount * number, 0, ); console.log('input.pointDiscount === true pointDiscountAmount', pointDiscountAmount); const { point } = await User.findByPk(wechatAccount.userId); console.log('input.pointDiscount === true point', point); // 用户积分大于总抵扣积分 if ((point / 100) >= pointDiscountAmount) { data.pointDiscount += pointDiscountAmount; data.amount -= pointDiscountAmount; } else { data.pointDiscount += point / 100; data.amount -= point / 100; } console.log('input.pointDiscount === true data', data); } switch (input.type) { case 'distribution': // 邮费相关 const rel = await Config.findByPk('free'); const cost = await Config.findByPk('cost'); // 判断是否足够免运费的金额 if (data.amount < rel.integer) { data.amount += cost.integer; data.freight = cost.integer; } break; default: break; } console.log('data data data data data', data); // 创建订单 const order = await Order.create(_.pickBy(_.pick( data, [ 'price', 'discount', 'amount', 'couponId', 'userId', 'storeId', 'time', 'code', 'type', 'payment', 'discount', 'freight', 'pointDiscount', ] ), value => value !== null)); if (order) { // 生成二维码并存储至阿里云 await ctx.service.file.generateImage(order.id); } // 更新优惠券 if (input.couponId) { // 找到所传优惠券 const coupon = await Coupon.findByPk(input.couponId); if (coupon) { await coupon.update({ orderId: order.id }); } } if (input.type === 'distribution') { const { receiverName, receiverPhone, receiverAddress } = input.address; // 并创建订单地址 await Address.create({ receiverName, receiverPhone, receiverAddress, orderId: order.id, }); } // 循环创建订单内的商品 for (const iterator of orderItem) { iterator.orderId = order.id; const ordersitem = await OrderItem.create(iterator); console.log('ordersitem',ordersitem); } // 创建交易单号 const { id: tradeId } = await order.createTrade({ price: data.amount, orderId: order.id, }); console.log('tradeId',tradeId); const ip = await ctx.get('x-real-ip'); console.log('ip',ip); return await ctx.app.wechatPay.requestPayment({ body: '购买商品', out_trade_no: String(tradeId), total_fee: order.amount, spbill_create_ip: ip, trade_type: 'JSAPI', openid: wechatAccount.openId, }); }; // 余额支付 async balance(input) { const { ctx, app } = this; const { Order, Item, OrderItem, Store, Coupon, WechatAccount, Config, Address, User, Point, Balance, Phone, } = ctx.model; // 找到当前用户的 openId const wechatAccount = await WechatAccount.findOne({ where: { userId: ctx.state.user.sub, }, }); // 找到店铺 const store = await Store.findByPk(input.storeId); // 找到当前用户 const user = await User.findByPk(wechatAccount.userId); // 取出商品的实际价格及数量 const items: any = []; // 定义订单内的商品 const orderItem: any = []; if (user.role==='member') { // 循环创建订单内的商品 for (const iterator of input.itemIds) { const item = await Item.findByPk(iterator.itemId); await orderItem.push({ fileKey: item.imageKey, title: item.name, price: item.memberPrice, commission: item.commission, amount: iterator.number * item.memberPrice, number: iterator.number, itemCode: item.code, }); await items.push({ price: item.memberPrice, pointDiscount: item.pointDiscountPrice, number: iterator.number, }); } }else{ // 循环创建订单内的商品 for (const iterator of input.itemIds) { const item = await Item.findByPk(iterator.itemId); await orderItem.push({ fileKey: item.imageKey, title: item.name, price: item.price, commission: item.commission, amount: iterator.number * item.price, number: iterator.number, itemCode: item.code, }); await items.push({ price: item.price, pointDiscount: item.pointDiscountPrice, number: iterator.number, }); } } let code = ''; for (let i = 0; i < 8; i++) { const num = Math.floor(Math.random() * 10); code += num; } // 整合订单所需参数 const data: any = { userId: wechatAccount.userId, storeId: store.id, time: input.time, price: items.reduce( (total, { price, number }) => total + price * number, 0, ), amount: items.reduce( (total, { price, number }) => total + price * number, 0, ), code, payment: input.payment, type: input.type, discount: 0, pointDiscount: 0, }; if (input.pointDiscount) { console.log('input.pointDiscount === true'); // 积分比例为: 消费1元得100分 100分可兑换0.01元 // 计算出总可以抵扣的金额 const pointDiscountAmount = items.reduce( (total, { pointDiscount, number }) => total + pointDiscount * number, 0, ); console.log('input.pointDiscount === true pointDiscountAmount', pointDiscountAmount); const { point } = await User.findByPk(wechatAccount.userId); console.log('input.pointDiscount === true point', point); // 用户积分大于总抵扣积分 if ((point / 100) >= pointDiscountAmount) { data.pointDiscount += pointDiscountAmount; data.amount -= pointDiscountAmount; } else { data.pointDiscount += point / 100; data.amount -= point / 100; } console.log('input.pointDiscount === true data', data); } switch (input.type) { case 'distribution': // 邮费相关 const rel = await Config.findByPk('free'); const cost = await Config.findByPk('cost'); // 判断是否足够免运费的金额 if (data.amount < rel.integer) { data.amount += cost.integer; data.freight = cost.integer; } break; default: break; } if (input.couponId) { // 找到所传优惠券 const coupon = await Coupon.findByPk(input.couponId); // 判断优惠券是否存在 且价格是否大于等于优惠券需求的价格 if (coupon && data.amount >= coupon.require) { data.discount += coupon.amount; data.amount -= coupon.amount; } } // 创建订单 const order = await Order.create(_.pickBy( _.pick(data, [ 'price', 'discount', 'amount', 'couponId', 'userId', 'storeId', 'time', 'code', 'type', 'payment', 'discount', 'freight', 'pointDiscount', ]), value => value !== null)); if (order) { // 生成二维码并存储至阿里云 await ctx.service.file.generateImage(order.id); } // 更新优惠券 if (input.couponId) { // 找到所传优惠券 const coupon = await Coupon.findByPk(input.couponId); if (coupon) { await coupon.update({ orderId: order.id }); } } if (input.type === 'distribution') { const { receiverName, receiverPhone, receiverAddress } = input.address; // 并创建订单地址 await Address.create({ receiverName, receiverPhone, receiverAddress, orderId: order.id, }); } // 循环创建订单内的商品 for (const iterator of orderItem) { iterator.orderId = order.id; await OrderItem.create(iterator) } // 创建交易单号 const trade = await order.createTrade({ price: data.amount, orderId: order.id, }); // 若用户的余额大于等于订单的总价 if (user.balance >= order.amount) { // 更新交易状态 switch (order.type) { case 'storeBuy': await trade.update({ status: 'paid' }); await order.update({ status: 'completed' }); break; case 'distribution': await trade.update({ status: 'paid' }); await order.update({ status: 'paid' }); break; case 'unmanned': await trade.update({ status: 'paid' }); await order.update({ status: 'fetch' }); break; default: break; } // 获取百度的 token const token = await app.redis.get('baiduAccessToken'); if (token) { // 定义路径 const nsp = app.io.of('/'); const phone = await Phone.findOne({ where: { userId: order.userId } }); // 定义文本 let text = ''; let number = 0; let tailNumber = ''; let bindPhone = true; if (phone) { bindPhone = true; tailNumber = phone.number.substr(-4); let orderType = ''; switch (order.type) { case 'distribution': orderType = '配送订单'; break; case 'unmanned': orderType = '自提订单'; break; case 'storeBuy': orderType = '直购订单'; break; default: break; } // 找到订单内所有的商品 const orderItems = await OrderItem.findAll({ where: { orderId: order.id } }); // 取出件数 number = orderItems.reduce((total, item) => total + item.number, 0); // 定义文本 text = `手机尾号为${tailNumber.split('').join(' ')}的${orderType}已支付,共计${number}件商品,金额${order.amount / 100}元。`; } else { bindPhone = false; tailNumber = order.id.substr(-4); let orderType = ''; switch (order.type) { case 'distribution': orderType = '配送订单'; break; case 'unmanned': orderType = '自提订单'; break; case 'storeBuy': orderType = '门店订单'; break; default: break; } // 找到订单内所有的商品 const orderItems = await OrderItem.findAll({ where: { orderId: order.id } }); // 取出件数 number = orderItems.reduce((total, item) => total + item.number, 0); // 定义文本 text = `订单尾号为${tailNumber.split('').join(' ')}的${orderType}已支付,共计${number}件商品,金额${order.amount / 100}元。`; } // 定义所传数据 const msg = { id: order.id, number, tailNumber, bindPhone, order, type: order.type, amount: order.amount, soundUrl: `https://tsn.baidu.com/text2audio?lan=zh&ctp=1&cuid=abcdxxx&tok=${token}&tex=${urlencode(text)}&vol=9&spd=5&pit=5`, }; // 获取存储在redis中店铺的键值对 const storeEquipment = await app.redis.get(`${order.storeId}`); // 传输给在线的客户端 await nsp.to(storeEquipment).emit('online', { msg, }); } const coupon = await Coupon.findOne({ where: { orderId: order.id, }, }); if (coupon) await coupon.update({ usedAt: order.createdAt }); const orderItems = await OrderItem.findAll({ where: { orderId: order.id, }, }); for (const iterator of orderItems) { await iterator.update({ status: 'completed' }); const item = await Item.findByPk(iterator.itemCode); await item.update({ stock: item.stock - iterator.number }); } const store = await Store.findByPk(order.storeId); // 记录店铺收入 await Balance.create({ balance: store.balance + order.amount, price: order.amount, add: true, remark: '店铺收入', userId: store.userId, storeId: store.id, orderId: order.id, }); // 记录用户消费 await Balance.create({ balance: user.balance - order.amount, price: order.amount, add: false, remark: '用户消费', userId: order.userId, orderId: order.id, }); await store.update({ balance: store.balance + order.amount, sales: store.balance + order.amount, }); // 找到当前用户 const currentUser = await User.findByPk(order.userId); // 记录购买积分 await Point.create({ point: currentUser.point + order.amount, price: order.amount, add: 'true', remark: '购买商品所得', userId: currentUser.id, orderId: order.id, }); await currentUser.update({ point: currentUser.point + order.amount, balance: currentUser.balance - order.amount, }); if (currentUser.inviterId) { // 找到当前用户的邀请者 const inviterUser = await User.findByPk(currentUser.inviterId); if (inviterUser && inviterUser.role === 'member') { await ctx.service.math.index(inviterUser.id, order.id); } } return true; } else { throw new ForbiddenError('余额不足!'); } }; }
the_stack
import { ExtensionDetailsViewController } from 'background/extension-details-view-controller'; import { BrowserAdapter } from 'common/browser-adapters/browser-adapter'; import { IMock, It, Mock, MockBehavior, Times } from 'typemoq'; import { Tabs } from 'webextension-polyfill-ts'; describe('ExtensionDetailsViewController', () => { let browserAdapterMock: IMock<BrowserAdapter>; let testSubject: ExtensionDetailsViewController; let onTabRemoveCallback: (tabId: number, removeInfo: chrome.tabs.TabRemoveInfo) => void; let onUpdateTabCallback: ( tabId: number, changeInfo: chrome.tabs.TabChangeInfo, tab: chrome.tabs.Tab, ) => void; beforeEach(() => { browserAdapterMock = Mock.ofType<BrowserAdapter>(undefined, MockBehavior.Strict); browserAdapterMock .setup(adapter => adapter.addListenerToTabsOnRemoved(It.isAny())) .callback(callback => { onTabRemoveCallback = callback; }) .verifiable(); browserAdapterMock .setup(adapter => adapter.addListenerToTabsOnUpdated(It.isAny())) .callback(callback => { onUpdateTabCallback = callback; }) .verifiable(); testSubject = new ExtensionDetailsViewController(browserAdapterMock.object); }); describe('showDetailsView', () => { it('creates a details view the first time', async () => { const targetTabId = 12; const detailsViewTabId = 10; setupCreateDetailsView(targetTabId, detailsViewTabId).verifiable(Times.once()); await testSubject.showDetailsView(targetTabId); browserAdapterMock.verifyAll(); }); it('switch to existing tab the second time', async () => { const targetTabId = 5; const detailsViewTabId = 10; setupCreateDetailsView(targetTabId, detailsViewTabId).verifiable(Times.once()); await testSubject.showDetailsView(targetTabId); browserAdapterMock.reset(); setupCreateDetailsViewForAnyUrl(Times.never()); setupSwitchToTab(detailsViewTabId); // call show details second time await testSubject.showDetailsView(targetTabId); browserAdapterMock.verifyAll(); }); it('propagates error from failing browser adapter call to switch to tab', async () => { const targetTabId = 5; const detailsViewTabId = 10; setupCreateDetailsView(targetTabId, detailsViewTabId).verifiable(Times.once()); await testSubject.showDetailsView(targetTabId); browserAdapterMock.reset(); const errorMessage = 'switchToTab failed with dummy error'; browserAdapterMock .setup(adapter => adapter.switchToTab(detailsViewTabId)) .returns(() => Promise.reject(errorMessage)); await expect(testSubject.showDetailsView(targetTabId)).rejects.toEqual(errorMessage); browserAdapterMock.verifyAll(); }); it('propagates error from failing browser adapter call to create tab', async () => { const targetTabId = 5; const errorMessage = 'error creating new window (from browser adapter)'; browserAdapterMock .setup(adapter => adapter.createTabInNewWindow( '/DetailsView/detailsView.html?tabId=' + targetTabId, ), ) .returns(() => Promise.reject(errorMessage)) .verifiable(Times.once()); await expect(testSubject.showDetailsView(targetTabId)).rejects.toEqual(errorMessage); browserAdapterMock.verifyAll(); }); }); test('showDetailsView after target tab updated', async () => { const targetTabId = 5; const detailsViewTabId = 10; setupCreateDetailsView(targetTabId, detailsViewTabId); // call show details once await testSubject.showDetailsView(targetTabId); browserAdapterMock.reset(); // update target tab onUpdateTabCallback(targetTabId, null, null); setupCreateDetailsViewForAnyUrl(Times.never()); setupSwitchToTab(detailsViewTabId); // call show details second time await testSubject.showDetailsView(targetTabId); browserAdapterMock.verifyAll(); }); test('showDetailsView after details tab navigated to another page', async () => { const targetTabId = 5; const detailsViewTabId = 10; const detailsViewRemovedHandlerMock = Mock.ofInstance((tabId: number) => {}); detailsViewRemovedHandlerMock .setup(handler => handler(targetTabId)) .verifiable(Times.once()); testSubject.setupDetailsViewTabRemovedHandler(detailsViewRemovedHandlerMock.object); setupCreateDetailsView(targetTabId, detailsViewTabId); // call show details once await testSubject.showDetailsView(targetTabId); browserAdapterMock.reset(); // update details tab browserAdapterMock .setup(adapter => adapter.getUrl(It.isAny())) .returns(suffix => `browser://mock_ext_id${suffix}`); onUpdateTabCallback( detailsViewTabId, { url: 'www.bing.com/DetailsView/detailsView.html?tabId=' + targetTabId }, null, ); setupCreateDetailsViewForAnyUrl(Times.once()); // call show details second time await testSubject.showDetailsView(targetTabId); browserAdapterMock.verifyAll(); detailsViewRemovedHandlerMock.verifyAll(); }); test('showDetailsView after details tab navigated to different details page', async () => { const targetTabId = 5; const detailsViewTabId = 10; setupCreateDetailsView(targetTabId, detailsViewTabId); // call show details once await testSubject.showDetailsView(targetTabId); browserAdapterMock.reset(); // update details tab browserAdapterMock .setup(adapter => adapter.getUrl(It.isAny())) .returns(suffix => `browser://mock_ext_id${suffix}`); onUpdateTabCallback( detailsViewTabId, { url: 'chromeExt://ext_id/DetailsView/detailsView.html?tabId=90' }, null, ); setupCreateDetailsViewForAnyUrl(Times.once()); // call show details second time await testSubject.showDetailsView(targetTabId); browserAdapterMock.verifyAll(); }); test('showDetailsView after details tab refresh', async () => { const targetTabId = 5; const detailsViewTabId = 10; setupCreateDetailsView(targetTabId, detailsViewTabId); // call show details once await testSubject.showDetailsView(targetTabId); browserAdapterMock.reset(); // update details tab browserAdapterMock .setup(adapter => adapter.getUrl(It.isAny())) .returns(suffix => `browser://mock_ext_id${suffix}`); onUpdateTabCallback( detailsViewTabId, { url: 'browser://MOCK_EXT_ID/detailsView/detailsView.html?tabId=' + targetTabId }, null, ); setupCreateDetailsViewForAnyUrl(Times.never()); setupSwitchToTab(detailsViewTabId); // call show details second time await testSubject.showDetailsView(targetTabId); browserAdapterMock.verifyAll(); }); test('showDetailsView after details tab has # at end', async () => { const targetTabId = 5; const detailsViewTabId = 10; setupCreateDetailsView(targetTabId, detailsViewTabId); // call show details once await testSubject.showDetailsView(targetTabId); browserAdapterMock.reset(); // update details tab browserAdapterMock .setup(adapter => adapter.getUrl(It.isAny())) .returns(suffix => `browser://mock_ext_id${suffix}`); onUpdateTabCallback( detailsViewTabId, { url: 'browser://MOCK_EXT_ID/detailsView/detailsView.html?tabId=' + targetTabId + '#', }, null, ); setupCreateDetailsViewForAnyUrl(Times.never()); setupSwitchToTab(detailsViewTabId); // call show details second time await testSubject.showDetailsView(targetTabId); browserAdapterMock.verifyAll(); }); test('showDetailsView after details tab title update', async () => { const targetTabId = 5; const detailsViewTabId = 10; setupCreateDetailsView(targetTabId, detailsViewTabId); // call show details once await testSubject.showDetailsView(targetTabId); browserAdapterMock.reset(); // update details tab onUpdateTabCallback(detailsViewTabId, { title: 'issues' }, null); setupCreateDetailsViewForAnyUrl(Times.never()); setupSwitchToTab(detailsViewTabId); // call show details second time await testSubject.showDetailsView(targetTabId); browserAdapterMock.verifyAll(); }); test('showDetailsView after random tab updated', async () => { const targetTabId = 5; const detailsViewTabId = 10; setupCreateDetailsView(targetTabId, detailsViewTabId); // call show details once await testSubject.showDetailsView(targetTabId); browserAdapterMock.reset(); // remove details tab onUpdateTabCallback(123, { title: 'issues' }, null); setupCreateDetailsViewForAnyUrl(Times.never()); setupSwitchToTab(detailsViewTabId); // call show details second time await testSubject.showDetailsView(targetTabId); browserAdapterMock.verifyAll(); }); test('showDetailsView after target tab removed', async () => { const targetTabId = 5; const detailsViewTabId = 10; setupCreateDetailsView(targetTabId, detailsViewTabId); // call show details once await testSubject.showDetailsView(targetTabId); browserAdapterMock.reset(); // remove target tab onTabRemoveCallback(targetTabId, null); setupCreateDetailsViewForAnyUrl(Times.once()); // call show details second time await testSubject.showDetailsView(targetTabId); browserAdapterMock.verifyAll(); }); test('showDetailsView after details tab removed', async () => { const targetTabId = 5; const detailsViewTabId = 10; setupCreateDetailsView(targetTabId, detailsViewTabId); const detailsViewRemovedHandlerMock = Mock.ofInstance((tabId: number) => {}); detailsViewRemovedHandlerMock .setup(handler => handler(targetTabId)) .verifiable(Times.once()); testSubject.setupDetailsViewTabRemovedHandler(detailsViewRemovedHandlerMock.object); // call show details once await testSubject.showDetailsView(targetTabId); browserAdapterMock.reset(); // remove details tab onTabRemoveCallback(detailsViewTabId, null); setupCreateDetailsViewForAnyUrl(Times.once()); // call show details second time await testSubject.showDetailsView(targetTabId); browserAdapterMock.verifyAll(); detailsViewRemovedHandlerMock.verifyAll(); }); test('showDetailsView after details tab removed, remove handler not set', async () => { const targetTabId = 5; const detailsViewTabId = 10; setupCreateDetailsView(targetTabId, detailsViewTabId); // call show details once await testSubject.showDetailsView(targetTabId); browserAdapterMock.reset(); // remove details tab onTabRemoveCallback(detailsViewTabId, null); setupCreateDetailsViewForAnyUrl(Times.once()); // call show details second time await testSubject.showDetailsView(targetTabId); browserAdapterMock.verifyAll(); }); test('showDetailsView after random tab removed', async () => { const targetTabId = 5; const detailsViewTabId = 10; setupCreateDetailsView(targetTabId, detailsViewTabId); // call show details once await testSubject.showDetailsView(targetTabId); browserAdapterMock.reset(); // remove details tab onTabRemoveCallback(100, null); setupCreateDetailsViewForAnyUrl(Times.never()); setupSwitchToTab(detailsViewTabId); // call show details second time await testSubject.showDetailsView(targetTabId); browserAdapterMock.verifyAll(); }); const setupSwitchToTab = (tabId: number) => { return browserAdapterMock .setup(adapter => adapter.switchToTab(tabId)) .returns(() => Promise.resolve()); }; const setupCreateDetailsView = (targetTabId: number, resultingDetailsViewTabId: number) => { return browserAdapterMock .setup(adapter => adapter.createTabInNewWindow('/DetailsView/detailsView.html?tabId=' + targetTabId), ) .returns(() => Promise.resolve({ id: resultingDetailsViewTabId } as Tabs.Tab)); }; const setupCreateDetailsViewForAnyUrl = (times: Times) => { browserAdapterMock .setup(adapter => adapter.createTabInNewWindow(It.isAny())) .returns(() => Promise.resolve({ id: -1 } as Tabs.Tab)) .verifiable(times); }; });
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/authorizationsMappers"; import * as Parameters from "../models/parameters"; import { AvsClientContext } from "../avsClientContext"; /** Class representing a Authorizations. */ export class Authorizations { private readonly client: AvsClientContext; /** * Create a Authorizations. * @param {AvsClientContext} client Reference to the service client. */ constructor(client: AvsClientContext) { this.client = client; } /** * @summary List ExpressRoute Circuit Authorizations in a private cloud * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param privateCloudName Name of the private cloud * @param [options] The optional parameters * @returns Promise<Models.AuthorizationsListResponse> */ list(resourceGroupName: string, privateCloudName: string, options?: msRest.RequestOptionsBase): Promise<Models.AuthorizationsListResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param privateCloudName Name of the private cloud * @param callback The callback */ list(resourceGroupName: string, privateCloudName: string, callback: msRest.ServiceCallback<Models.ExpressRouteAuthorizationList>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param privateCloudName Name of the private cloud * @param options The optional parameters * @param callback The callback */ list(resourceGroupName: string, privateCloudName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ExpressRouteAuthorizationList>): void; list(resourceGroupName: string, privateCloudName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ExpressRouteAuthorizationList>, callback?: msRest.ServiceCallback<Models.ExpressRouteAuthorizationList>): Promise<Models.AuthorizationsListResponse> { return this.client.sendOperationRequest( { resourceGroupName, privateCloudName, options }, listOperationSpec, callback) as Promise<Models.AuthorizationsListResponse>; } /** * @summary Get an ExpressRoute Circuit Authorization by name in a private cloud * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param privateCloudName Name of the private cloud * @param authorizationName Name of the ExpressRoute Circuit Authorization in the private cloud * @param [options] The optional parameters * @returns Promise<Models.AuthorizationsGetResponse> */ get(resourceGroupName: string, privateCloudName: string, authorizationName: string, options?: msRest.RequestOptionsBase): Promise<Models.AuthorizationsGetResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param privateCloudName Name of the private cloud * @param authorizationName Name of the ExpressRoute Circuit Authorization in the private cloud * @param callback The callback */ get(resourceGroupName: string, privateCloudName: string, authorizationName: string, callback: msRest.ServiceCallback<Models.ExpressRouteAuthorization>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param privateCloudName Name of the private cloud * @param authorizationName Name of the ExpressRoute Circuit Authorization in the private cloud * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, privateCloudName: string, authorizationName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ExpressRouteAuthorization>): void; get(resourceGroupName: string, privateCloudName: string, authorizationName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ExpressRouteAuthorization>, callback?: msRest.ServiceCallback<Models.ExpressRouteAuthorization>): Promise<Models.AuthorizationsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, privateCloudName, authorizationName, options }, getOperationSpec, callback) as Promise<Models.AuthorizationsGetResponse>; } /** * @summary Create or update an ExpressRoute Circuit Authorization in a private cloud * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param privateCloudName The name of the private cloud. * @param authorizationName Name of the ExpressRoute Circuit Authorization in the private cloud * @param authorization An ExpressRoute Circuit Authorization * @param [options] The optional parameters * @returns Promise<Models.AuthorizationsCreateOrUpdateResponse> */ createOrUpdate(resourceGroupName: string, privateCloudName: string, authorizationName: string, authorization: any, options?: msRest.RequestOptionsBase): Promise<Models.AuthorizationsCreateOrUpdateResponse> { return this.beginCreateOrUpdate(resourceGroupName,privateCloudName,authorizationName,authorization,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.AuthorizationsCreateOrUpdateResponse>; } /** * @summary Delete an ExpressRoute Circuit Authorization in a private cloud * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param privateCloudName Name of the private cloud * @param authorizationName Name of the ExpressRoute Circuit Authorization in the private cloud * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(resourceGroupName: string, privateCloudName: string, authorizationName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDeleteMethod(resourceGroupName,privateCloudName,authorizationName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * @summary Create or update an ExpressRoute Circuit Authorization in a private cloud * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param privateCloudName The name of the private cloud. * @param authorizationName Name of the ExpressRoute Circuit Authorization in the private cloud * @param authorization An ExpressRoute Circuit Authorization * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdate(resourceGroupName: string, privateCloudName: string, authorizationName: string, authorization: any, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, privateCloudName, authorizationName, authorization, options }, beginCreateOrUpdateOperationSpec, options); } /** * @summary Delete an ExpressRoute Circuit Authorization in a private cloud * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param privateCloudName Name of the private cloud * @param authorizationName Name of the ExpressRoute Circuit Authorization in the private cloud * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(resourceGroupName: string, privateCloudName: string, authorizationName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, privateCloudName, authorizationName, options }, beginDeleteMethodOperationSpec, options); } /** * @summary List ExpressRoute Circuit Authorizations in a private cloud * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.AuthorizationsListNextResponse> */ listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.AuthorizationsListNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ExpressRouteAuthorizationList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ExpressRouteAuthorizationList>): void; listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ExpressRouteAuthorizationList>, callback?: msRest.ServiceCallback<Models.ExpressRouteAuthorizationList>): Promise<Models.AuthorizationsListNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listNextOperationSpec, callback) as Promise<Models.AuthorizationsListNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/authorizations", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.privateCloudName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ExpressRouteAuthorizationList }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/authorizations/{authorizationName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.privateCloudName, Parameters.authorizationName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ExpressRouteAuthorization }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/authorizations/{authorizationName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.privateCloudName, Parameters.authorizationName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "authorization", mapper: { required: true, serializedName: "authorization", type: { name: "Object" } } }, responses: { 200: { bodyMapper: Mappers.ExpressRouteAuthorization }, 201: { bodyMapper: Mappers.ExpressRouteAuthorization }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/authorizations/{authorizationName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.privateCloudName, Parameters.authorizationName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ExpressRouteAuthorizationList }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import { INodeProperties, } from 'n8n-workflow'; export const chargeOperations: INodeProperties[] = [ { displayName: 'Operation', name: 'operation', type: 'options', default: 'get', description: 'Operation to perform', options: [ { name: 'Create', value: 'create', description: 'Create a charge', }, { name: 'Get', value: 'get', description: 'Get a charge', }, { name: 'Get All', value: 'getAll', description: 'Get all charges', }, { name: 'Update', value: 'update', description: 'Update a charge', }, ], displayOptions: { show: { resource: [ 'charge', ], }, }, }, ]; export const chargeFields: INodeProperties[] = [ // ---------------------------------- // charge: create // ---------------------------------- { displayName: 'Customer ID', name: 'customerId', type: 'string', required: true, default: '', description: 'ID of the customer to be associated with this charge', displayOptions: { show: { resource: [ 'charge', ], operation: [ 'create', ], }, }, }, { displayName: 'Amount', name: 'amount', type: 'number', required: true, default: 0, description: 'Amount in cents to be collected for this charge, e.g. enter <code>100</code> for $1.00', typeOptions: { minValue: 0, maxValue: 99999999, }, displayOptions: { show: { resource: [ 'charge', ], operation: [ 'create', ], }, }, }, { displayName: 'Currency', name: 'currency', type: 'options', typeOptions: { loadOptionsMethod: 'getCurrencies', }, required: true, default: '', description: 'Three-letter ISO currency code, e.g. <code>USD</code> or <code>EUR</code>. It must be a <a href="https://stripe.com/docs/currencies">Stripe-supported currency</a>', displayOptions: { show: { resource: [ 'charge', ], operation: [ 'create', ], }, }, }, { displayName: 'Source ID', name: 'source', type: 'string', required: true, default: '', description: 'ID of the customer\'s payment source to be charged', displayOptions: { show: { resource: [ 'charge', ], operation: [ 'create', ], }, }, }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'charge', ], operation: [ 'create', ], }, }, options: [ { displayName: 'Description', name: 'description', type: 'string', default: '', description: 'Arbitrary text to describe the charge to create', }, { displayName: 'Metadata', name: 'metadata', type: 'fixedCollection', default: [], placeholder: 'Add Metadata Item', description: 'Set of key-value pairs to attach to the charge to create', typeOptions: { multipleValues: true, }, options: [ { displayName: 'Metadata Properties', name: 'metadataProperties', values: [ { displayName: 'Key', name: 'key', type: 'string', default: '', }, { displayName: 'Value', name: 'value', type: 'string', default: '', }, ], }, ], }, { displayName: 'Receipt Email', name: 'receipt_email', type: 'string', default: '', description: 'Email address to which the receipt for this charge will be sent', }, { displayName: 'Shipping', name: 'shipping', type: 'fixedCollection', description: 'Shipping information for the charge', placeholder: 'Add Field', typeOptions: { multipleValues: true, }, default: [], options: [ { displayName: 'Shipping Properties', name: 'shippingProperties', values: [ { displayName: 'Recipient Name', name: 'name', type: 'string', description: 'Name of the person who will receive the shipment', default: '', }, { displayName: 'Address', name: 'address', type: 'fixedCollection', default: {}, placeholder: 'Add Field', options: [ { displayName: 'Details', name: 'details', values: [ { displayName: 'Line 1', name: 'line1', description: 'Address line 1 (e.g. street, PO Box, or company name)', type: 'string', default: '', }, { displayName: 'Line 2', name: 'line2', description: 'Address line 2 (e.g. apartment, suite, unit, or building)', type: 'string', default: '', }, { displayName: 'City', name: 'city', description: 'City, district, suburb, town, or village', type: 'string', default: '', }, { displayName: 'State', name: 'state', description: 'State, county, province, or region', type: 'string', default: '', }, { displayName: 'Country', name: 'country', description: 'Two-letter country code (<a href="https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2">ISO 3166-1 alpha-2</a>)', type: 'string', default: '', }, { displayName: 'Postal Code', name: 'postal_code', description: 'ZIP or postal code', type: 'string', default: '', }, ], }, ], }, ], }, ], }, ], }, // ---------------------------------- // charge: get // ---------------------------------- { displayName: 'Charge ID', name: 'chargeId', type: 'string', required: true, default: '', description: 'ID of the charge to retrieve.', displayOptions: { show: { resource: [ 'charge', ], operation: [ 'get', ], }, }, }, // ---------------------------------- // charge: getAll // ---------------------------------- { displayName: 'Return All', name: 'returnAll', type: 'boolean', default: false, description: 'Whether to return all results or only up to a given limit', displayOptions: { show: { resource: [ 'charge', ], operation: [ 'getAll', ], }, }, }, { displayName: 'Limit', name: 'limit', type: 'number', default: 50, description: 'How many results to return', typeOptions: { minValue: 1, maxValue: 1000, }, displayOptions: { show: { resource: [ 'charge', ], operation: [ 'getAll', ], returnAll: [ false, ], }, }, }, // ---------------------------------- // charge: update // ---------------------------------- { displayName: 'Charge ID', name: 'chargeId', type: 'string', required: true, default: '', description: 'ID of the charge to update', displayOptions: { show: { resource: [ 'charge', ], operation: [ 'update', ], }, }, }, { displayName: 'Update Fields', name: 'updateFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'charge', ], operation: [ 'update', ], }, }, options: [ { displayName: 'Description', name: 'description', type: 'string', default: '', description: 'Arbitrary text to describe the charge to update', }, { displayName: 'Metadata', name: 'metadata', type: 'fixedCollection', default: {}, placeholder: 'Add Metadata Item', description: 'Set of key-value pairs to attach to the charge to update', typeOptions: { multipleValues: true, }, options: [ { displayName: 'Metadata Properties', name: 'metadataProperties', values: [ { displayName: 'Key', name: 'key', type: 'string', default: '', }, { displayName: 'Value', name: 'value', type: 'string', default: '', }, ], }, ], }, { displayName: 'Receipt Email', name: 'receipt_email', type: 'string', default: '', description: 'The email address to which the receipt for this charge will be sent', }, { displayName: 'Shipping', name: 'shipping', type: 'fixedCollection', default: {}, description: 'Shipping information for the charge', placeholder: 'Add Field', typeOptions: { multipleValues: true, }, options: [ { displayName: 'Shipping Properties', name: 'shippingProperties', default: {}, values: [ { displayName: 'Recipient Name', name: 'name', type: 'string', default: '', }, { displayName: 'Recipient Address', name: 'address', type: 'fixedCollection', default: {}, placeholder: 'Add Address Details', options: [ { displayName: 'Details', name: 'details', values: [ { displayName: 'Line 1', name: 'line1', description: 'Address line 1 (e.g. street, PO Box, or company name)', type: 'string', default: '', }, { displayName: 'Line 2', name: 'line2', description: 'Address line 2 (e.g. apartment, suite, unit, or building)', type: 'string', default: '', }, { displayName: 'City', name: 'city', description: 'City, district, suburb, town, or village', type: 'string', default: '', }, { displayName: 'State', name: 'state', description: 'State, county, province, or region', type: 'string', default: '', }, { displayName: 'Country', name: 'country', description: 'Two-letter country code (<a href="https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2">ISO 3166-1 alpha-2</a>)', type: 'string', default: '', }, { displayName: 'Postal Code', name: 'postal_code', description: 'ZIP or postal code', type: 'string', default: '', }, ], }, ], }, ], }, ], }, ], }, ];
the_stack
import * as RTE from "fp-ts/lib/ReaderTaskEither"; import * as E from "fp-ts/lib/Either"; import { flow, pipe } from "fp-ts/lib/function"; import { randomUUID } from "crypto"; import sanitizeHtml from "sanitize-html"; import showdown from "showdown"; import * as db from "./notes-db"; import * as noteImport from "./note-import"; import type { SocketSessionRecord } from "./socket-session-store"; import * as AsyncIterator from "./util/async-iterator"; import { invalidateResources } from "./live-query-store"; import * as auth from "./auth"; export type NoteModelType = db.NoteModelType; export const decodeNote = db.decodeNote; export const NoteModel = db.NoteModel; export type NoteSearchMatchType = db.NoteSearchMatchType; const sanitizeNoteContent = (content: string) => { const [, ...contentLines] = content.split("\n"); const converter = new showdown.Converter({ tables: true, }); const sanitizedContent = sanitizeHtml( converter.makeHtml(contentLines.join("\n")), { allowedTags: [], } ); return sanitizedContent; }; export const getNoteById = (id: string) => pipe( auth.requireAuth(), RTE.rightReaderTask, RTE.chainW(() => db.getNoteById(id)), RTE.chainW((note) => { switch (note.type) { case "admin": return pipe( auth.requireAdmin(), RTE.rightReaderTask, RTE.map(() => note) ); case "public": return RTE.right(note); default: return RTE.left(new Error("Insufficient permissions.")); } }) ); export const getPaginatedNotes = ({ first, onlyEntryPoints, cursor, }: { /* amount of items to fetch */ first: number; /* whether only public notes should be returned */ /* whether only entrypoints should be returned */ onlyEntryPoints: boolean; /* cursor which can be used to fetch more */ cursor: null | { /* createdAt date of the item after which items should be fetched */ lastCreatedAt: number; /* id of the item after which items should be fetched */ lastId: string; }; }) => pipe( auth.requireAuth(), RTE.rightReaderTask, RTE.chainW(() => RTE.ask<{ session: SocketSessionRecord }>()), RTE.chainW(({ session }) => db.getPaginatedNotes({ first, onlyPublic: session.role === "user", onlyEntryPoints, cursor, }) ) ); export const createNote = ({ title, content, isEntryPoint, }: { title: string; content: string; isEntryPoint: boolean; }) => pipe( auth.requireAdmin(), RTE.rightReaderTask, RTE.chainW(() => db.updateOrInsertNote({ id: randomUUID(), title, content, access: "admin", sanitizedContent: sanitizeNoteContent(content), isEntryPoint, }) ), RTE.chain(getNoteById), RTE.chainW((note) => pipe( publishNotesUpdate({ type: "NOTE_CREATED", noteId: note.id, createdAt: note.createdAt, isEntryPoint: note.isEntryPoint, access: note.type, }), RTE.map(() => note) ) ) ); export const updateNoteContent = ({ id, content, }: { id: string; content: string; }) => pipe( auth.requireAdmin(), RTE.rightReaderTask, RTE.chainW(() => db.getNoteById(id)), RTE.chainW((note) => db.updateOrInsertNote({ id, title: note.title, content, access: note.type, sanitizedContent: sanitizeNoteContent(content), isEntryPoint: note.isEntryPoint, }) ) ); export const updateNoteAccess = ({ id, access, }: { id: string; access: string; }) => pipe( auth.requireAdmin(), RTE.rightReaderTask, RTE.chainW(() => pipe(db.NoteAccessTypeModel.decode(access), RTE.fromEither) ), RTE.chainW((access) => pipe( db.getNoteById(id), RTE.chainW((note) => pipe( db.updateOrInsertNote({ id, title: note.title, content: note.content, access: access, sanitizedContent: sanitizeNoteContent(note.content), isEntryPoint: note.isEntryPoint, }), RTE.chainW((noteId) => pipe( note.type !== access ? pipe( publishNotesUpdate({ type: "NOTE_CHANGE_ACCESS", noteId, createdAt: note.createdAt, access, isEntryPoint: note.isEntryPoint, }), RTE.chainW(() => invalidateResources([`Note:${note.id}`])) ) : RTE.right(undefined), RTE.map(() => noteId) ) ) ) ) ) ) ); const publishNotesUpdate = (payload: NotesUpdatesPayload) => pipe( RTE.ask<NotesUpdatesDependency>(), RTE.chainW((deps) => pipe( E.tryCatch(() => deps.notesUpdates.publish(payload), E.toError), RTE.fromEither ) ) ); export const updateNoteIsEntryPoint = ({ id, isEntryPoint, }: { id: string; isEntryPoint: boolean; }) => pipe( auth.requireAdmin(), RTE.rightReaderTask, RTE.chainW(() => pipe( db.getNoteById(id), RTE.chainW((note) => pipe( db.updateOrInsertNote({ id, title: note.title, content: note.content, access: note.type, sanitizedContent: sanitizeNoteContent(note.content), isEntryPoint, }), RTE.chainW((noteId) => pipe( isEntryPoint !== note.isEntryPoint ? publishNotesUpdate({ type: "NOTE_CHANGE_ENTRY_POINT", noteId, createdAt: note.createdAt, access: note.type, isEntryPoint: isEntryPoint, }) : RTE.right(undefined), RTE.map(() => noteId) ) ) ) ) ) ) ); export const updateNoteTitle = ({ id, title }: { id: string; title: string }) => pipe( auth.requireAdmin(), RTE.rightReaderTask, RTE.chainW(() => db.getNoteById(id)), RTE.chainW((note) => pipe( db.updateOrInsertNote({ id, title, content: note.content, access: note.type, sanitizedContent: sanitizeNoteContent(note.content), isEntryPoint: note.isEntryPoint, }), RTE.chainW((noteId) => pipe( title !== note.title ? publishNotesUpdate({ type: "NOTE_CHANGE_TITLE", noteId, createdAt: note.createdAt, access: note.type, isEntryPoint: note.isEntryPoint, }) : RTE.right(undefined), RTE.map(() => noteId) ) ) ) ) ); export const deleteNote = (noteId: string) => pipe( auth.requireAdmin(), RTE.rightReaderTask, RTE.chainW(() => db.getNoteById(noteId)), RTE.chainW((note) => pipe( publishNotesUpdate({ type: "NOTE_DELETED", noteId: note.id, createdAt: note.createdAt, isEntryPoint: note.isEntryPoint, access: note.type, }), RTE.chainW(() => db.deleteNote(note.id)) ) ) ); export const findPublicNotes = (query: string) => pipe( auth.requireAuth(), RTE.rightReaderTask, RTE.chainW(() => RTE.ask<auth.SessionDependency>()), RTE.chainW((d) => db.searchNotes(query, d.session.role === "user")) ); export const importNote = flow( noteImport.parseNoteData, RTE.fromEither, RTE.chainW((d) => db.updateOrInsertNote({ ...d, access: "public", isEntryPoint: d.isEntryPoint, }) ) ); interface NotesChangedAccessPayload { type: "NOTE_CHANGE_ACCESS"; noteId: string; createdAt: number; access: "admin" | "public"; isEntryPoint: boolean; } interface NotesChangedIsEntryPointPayload { type: "NOTE_CHANGE_ENTRY_POINT"; noteId: string; createdAt: number; isEntryPoint: boolean; access: "admin" | "public"; } interface NotesChangedTitlePayload { type: "NOTE_CHANGE_TITLE"; noteId: string; createdAt: number; isEntryPoint: boolean; access: "admin" | "public"; } interface NotesDeletedNotePayload { type: "NOTE_DELETED"; noteId: string; createdAt: number; isEntryPoint: boolean; access: "admin" | "public"; } interface NotesCreatedNotePayload { type: "NOTE_CREATED"; noteId: string; createdAt: number; isEntryPoint: boolean; access: "admin" | "public"; } export type NotesUpdatesPayload = | NotesChangedAccessPayload | NotesChangedIsEntryPointPayload | NotesChangedTitlePayload | NotesDeletedNotePayload | NotesCreatedNotePayload; export interface NotesUpdates { subscribe: () => AsyncIterableIterator<NotesUpdatesPayload>; publish: (payload: NotesUpdatesPayload) => void; } interface NotesUpdatesDependency { notesUpdates: NotesUpdates; } interface NoteCursor { lastId: string; lastCreatedAt: number; } /** * Whether the cursor a is located after cursor b */ export const isAfterCursor = (a: NoteCursor, b: null | NoteCursor) => { if (b === null) { return false; } if (a.lastCreatedAt === b.lastCreatedAt) { return a.lastId > b.lastId; } if (a.lastCreatedAt > b.lastCreatedAt) { return false; } return true; }; export const subscribeToNotesUpdates = (params: { mode: "all" | "entrypoint"; cursor: null | { lastId: string; lastCreatedAt: number; }; hasNextPage: boolean; }) => pipe( auth.requireAuth(), RTE.rightReaderTask, RTE.chainW(() => RTE.ask<NotesUpdatesDependency & auth.SessionDependency>() ), RTE.map((deps) => pipe( deps.notesUpdates.subscribe(), // skip all events that are after our last cursor // as those notes are not relevant for the client AsyncIterator.filter( (payload) => !isAfterCursor( { lastId: payload.noteId, lastCreatedAt: payload.createdAt, }, params.cursor ) || !params.hasNextPage ), AsyncIterator.map((payload) => { const hasAccess = (payload.access === "admin" && deps.session.role === "admin") || payload.access === "public"; switch (payload.type) { case "NOTE_CHANGE_ACCESS": { if ( (params.mode === "entrypoint" && payload.isEntryPoint === false) || deps.session.role === "admin" ) { return { addedNodeId: null, updatedNoteId: null, removedNoteId: null, mode: params.mode, }; } // deps.session.role === "user" return { addedNodeId: payload.access === "public" ? payload.noteId : null, updatedNoteId: null, removedNoteId: payload.access === "admin" ? payload.noteId : null, mode: params.mode, }; } case "NOTE_CHANGE_ENTRY_POINT": { if (params.mode === "all") { return { addedNodeId: null, updatedNoteId: null, removedNoteId: null, mode: params.mode, }; } return { addedNodeId: hasAccess && payload.isEntryPoint ? payload.noteId : null, updatedNoteId: null, removedNoteId: hasAccess && !payload.isEntryPoint ? payload.noteId : null, mode: params.mode, }; } case "NOTE_CHANGE_TITLE": { if ( params.mode === "entrypoint" && payload.isEntryPoint === false ) { return { addedNodeId: null, updatedNoteId: null, removedNoteId: null, mode: params.mode, }; } return { addedNodeId: null, updatedNoteId: hasAccess ? payload.noteId : null, removedNoteId: null, mode: params.mode, }; } case "NOTE_CREATED": { if ( params.mode === "entrypoint" && payload.isEntryPoint === false ) { return { addedNodeId: null, updatedNoteId: null, removedNoteId: null, mode: params.mode, }; } return { addedNodeId: hasAccess ? payload.noteId : null, updatedNoteId: null, removedNoteId: null, mode: params.mode, }; } case "NOTE_DELETED": { if ( params.mode === "entrypoint" && payload.isEntryPoint === false ) { return { addedNodeId: null, updatedNoteId: null, removedNoteId: null, mode: params.mode, }; } return { addedNodeId: null, updatedNoteId: null, removedNoteId: hasAccess ? payload.noteId : null, mode: params.mode, }; } } }), // micro optimization for not sending empty payloads where every field is null to the client. AsyncIterator.filter( (value): value is typeof value => value.addedNodeId !== null || value.removedNoteId !== null || value.updatedNoteId !== null ) ) ) );
the_stack
import {TextureAllocation, TextureAllocationData} from './TextureAllocation'; import {BaseGlNodeType} from '../../_Base'; // import {TypedConnection, COMPONENTS_COUNT_BY_TYPE} from '../../../../../Engine/Node/Gl/GlData'; import {TextureVariable} from './TextureVariable'; import {ShaderConfig} from '../configs/ShaderConfig'; import {ShaderName} from '../../../utils/shaders/ShaderName'; import {PolyScene} from '../../../../scene/PolyScene'; import {GlConnectionPointComponentsCountMap, BaseGlConnectionPoint} from '../../../utils/io/connections/Gl'; import {AttributeGlNode} from '../../Attribute'; import {GlobalsGlNode} from '../../Globals'; import {OutputGlNode} from '../../Output'; import {ArrayUtils} from '../../../../../core/ArrayUtils'; import {PolyDictionary} from '../../../../../types/GlobalTypes'; import {MapUtils} from '../../../../../core/MapUtils'; export type TextureAllocationsControllerData = { writable: PolyDictionary<TextureAllocationData>[]; readonly: PolyDictionary<TextureAllocationData>[]; }; const OUTPUT_NAME_ATTRIBUTES = ['position', 'normal', 'color', 'uv']; export class TextureAllocationsController { private _writableAllocations: TextureAllocation[] = []; private _readonlyAllocations: TextureAllocation[] = []; // private _next_allocation_index: number = 0; constructor() {} private static _sortNodes(root_nodes: BaseGlNodeType[]): BaseGlNodeType[] { //let's go through the output node first, in case there is a name conflict, it will have priority const outputNodes = root_nodes.filter((node) => node.type() == OutputGlNode.type()); const sortedRootNodes: BaseGlNodeType[] = outputNodes; // we also sort them by name, to add some predictability to the generated shaders const nonOutputNodes = root_nodes.filter((node) => node.type() != OutputGlNode.type()); const nonOutputNodeNames = nonOutputNodes.map((n) => n.name()).sort(); const nonOutputNodesByName: Map<string, BaseGlNodeType> = new Map(); for (let node of nonOutputNodes) { nonOutputNodesByName.set(node.name(), node); } for (let nodeName of nonOutputNodeNames) { const node = nonOutputNodesByName.get(nodeName); if (node) { sortedRootNodes.push(node); } } return sortedRootNodes; } allocateConnectionsFromRootNodes(root_nodes: BaseGlNodeType[], leaf_nodes: BaseGlNodeType[]) { const variables = []; root_nodes = TextureAllocationsController._sortNodes(root_nodes); leaf_nodes = TextureAllocationsController._sortNodes(leaf_nodes); for (let node of root_nodes) { const node_id = node.graphNodeId(); switch (node.type()) { case OutputGlNode.type(): { for (let connection_point of node.io.inputs.namedInputConnectionPoints()) { const input = node.io.inputs.named_input(connection_point.name()); if (input) { // connections_by_node_id[node_id] = connections_by_node_id[node_id] || [] // connections_by_node_id[node_id].push(named_input) const variable = new TextureVariable( connection_point.name(), GlConnectionPointComponentsCountMap[connection_point.type()] ); variable.addGraphNodeId(node_id); variables.push(variable); } } break; } case AttributeGlNode.type(): { const attrib_node = node as AttributeGlNode; const named_input: BaseGlNodeType | null = attrib_node.connected_input_node(); const connection_point: | BaseGlConnectionPoint | undefined = attrib_node.connected_input_connection_point(); if (named_input && connection_point) { // connections_by_node_id[node_id] = connections_by_node_id[node_id] || [] // connections_by_node_id[node_id].push(named_input) const variable = new TextureVariable( attrib_node.attribute_name, GlConnectionPointComponentsCountMap[connection_point.type()] ); variable.addGraphNodeId(node_id); variables.push(variable); } break; } } } for (let node of leaf_nodes) { const node_id = node.graphNodeId(); switch (node.type()) { case GlobalsGlNode.type(): { const globals_node = node as GlobalsGlNode; // const output_names_not_attributes = ['frame', 'gl_FragCoord', 'gl_PointCoord']; for (let output_name of globals_node.io.outputs.used_output_names()) { // is_attribute, as opposed to frame, gl_FragCoord and gl_PointCoord which are either uniforms or provided by the renderer const is_attribute = OUTPUT_NAME_ATTRIBUTES.includes(output_name); if (is_attribute) { const connection_point = globals_node.io.outputs.namedOutputConnectionPointsByName( output_name ); if (connection_point) { const gl_type = connection_point.type(); const variable = new TextureVariable( output_name, GlConnectionPointComponentsCountMap[gl_type] ); variable.addGraphNodeId(node_id); variables.push(variable); } } } break; } case AttributeGlNode.type(): { const attribute_node = node as AttributeGlNode; const connection_point = attribute_node.output_connection_point(); if (connection_point) { // connections_by_node_id[node_id] = connections_by_node_id[node_id] || [] // connections_by_node_id[node_id].push(named_output) const variable = new TextureVariable( attribute_node.attribute_name, GlConnectionPointComponentsCountMap[connection_point.type()] ); if (!attribute_node.isExporting()) { variable.setReadonly(true); } variable.addGraphNodeId(node_id); variables.push(variable); } break; } } } this._allocateVariables(variables); } private _allocateVariables(variables: TextureVariable[]) { const variables_by_size_inverse = ArrayUtils.sortBy(variables, (variable) => { return -variable.size(); }); const uniqVariables = this._ensureVariablesAreUnique(variables_by_size_inverse); for (let variable of uniqVariables) { if (variable.readonly()) { this._allocateVariable(variable, this._readonlyAllocations); } else { this._allocateVariable(variable, this._writableAllocations); } } } private _ensureVariablesAreUnique(variables: TextureVariable[]) { const variableByName: Map<string, TextureVariable[]> = new Map(); for (let variable of variables) { MapUtils.pushOnArrayAtEntry(variableByName, variable.name(), variable); } const uniqVariables: TextureVariable[] = []; variableByName.forEach((variablesForName, variableName) => { const firstVariable = variablesForName[0]; uniqVariables.push(firstVariable); for (let i = 1; i < variablesForName.length; i++) { const otherVariable = variablesForName[i]; firstVariable.merge(otherVariable); } }); return uniqVariables; } private _allocateVariable(new_variable: TextureVariable, allocations: TextureAllocation[]) { let isAllocated = this.hasVariable(new_variable.name()); if (isAllocated) { throw 'no variable should be allocated since they have been made unique before'; // const allocated_variable = this.variables().filter((v) => v.name() == new_variable.name())[0]; // allocated_variable.merge(new_variable); } else { if (!isAllocated) { for (let allocation of allocations) { if (!isAllocated && allocation.hasSpaceForVariable(new_variable)) { allocation.addVariable(new_variable); isAllocated = true; } } } if (!isAllocated) { const new_allocation = new TextureAllocation(/*this.nextAllocationName()*/); allocations.push(new_allocation); new_allocation.addVariable(new_variable); } } } private _addWritableAllocation(allocation: TextureAllocation) { this._writableAllocations.push(allocation); } private _addReadonlyAllocation(allocation: TextureAllocation) { this._readonlyAllocations.push(allocation); } readonlyAllocations() { return this._readonlyAllocations; } // private _nextAllocationName(): ShaderName { // const name = ParticleShaderNames[this._next_allocation_index]; // this._next_allocation_index += 1; // return name; // } shaderNames(): ShaderName[] { const explicit_shader_names = this._writableAllocations.map((a) => a.shaderName()); // include dependencies if needed // TODO: typescript - do I need those? // if (lodash_includes(explicit_shader_names, 'acceleration')) { // explicit_shader_names.push('velocity'); // } // if (lodash_includes(explicit_shader_names, 'velocity')) { // explicit_shader_names.push('position'); // } return ArrayUtils.uniq(explicit_shader_names); } createShaderConfigs(): ShaderConfig[] { return [ // new ShaderConfig('position', ['position'], []), // new ShaderConfig('fragment', ['color', 'alpha'], ['vertex']), ]; } allocationForShaderName(shader_name: ShaderName): TextureAllocation | undefined { const writeableAllocation = this._writableAllocations.filter((a) => a.shaderName() == shader_name)[0]; if (writeableAllocation) { return writeableAllocation; } return this._readonlyAllocations.filter((a) => a.shaderName() == shader_name)[0]; } inputNamesForShaderName(root_node: BaseGlNodeType, shader_name: ShaderName) { const allocation = this.allocationForShaderName(shader_name); if (allocation) { return allocation.inputNamesForNode(root_node); } } // find_variable(root_node: BaseNodeGl, shader_name: ShaderName, input_name: string): TextureVariable{ // const allocation = this.allocation_for_shader_name(shader_name) // if(allocation){ // return allocation.find_variable_with_node(root_node, input_name) // } // } variable(variable_name: string): TextureVariable | undefined { for (let allocation of this._writableAllocations) { const variable = allocation.variable(variable_name); if (variable) { return variable; } } for (let allocation of this._readonlyAllocations) { const variable = allocation.variable(variable_name); if (variable) { return variable; } } } variables(): TextureVariable[] { const writableVariables = this._writableAllocations.map((a) => a.variables() || []).flat(); const readonlyVariables = this._writableAllocations.map((a) => a.variables() || []).flat(); return writableVariables.concat(readonlyVariables); } hasVariable(name: string): boolean { const names = this.variables().map((v) => v.name()); return names.includes(name); } static fromJSON(data: TextureAllocationsControllerData): TextureAllocationsController { const controller = new TextureAllocationsController(); for (let datum of data.writable) { const shader_name = Object.keys(datum)[0] as ShaderName; const allocation_data = datum[shader_name]; const new_allocation = TextureAllocation.fromJSON(allocation_data); controller._addWritableAllocation(new_allocation); } for (let datum of data.readonly) { const shader_name = Object.keys(datum)[0] as ShaderName; const allocation_data = datum[shader_name]; const new_allocation = TextureAllocation.fromJSON(allocation_data); controller._addReadonlyAllocation(new_allocation); } return controller; } toJSON(scene: PolyScene): TextureAllocationsControllerData { const writable = this._writableAllocations.map((allocation: TextureAllocation) => { const data = { [allocation.shaderName()]: allocation.toJSON(scene), }; return data; }); const readonly = this._readonlyAllocations.map((allocation: TextureAllocation) => { const data = { [allocation.shaderName()]: allocation.toJSON(scene), }; return data; }); return {writable, readonly}; } print(scene: PolyScene) { console.warn(JSON.stringify(this.toJSON(scene), [''], 2)); } }
the_stack
import * as pathHelper from '../src/internal-path-helper' const IS_WINDOWS = process.platform === 'win32' describe('path-helper', () => { it('dirname interprets directory name from paths', () => { assertDirectoryName('', '.') assertDirectoryName('.', '.') assertDirectoryName('..', '.') assertDirectoryName('hello', '.') assertDirectoryName('hello/', '.') assertDirectoryName('hello/world', 'hello') if (IS_WINDOWS) { // Removes redundant slashes assertDirectoryName('C:\\\\hello\\\\\\world\\\\', 'C:\\hello') assertDirectoryName('C://hello///world//', 'C:\\hello') // Relative root: assertDirectoryName('\\hello\\\\world\\\\again\\\\', '\\hello\\world') assertDirectoryName('/hello///world//again//', '\\hello\\world') // UNC: assertDirectoryName('\\\\hello\\world\\again\\', '\\\\hello\\world') assertDirectoryName( '\\\\hello\\\\\\world\\\\again\\\\', '\\\\hello\\world' ) assertDirectoryName( '\\\\\\hello\\\\\\world\\\\again\\\\', '\\\\hello\\world' ) assertDirectoryName( '\\\\\\\\hello\\\\\\world\\\\again\\\\', '\\\\hello\\world' ) assertDirectoryName('//hello///world//again//', '\\\\hello\\world') assertDirectoryName('///hello///world//again//', '\\\\hello\\world') assertDirectoryName('/////hello///world//again//', '\\\\hello\\world') // Relative: assertDirectoryName('hello\\world', 'hello') // Directory trimming assertDirectoryName('a:/hello', 'a:\\') assertDirectoryName('z:/hello', 'z:\\') assertDirectoryName('A:/hello', 'A:\\') assertDirectoryName('Z:/hello', 'Z:\\') assertDirectoryName('C:/', 'C:\\') assertDirectoryName('C:/hello', 'C:\\') assertDirectoryName('C:/hello/', 'C:\\') assertDirectoryName('C:/hello/world', 'C:\\hello') assertDirectoryName('C:/hello/world/', 'C:\\hello') assertDirectoryName('C:', 'C:') assertDirectoryName('C:hello', 'C:') assertDirectoryName('C:hello/', 'C:') assertDirectoryName('C:hello/world', 'C:hello') assertDirectoryName('C:hello/world/', 'C:hello') assertDirectoryName('/', '\\') assertDirectoryName('/hello', '\\') assertDirectoryName('/hello/', '\\') assertDirectoryName('/hello/world', '\\hello') assertDirectoryName('/hello/world/', '\\hello') assertDirectoryName('\\', '\\') assertDirectoryName('\\hello', '\\') assertDirectoryName('\\hello\\', '\\') assertDirectoryName('\\hello\\world', '\\hello') assertDirectoryName('\\hello\\world\\', '\\hello') assertDirectoryName('//hello', '\\\\hello') assertDirectoryName('//hello/', '\\\\hello') assertDirectoryName('//hello/world', '\\\\hello\\world') assertDirectoryName('//hello/world/', '\\\\hello\\world') assertDirectoryName('\\\\hello', '\\\\hello') assertDirectoryName('\\\\hello\\', '\\\\hello') assertDirectoryName('\\\\hello\\world', '\\\\hello\\world') assertDirectoryName('\\\\hello\\world\\', '\\\\hello\\world') assertDirectoryName('//hello/world/again', '\\\\hello\\world') assertDirectoryName('//hello/world/again/', '\\\\hello\\world') assertDirectoryName('hello/world/', 'hello') assertDirectoryName('hello/world/again', 'hello\\world') assertDirectoryName('../../hello', '..\\..') } else { // Should not converts slashes assertDirectoryName('/hello\\world', '/') assertDirectoryName('/hello\\world/', '/') assertDirectoryName('\\\\hello\\world\\again', '.') assertDirectoryName('\\\\hello\\world/', '.') assertDirectoryName('\\\\hello\\world/again', '\\\\hello\\world') assertDirectoryName('hello\\world', '.') assertDirectoryName('hello\\world/', '.') // Should remove redundant slashes (rooted paths; UNC format not special) assertDirectoryName('//hello', '/') assertDirectoryName('//hello/world', '/hello') assertDirectoryName('//hello/world/', '/hello') assertDirectoryName('//hello//world//', '/hello') assertDirectoryName('///hello////world///', '/hello') // Should remove redundant slashes (relative paths) assertDirectoryName('hello//world//again//', 'hello/world') assertDirectoryName('hello///world///again///', 'hello/world') // Directory trimming (Windows drive root format not special) assertDirectoryName('C:/', '.') assertDirectoryName('C:/hello', 'C:') assertDirectoryName('C:/hello/', 'C:') assertDirectoryName('C:/hello/world', 'C:/hello') assertDirectoryName('C:/hello/world/', 'C:/hello') assertDirectoryName('C:', '.') assertDirectoryName('C:hello', '.') assertDirectoryName('C:hello/', '.') assertDirectoryName('C:hello/world', 'C:hello') assertDirectoryName('C:hello/world/', 'C:hello') // Directory trimming (rooted paths) assertDirectoryName('/', '/') assertDirectoryName('/hello', '/') assertDirectoryName('/hello/', '/') assertDirectoryName('/hello/world', '/hello') assertDirectoryName('/hello/world/', '/hello') // Directory trimming (relative paths) assertDirectoryName('hello/world/', 'hello') assertDirectoryName('hello/world/again', 'hello/world') assertDirectoryName('../../hello', '../..') } }) it('ensureAbsoluteRoot roots paths', () => { if (IS_WINDOWS) { const currentDrive = process.cwd().substr(0, 2) expect(currentDrive.match(/^[A-Z]:$/i)).toBeTruthy() const otherDrive = currentDrive.toUpperCase().startsWith('C') ? 'D:' : 'C:' // Preserves relative pathing assertEnsureAbsoluteRoot('C:/foo', '.', `C:/foo\\.`) assertEnsureAbsoluteRoot('C:/foo/..', 'bar', `C:/foo/..\\bar`) assertEnsureAbsoluteRoot('C:/foo', 'bar/../baz', `C:/foo\\bar/../baz`) // Already rooted - drive root assertEnsureAbsoluteRoot('D:\\', 'C:/', 'C:/') assertEnsureAbsoluteRoot('D:\\', 'a:/hello', 'a:/hello') assertEnsureAbsoluteRoot('D:\\', 'C:\\', 'C:\\') assertEnsureAbsoluteRoot('D:\\', 'C:\\hello', 'C:\\hello') // Already rooted - relative current drive root expect(process.cwd().length).toBeGreaterThan(3) // sanity check not drive root assertEnsureAbsoluteRoot(`${otherDrive}\\`, currentDrive, process.cwd()) assertEnsureAbsoluteRoot( `${otherDrive}\\`, `${currentDrive}hello`, `${process.cwd()}\\hello` ) assertEnsureAbsoluteRoot( `${otherDrive}\\`, `${currentDrive}hello/world`, `${process.cwd()}\\hello/world` ) assertEnsureAbsoluteRoot( `${otherDrive}\\`, `${currentDrive}hello\\world`, `${process.cwd()}\\hello\\world` ) // Already rooted - relative other drive root assertEnsureAbsoluteRoot( `${currentDrive}\\`, otherDrive, `${otherDrive}\\` ) assertEnsureAbsoluteRoot( `${currentDrive}\\`, `${otherDrive}hello`, `${otherDrive}\\hello` ) assertEnsureAbsoluteRoot( `${currentDrive}\\`, `${otherDrive}hello/world`, `${otherDrive}\\hello/world` ) assertEnsureAbsoluteRoot( `${currentDrive}\\`, `${otherDrive}hello\\world`, `${otherDrive}\\hello\\world` ) // Already rooted - current drive root assertEnsureAbsoluteRoot(`${otherDrive}\\`, '/', `${currentDrive}\\`) assertEnsureAbsoluteRoot( `${otherDrive}\\`, '/hello', `${currentDrive}\\hello` ) assertEnsureAbsoluteRoot(`${otherDrive}\\`, '\\', `${currentDrive}\\`) assertEnsureAbsoluteRoot( `${otherDrive}\\`, '\\hello', `${currentDrive}\\hello` ) // Already rooted - UNC assertEnsureAbsoluteRoot('D:\\', '//machine/share', '//machine/share') assertEnsureAbsoluteRoot( 'D:\\', '\\\\machine\\share', '\\\\machine\\share' ) // Relative assertEnsureAbsoluteRoot('D:/', 'hello', 'D:/hello') assertEnsureAbsoluteRoot('D:/', 'hello/world', 'D:/hello/world') assertEnsureAbsoluteRoot('D:\\', 'hello', 'D:\\hello') assertEnsureAbsoluteRoot('D:\\', 'hello\\world', 'D:\\hello\\world') assertEnsureAbsoluteRoot('D:/root', 'hello', 'D:/root\\hello') assertEnsureAbsoluteRoot('D:/root', 'hello/world', 'D:/root\\hello/world') assertEnsureAbsoluteRoot('D:\\root', 'hello', 'D:\\root\\hello') assertEnsureAbsoluteRoot( 'D:\\root', 'hello\\world', 'D:\\root\\hello\\world' ) assertEnsureAbsoluteRoot('D:/root/', 'hello', 'D:/root/hello') assertEnsureAbsoluteRoot('D:/root/', 'hello/world', 'D:/root/hello/world') assertEnsureAbsoluteRoot('D:\\root\\', 'hello', 'D:\\root\\hello') assertEnsureAbsoluteRoot( 'D:\\root\\', 'hello\\world', 'D:\\root\\hello\\world' ) } else { // Preserves relative pathing assertEnsureAbsoluteRoot('/foo', '.', `/foo/.`) assertEnsureAbsoluteRoot('/foo/..', 'bar', `/foo/../bar`) assertEnsureAbsoluteRoot('/foo', 'bar/../baz', `/foo/bar/../baz`) // Already rooted assertEnsureAbsoluteRoot('/root', '/', '/') assertEnsureAbsoluteRoot('/root', '/hello', '/hello') assertEnsureAbsoluteRoot('/root', '/hello/world', '/hello/world') // Not already rooted - Windows style drive root assertEnsureAbsoluteRoot('/root', 'C:/', '/root/C:/') assertEnsureAbsoluteRoot('/root', 'C:/hello', '/root/C:/hello') assertEnsureAbsoluteRoot('/root', 'C:\\', '/root/C:\\') // Not already rooted - Windows style relative drive root assertEnsureAbsoluteRoot('/root', 'C:', '/root/C:') assertEnsureAbsoluteRoot('/root', 'C:hello/world', '/root/C:hello/world') // Not already rooted - Windows style current drive root assertEnsureAbsoluteRoot('/root', '\\', '/root/\\') assertEnsureAbsoluteRoot( '/root', '\\hello\\world', '/root/\\hello\\world' ) // Not already rooted - Windows style UNC assertEnsureAbsoluteRoot( '/root', '\\\\machine\\share', '/root/\\\\machine\\share' ) // Not already rooted - relative assertEnsureAbsoluteRoot('/', 'hello', '/hello') assertEnsureAbsoluteRoot('/', 'hello/world', '/hello/world') assertEnsureAbsoluteRoot('/', 'hello\\world', '/hello\\world') assertEnsureAbsoluteRoot('/root', 'hello', '/root/hello') assertEnsureAbsoluteRoot('/root', 'hello/world', '/root/hello/world') assertEnsureAbsoluteRoot('/root', 'hello\\world', '/root/hello\\world') assertEnsureAbsoluteRoot('/root/', 'hello', '/root/hello') assertEnsureAbsoluteRoot('/root/', 'hello/world', '/root/hello/world') assertEnsureAbsoluteRoot('/root/', 'hello\\world', '/root/hello\\world') assertEnsureAbsoluteRoot('/root\\', 'hello', '/root\\/hello') assertEnsureAbsoluteRoot('/root\\', 'hello/world', '/root\\/hello/world') assertEnsureAbsoluteRoot( '/root\\', 'hello\\world', '/root\\/hello\\world' ) } }) it('hasAbsoluteRoot detects absolute root', () => { if (IS_WINDOWS) { // Drive root assertHasAbsoluteRoot('C:/', true) assertHasAbsoluteRoot('a:/hello', true) assertHasAbsoluteRoot('c:/hello', true) assertHasAbsoluteRoot('z:/hello', true) assertHasAbsoluteRoot('A:/hello', true) assertHasAbsoluteRoot('C:/hello', true) assertHasAbsoluteRoot('Z:/hello', true) assertHasAbsoluteRoot('C:\\', true) assertHasAbsoluteRoot('C:\\hello', true) // Relative drive root assertHasAbsoluteRoot('C:', false) assertHasAbsoluteRoot('C:hello', false) assertHasAbsoluteRoot('C:hello/world', false) assertHasAbsoluteRoot('C:hello\\world', false) // Current drive root assertHasAbsoluteRoot('/', false) assertHasAbsoluteRoot('/hello', false) assertHasAbsoluteRoot('/hello/world', false) assertHasAbsoluteRoot('\\', false) assertHasAbsoluteRoot('\\hello', false) assertHasAbsoluteRoot('\\hello\\world', false) // UNC assertHasAbsoluteRoot('//machine/share', true) assertHasAbsoluteRoot('//machine/share/', true) assertHasAbsoluteRoot('//machine/share/hello', true) assertHasAbsoluteRoot('\\\\machine\\share', true) assertHasAbsoluteRoot('\\\\machine\\share\\', true) assertHasAbsoluteRoot('\\\\machine\\share\\hello', true) // Relative assertHasAbsoluteRoot('hello', false) assertHasAbsoluteRoot('hello/world', false) assertHasAbsoluteRoot('hello\\world', false) } else { // Root assertHasAbsoluteRoot('/', true) assertHasAbsoluteRoot('/hello', true) assertHasAbsoluteRoot('/hello/world', true) // Windows style drive root - false on OSX/Linux assertHasAbsoluteRoot('C:/', false) assertHasAbsoluteRoot('a:/hello', false) assertHasAbsoluteRoot('c:/hello', false) assertHasAbsoluteRoot('z:/hello', false) assertHasAbsoluteRoot('A:/hello', false) assertHasAbsoluteRoot('C:/hello', false) assertHasAbsoluteRoot('Z:/hello', false) assertHasAbsoluteRoot('C:\\', false) assertHasAbsoluteRoot('C:\\hello', false) // Windows style relative drive root - false on OSX/Linux assertHasAbsoluteRoot('C:', false) assertHasAbsoluteRoot('C:hello', false) assertHasAbsoluteRoot('C:hello/world', false) assertHasAbsoluteRoot('C:hello\\world', false) // Windows style current drive root - false on OSX/Linux assertHasAbsoluteRoot('\\', false) assertHasAbsoluteRoot('\\hello', false) assertHasAbsoluteRoot('\\hello\\world', false) // Windows style UNC - false on OSX/Linux assertHasAbsoluteRoot('\\\\machine\\share', false) assertHasAbsoluteRoot('\\\\machine\\share\\', false) assertHasAbsoluteRoot('\\\\machine\\share\\hello', false) // Relative assertHasAbsoluteRoot('hello', false) assertHasAbsoluteRoot('hello/world', false) assertHasAbsoluteRoot('hello\\world', false) } }) it('hasRoot detects root', () => { if (IS_WINDOWS) { // Drive root assertHasRoot('C:/', true) assertHasRoot('a:/hello', true) assertHasRoot('c:/hello', true) assertHasRoot('z:/hello', true) assertHasRoot('A:/hello', true) assertHasRoot('C:/hello', true) assertHasRoot('Z:/hello', true) assertHasRoot('C:\\', true) assertHasRoot('C:\\hello', true) // Relative drive root assertHasRoot('C:', true) assertHasRoot('C:hello', true) assertHasRoot('C:hello/world', true) assertHasRoot('C:hello\\world', true) // Current drive root assertHasRoot('/', true) assertHasRoot('/hello', true) assertHasRoot('/hello/world', true) assertHasRoot('\\', true) assertHasRoot('\\hello', true) assertHasRoot('\\hello\\world', true) // UNC assertHasRoot('//machine/share', true) assertHasRoot('//machine/share/', true) assertHasRoot('//machine/share/hello', true) assertHasRoot('\\\\machine\\share', true) assertHasRoot('\\\\machine\\share\\', true) assertHasRoot('\\\\machine\\share\\hello', true) // Relative assertHasRoot('hello', false) assertHasRoot('hello/world', false) assertHasRoot('hello\\world', false) } else { // Root assertHasRoot('/', true) assertHasRoot('/hello', true) assertHasRoot('/hello/world', true) // Windows style drive root - false on OSX/Linux assertHasRoot('C:/', false) assertHasRoot('a:/hello', false) assertHasRoot('c:/hello', false) assertHasRoot('z:/hello', false) assertHasRoot('A:/hello', false) assertHasRoot('C:/hello', false) assertHasRoot('Z:/hello', false) assertHasRoot('C:\\', false) assertHasRoot('C:\\hello', false) // Windows style relative drive root - false on OSX/Linux assertHasRoot('C:', false) assertHasRoot('C:hello', false) assertHasRoot('C:hello/world', false) assertHasRoot('C:hello\\world', false) // Windows style current drive root - false on OSX/Linux assertHasRoot('\\', false) assertHasRoot('\\hello', false) assertHasRoot('\\hello\\world', false) // Windows style UNC - false on OSX/Linux assertHasRoot('\\\\machine\\share', false) assertHasRoot('\\\\machine\\share\\', false) assertHasRoot('\\\\machine\\share\\hello', false) // Relative assertHasRoot('hello', false) assertHasRoot('hello/world', false) assertHasRoot('hello\\world', false) } }) it('normalizeSeparators normalizes slashes', () => { if (IS_WINDOWS) { // Drive-rooted assertNormalizeSeparators('C:/', 'C:\\') assertNormalizeSeparators('C:/hello', 'C:\\hello') assertNormalizeSeparators('C:/hello/', 'C:\\hello\\') assertNormalizeSeparators('C:\\', 'C:\\') assertNormalizeSeparators('C:\\hello', 'C:\\hello') assertNormalizeSeparators('C:', 'C:') assertNormalizeSeparators('C:hello', 'C:hello') assertNormalizeSeparators('C:hello/world', 'C:hello\\world') assertNormalizeSeparators('C:hello\\world', 'C:hello\\world') assertNormalizeSeparators('/', '\\') assertNormalizeSeparators('/hello', '\\hello') assertNormalizeSeparators('/hello/world', '\\hello\\world') assertNormalizeSeparators('/hello//world', '\\hello\\world') assertNormalizeSeparators('\\', '\\') assertNormalizeSeparators('\\hello', '\\hello') assertNormalizeSeparators('\\hello\\', '\\hello\\') assertNormalizeSeparators('\\hello\\world', '\\hello\\world') assertNormalizeSeparators('\\hello\\\\world', '\\hello\\world') // UNC assertNormalizeSeparators('//machine/share', '\\\\machine\\share') assertNormalizeSeparators('//machine/share/', '\\\\machine\\share\\') assertNormalizeSeparators( '//machine/share/hello', '\\\\machine\\share\\hello' ) assertNormalizeSeparators('///machine/share', '\\\\machine\\share') assertNormalizeSeparators('\\\\machine\\share', '\\\\machine\\share') assertNormalizeSeparators('\\\\machine\\share\\', '\\\\machine\\share\\') assertNormalizeSeparators( '\\\\machine\\share\\hello', '\\\\machine\\share\\hello' ) assertNormalizeSeparators('\\\\\\machine\\share', '\\\\machine\\share') // Relative assertNormalizeSeparators('hello', 'hello') assertNormalizeSeparators('hello/world', 'hello\\world') assertNormalizeSeparators('hello//world', 'hello\\world') assertNormalizeSeparators('hello\\world', 'hello\\world') assertNormalizeSeparators('hello\\\\world', 'hello\\world') } else { // Rooted assertNormalizeSeparators('/', '/') assertNormalizeSeparators('/hello', '/hello') assertNormalizeSeparators('/hello/world', '/hello/world') assertNormalizeSeparators('//hello/world/', '/hello/world/') // Backslash not converted assertNormalizeSeparators('C:\\', 'C:\\') assertNormalizeSeparators('C:\\\\hello\\\\', 'C:\\\\hello\\\\') assertNormalizeSeparators('\\', '\\') assertNormalizeSeparators('\\hello', '\\hello') assertNormalizeSeparators('\\hello\\world', '\\hello\\world') assertNormalizeSeparators('hello\\world', 'hello\\world') // UNC not converted assertNormalizeSeparators('\\\\machine\\share', '\\\\machine\\share') // UNC not preserved assertNormalizeSeparators('//machine/share', '/machine/share') // Relative assertNormalizeSeparators('hello', 'hello') assertNormalizeSeparators('hello/////world', 'hello/world') } }) it('safeTrimTrailingSeparator safely trims trailing separator', () => { assertSafeTrimTrailingSeparator('', '') if (IS_WINDOWS) { // Removes redundant slashes assertSafeTrimTrailingSeparator( 'C:\\\\hello\\\\\\world\\\\', 'C:\\hello\\world' ) assertSafeTrimTrailingSeparator('C://hello///world//', 'C:\\hello\\world') // Relative root: assertSafeTrimTrailingSeparator( '\\hello\\\\world\\\\again\\\\', '\\hello\\world\\again' ) assertSafeTrimTrailingSeparator( '/hello///world//again//', '\\hello\\world\\again' ) // UNC: assertSafeTrimTrailingSeparator('\\\\hello\\world\\', '\\\\hello\\world') assertSafeTrimTrailingSeparator( '\\\\hello\\world\\\\', '\\\\hello\\world' ) assertSafeTrimTrailingSeparator( '\\\\hello\\\\\\world\\\\again\\', '\\\\hello\\world\\again' ) assertSafeTrimTrailingSeparator('//hello/world/', '\\\\hello\\world') assertSafeTrimTrailingSeparator('//hello/world//', '\\\\hello\\world') assertSafeTrimTrailingSeparator( '//hello//world//again/', '\\\\hello\\world\\again' ) // Relative: assertSafeTrimTrailingSeparator('hello\\world\\', 'hello\\world') // Slash trimming assertSafeTrimTrailingSeparator('a:/hello/', 'a:\\hello') assertSafeTrimTrailingSeparator('z:/hello', 'z:\\hello') assertSafeTrimTrailingSeparator('C:/', 'C:\\') assertSafeTrimTrailingSeparator('C:\\', 'C:\\') assertSafeTrimTrailingSeparator('C:/hello/world', 'C:\\hello\\world') assertSafeTrimTrailingSeparator('C:/hello/world/', 'C:\\hello\\world') assertSafeTrimTrailingSeparator('C:', 'C:') assertSafeTrimTrailingSeparator('C:hello/', 'C:hello') assertSafeTrimTrailingSeparator('/', '\\') assertSafeTrimTrailingSeparator('/hello/', '\\hello') assertSafeTrimTrailingSeparator('\\', '\\') assertSafeTrimTrailingSeparator('\\hello\\', '\\hello') assertSafeTrimTrailingSeparator('//hello/', '\\\\hello') assertSafeTrimTrailingSeparator('//hello/world', '\\\\hello\\world') assertSafeTrimTrailingSeparator('//hello/world/', '\\\\hello\\world') assertSafeTrimTrailingSeparator('\\\\hello', '\\\\hello') assertSafeTrimTrailingSeparator('\\\\hello\\', '\\\\hello') assertSafeTrimTrailingSeparator('\\\\hello\\world', '\\\\hello\\world') assertSafeTrimTrailingSeparator('\\\\hello\\world\\', '\\\\hello\\world') assertSafeTrimTrailingSeparator('hello/world/', 'hello\\world') assertSafeTrimTrailingSeparator('hello/', 'hello') assertSafeTrimTrailingSeparator('../../', '..\\..') } else { // Should not converts slashes assertSafeTrimTrailingSeparator('/hello\\world', '/hello\\world') assertSafeTrimTrailingSeparator('/hello\\world/', '/hello\\world') assertSafeTrimTrailingSeparator('\\\\hello\\world/', '\\\\hello\\world') assertSafeTrimTrailingSeparator('hello\\world/', 'hello\\world') // Should remove redundant slashes (rooted paths; UNC format not special) assertSafeTrimTrailingSeparator('//hello', '/hello') assertSafeTrimTrailingSeparator('//hello/world', '/hello/world') assertSafeTrimTrailingSeparator('//hello/world/', '/hello/world') assertSafeTrimTrailingSeparator('//hello//world//', '/hello/world') assertSafeTrimTrailingSeparator('///hello////world///', '/hello/world') // Should remove redundant slashes (relative paths) assertSafeTrimTrailingSeparator('hello//world//', 'hello/world') assertSafeTrimTrailingSeparator('hello///world///', 'hello/world') // Slash trimming (Windows drive root format not special) assertSafeTrimTrailingSeparator('C:/', 'C:') assertSafeTrimTrailingSeparator('C:/hello', 'C:/hello') assertSafeTrimTrailingSeparator('C:/hello/', 'C:/hello') assertSafeTrimTrailingSeparator('C:hello/', 'C:hello') // Slash trimming (rooted paths) assertSafeTrimTrailingSeparator('/', '/') assertSafeTrimTrailingSeparator('/hello', '/hello') assertSafeTrimTrailingSeparator('/hello/', '/hello') assertSafeTrimTrailingSeparator('/hello/world/', '/hello/world') // Slash trimming (relative paths) assertSafeTrimTrailingSeparator('hello/world/', 'hello/world') assertSafeTrimTrailingSeparator('../../', '../..') } }) }) function assertDirectoryName(itemPath: string, expected: string): void { expect(pathHelper.dirname(itemPath)).toBe(expected) } function assertEnsureAbsoluteRoot( root: string, itemPath: string, expected: string ): void { expect(pathHelper.ensureAbsoluteRoot(root, itemPath)).toBe(expected) } function assertHasAbsoluteRoot(itemPath: string, expected: boolean): void { expect(pathHelper.hasAbsoluteRoot(itemPath)).toBe(expected) } function assertHasRoot(itemPath: string, expected: boolean): void { expect(pathHelper.hasRoot(itemPath)).toBe(expected) } function assertNormalizeSeparators(itemPath: string, expected: string): void { expect(pathHelper.normalizeSeparators(itemPath)).toBe(expected) } function assertSafeTrimTrailingSeparator( itemPath: string, expected: string ): void { expect(pathHelper.safeTrimTrailingSeparator(itemPath)).toBe(expected) }
the_stack
import { LayerEffectsInfo, BevelStyle, LayerEffectShadow } from './psd'; import { toBlendMode, fromBlendMode } from './helpers'; import { PsdReader, checkSignature, readSignature, skipBytes, readUint16, readUint8, readUint32, readFixedPoint32, readColor } from './psdReader'; import { PsdWriter, writeSignature, writeUint16, writeZeros, writeFixedPoint32, writeUint8, writeUint32, writeColor } from './psdWriter'; const bevelStyles: BevelStyle[] = [ undefined as any, 'outer bevel', 'inner bevel', 'emboss', 'pillow emboss', 'stroke emboss' ]; function readBlendMode(reader: PsdReader) { checkSignature(reader, '8BIM'); return toBlendMode[readSignature(reader)] || 'normal'; } function writeBlendMode(writer: PsdWriter, mode: string | undefined) { writeSignature(writer, '8BIM'); writeSignature(writer, fromBlendMode[mode!] || 'norm'); } function readFixedPoint8(reader: PsdReader) { return readUint8(reader) / 0xff; } function writeFixedPoint8(writer: PsdWriter, value: number) { writeUint8(writer, Math.round(value * 0xff) | 0); } export function readEffects(reader: PsdReader) { const version = readUint16(reader); if (version !== 0) throw new Error(`Invalid effects layer version: ${version}`); const effectsCount = readUint16(reader); const effects: LayerEffectsInfo = <any>{}; for (let i = 0; i < effectsCount; i++) { checkSignature(reader, '8BIM'); const type = readSignature(reader); switch (type) { case 'cmnS': { // common state (see See Effects layer, common state info) const size = readUint32(reader); const version = readUint32(reader); const visible = !!readUint8(reader); skipBytes(reader, 2); if (size !== 7 || version !== 0 || !visible) throw new Error(`Invalid effects common state`); break; } case 'dsdw': // drop shadow (see See Effects layer, drop shadow and inner shadow info) case 'isdw': { // inner shadow (see See Effects layer, drop shadow and inner shadow info) const blockSize = readUint32(reader); const version = readUint32(reader); if (blockSize !== 41 && blockSize !== 51) throw new Error(`Invalid shadow size: ${blockSize}`); if (version !== 0 && version !== 2) throw new Error(`Invalid shadow version: ${version}`); const size = readFixedPoint32(reader); readFixedPoint32(reader); // intensity const angle = readFixedPoint32(reader); const distance = readFixedPoint32(reader); const color = readColor(reader); const blendMode = readBlendMode(reader); const enabled = !!readUint8(reader); const useGlobalLight = !!readUint8(reader); const opacity = readFixedPoint8(reader); if (blockSize >= 51) readColor(reader); // native color const shadowInfo: LayerEffectShadow = { size: { units: 'Pixels', value: size }, distance: { units: 'Pixels', value: distance }, angle, color, blendMode, enabled, useGlobalLight, opacity }; if (type === 'dsdw') { effects.dropShadow = [shadowInfo]; } else { effects.innerShadow = [shadowInfo]; } break; } case 'oglw': { // outer glow (see See Effects layer, outer glow info) const blockSize = readUint32(reader); const version = readUint32(reader); if (blockSize !== 32 && blockSize !== 42) throw new Error(`Invalid outer glow size: ${blockSize}`); if (version !== 0 && version !== 2) throw new Error(`Invalid outer glow version: ${version}`); const size = readFixedPoint32(reader); readFixedPoint32(reader); // intensity const color = readColor(reader); const blendMode = readBlendMode(reader); const enabled = !!readUint8(reader); const opacity = readFixedPoint8(reader); if (blockSize >= 42) readColor(reader); // native color effects.outerGlow = { size: { units: 'Pixels', value: size }, color, blendMode, enabled, opacity }; break; } case 'iglw': { // inner glow (see See Effects layer, inner glow info) const blockSize = readUint32(reader); const version = readUint32(reader); if (blockSize !== 32 && blockSize !== 43) throw new Error(`Invalid inner glow size: ${blockSize}`); if (version !== 0 && version !== 2) throw new Error(`Invalid inner glow version: ${version}`); const size = readFixedPoint32(reader); readFixedPoint32(reader); // intensity const color = readColor(reader); const blendMode = readBlendMode(reader); const enabled = !!readUint8(reader); const opacity = readFixedPoint8(reader); if (blockSize >= 43) { readUint8(reader); // inverted readColor(reader); // native color } effects.innerGlow = { size: { units: 'Pixels', value: size }, color, blendMode, enabled, opacity }; break; } case 'bevl': { // bevel (see See Effects layer, bevel info) const blockSize = readUint32(reader); const version = readUint32(reader); if (blockSize !== 58 && blockSize !== 78) throw new Error(`Invalid bevel size: ${blockSize}`); if (version !== 0 && version !== 2) throw new Error(`Invalid bevel version: ${version}`); const angle = readFixedPoint32(reader); const strength = readFixedPoint32(reader); const size = readFixedPoint32(reader); const highlightBlendMode = readBlendMode(reader); const shadowBlendMode = readBlendMode(reader); const highlightColor = readColor(reader); const shadowColor = readColor(reader); const style = bevelStyles[readUint8(reader)] || 'inner bevel'; const highlightOpacity = readFixedPoint8(reader); const shadowOpacity = readFixedPoint8(reader); const enabled = !!readUint8(reader); const useGlobalLight = !!readUint8(reader); const direction = readUint8(reader) ? 'down' : 'up'; if (blockSize >= 78) { readColor(reader); // real highlight color readColor(reader); // real shadow color } effects.bevel = { size: { units: 'Pixels', value: size }, angle, strength, highlightBlendMode, shadowBlendMode, highlightColor, shadowColor, style, highlightOpacity, shadowOpacity, enabled, useGlobalLight, direction, }; break; } case 'sofi': { // solid fill (Photoshop 7.0) (see See Effects layer, solid fill (added in Photoshop 7.0)) const size = readUint32(reader); const version = readUint32(reader); if (size !== 34) throw new Error(`Invalid effects solid fill info size: ${size}`); if (version !== 2) throw new Error(`Invalid effects solid fill info version: ${version}`); const blendMode = readBlendMode(reader); const color = readColor(reader); const opacity = readFixedPoint8(reader); const enabled = !!readUint8(reader); readColor(reader); // native color effects.solidFill = [{ blendMode, color, opacity, enabled }]; break; } default: throw new Error(`Invalid effect type: '${type}'`); } } return effects; } function writeShadowInfo(writer: PsdWriter, shadow: LayerEffectShadow) { writeUint32(writer, 51); writeUint32(writer, 2); writeFixedPoint32(writer, shadow.size && shadow.size.value || 0); writeFixedPoint32(writer, 0); // intensity writeFixedPoint32(writer, shadow.angle || 0); writeFixedPoint32(writer, shadow.distance && shadow.distance.value || 0); writeColor(writer, shadow.color); writeBlendMode(writer, shadow.blendMode); writeUint8(writer, shadow.enabled ? 1 : 0); writeUint8(writer, shadow.useGlobalLight ? 1 : 0); writeFixedPoint8(writer, shadow.opacity ?? 1); writeColor(writer, shadow.color); // native color } export function writeEffects(writer: PsdWriter, effects: LayerEffectsInfo) { const dropShadow = effects.dropShadow?.[0]; const innerShadow = effects.innerShadow?.[0]; const outerGlow = effects.outerGlow; const innerGlow = effects.innerGlow; const bevel = effects.bevel; const solidFill = effects.solidFill?.[0]; let count = 1; if (dropShadow) count++; if (innerShadow) count++; if (outerGlow) count++; if (innerGlow) count++; if (bevel) count++; if (solidFill) count++; writeUint16(writer, 0); writeUint16(writer, count); writeSignature(writer, '8BIM'); writeSignature(writer, 'cmnS'); writeUint32(writer, 7); // size writeUint32(writer, 0); // version writeUint8(writer, 1); // visible writeZeros(writer, 2); if (dropShadow) { writeSignature(writer, '8BIM'); writeSignature(writer, 'dsdw'); writeShadowInfo(writer, dropShadow); } if (innerShadow) { writeSignature(writer, '8BIM'); writeSignature(writer, 'isdw'); writeShadowInfo(writer, innerShadow); } if (outerGlow) { writeSignature(writer, '8BIM'); writeSignature(writer, 'oglw'); writeUint32(writer, 42); writeUint32(writer, 2); writeFixedPoint32(writer, outerGlow.size?.value || 0); writeFixedPoint32(writer, 0); // intensity writeColor(writer, outerGlow.color); writeBlendMode(writer, outerGlow.blendMode); writeUint8(writer, outerGlow.enabled ? 1 : 0); writeFixedPoint8(writer, outerGlow.opacity || 0); writeColor(writer, outerGlow.color); } if (innerGlow) { writeSignature(writer, '8BIM'); writeSignature(writer, 'iglw'); writeUint32(writer, 43); writeUint32(writer, 2); writeFixedPoint32(writer, innerGlow.size?.value || 0); writeFixedPoint32(writer, 0); // intensity writeColor(writer, innerGlow.color); writeBlendMode(writer, innerGlow.blendMode); writeUint8(writer, innerGlow.enabled ? 1 : 0); writeFixedPoint8(writer, innerGlow.opacity || 0); writeUint8(writer, 0); // inverted writeColor(writer, innerGlow.color); } if (bevel) { writeSignature(writer, '8BIM'); writeSignature(writer, 'bevl'); writeUint32(writer, 78); writeUint32(writer, 2); writeFixedPoint32(writer, bevel.angle || 0); writeFixedPoint32(writer, bevel.strength || 0); writeFixedPoint32(writer, bevel.size?.value || 0); writeBlendMode(writer, bevel.highlightBlendMode); writeBlendMode(writer, bevel.shadowBlendMode); writeColor(writer, bevel.highlightColor); writeColor(writer, bevel.shadowColor); const style = bevelStyles.indexOf(bevel.style!); writeUint8(writer, style <= 0 ? 1 : style); writeFixedPoint8(writer, bevel.highlightOpacity || 0); writeFixedPoint8(writer, bevel.shadowOpacity || 0); writeUint8(writer, bevel.enabled ? 1 : 0); writeUint8(writer, bevel.useGlobalLight ? 1 : 0); writeUint8(writer, bevel.direction === 'down' ? 1 : 0); writeColor(writer, bevel.highlightColor); writeColor(writer, bevel.shadowColor); } if (solidFill) { writeSignature(writer, '8BIM'); writeSignature(writer, 'sofi'); writeUint32(writer, 34); writeUint32(writer, 2); writeBlendMode(writer, solidFill.blendMode); writeColor(writer, solidFill.color); writeFixedPoint8(writer, solidFill.opacity || 0); writeUint8(writer, solidFill.enabled ? 1 : 0); writeColor(writer, solidFill.color); } }
the_stack
import { api, ApiTagDecorator, authorize, Class, EntityRelationInfo, responseType, route } from "@plumier/core" import reflect, { decorateClass } from "@plumier/reflect" import { decorateRoute, ResponseTransformer, responseTransformer } from "./decorator" import { GetManyCustomQueryDecorator, GetManyCustomQueryFunction, GetOneCustomQueryDecorator, GetOneCustomQueryFunction, } from "./helper" // --------------------------------------------------------------------- // // ------------------------------- TYPES ------------------------------- // // --------------------------------------------------------------------- // type ActionNotation = "Put" | "Patch" | "Post" | "GetMany" | "GetOne" | "Delete" interface ActionConfig { authorize?: string[] ignore?: true transformer?: { target: Class, fn: ResponseTransformer } getOneCustomQuery?: { type: Class | [Class], query: GetOneCustomQueryFunction } getManyCustomQuery?: { type: Class | [Class], query: GetManyCustomQueryFunction } } type ActionConfigMap = Map<string, ActionConfig> interface GenericControllerOptions { path?: string map: ActionConfigMap actions(): string[] } function getActionName(method: ActionNotation) { if (method === "Delete") return "delete" if (method === "GetMany") return "list" if (method === "GetOne") return "get" if (method === "Patch") return "modify" if (method === "Post") return "save" else return "replace" } class ControllerBuilder { private path?: string private map: ActionConfigMap = new Map() /** * Set custom path for generic controller */ setPath(path: string): ControllerBuilder { this.path = path return this } /** * Configure multiple generic controller actions based on their http method */ methods(...notations: ActionNotation[]) { return new ActionsBuilder(this.map, notations.map(x => getActionName(x))) } /** * Configure multiple generic controller actions based on their name */ actionNames(...names: string[]) { return new ActionsBuilder(this.map, names) } /** * Configure generic controller action handles POST http method */ post() { return new ActionsBuilder(this.map, ["save"]) } /** * Configure generic controller action handles PUT http method */ put() { return new ActionsBuilder(this.map, ["replace"]) } /** * Configure generic controller action handles PATCH http method */ patch() { return new ActionsBuilder(this.map, ["modify"]) } /** * Configure generic controller action handles DELETE http method */ delete() { return new ActionsBuilder(this.map, ["delete"]) } /** * Configure generic controller action handles GET http method with single result */ getOne() { return new GetOneActionBuilder(this.map, ["get"]) } /** * Configure generic controller action handles POST http method with multiple result */ getMany() { return new GetManyActionBuilder(this.map, ["list"]) } /** * Configure generic controller actions handles POST, PUT, PATCH, DELETE http method */ mutators() { return new ActionsBuilder(this.map, ["delete", "modify", "save", "replace"]) } /** * Configure generic controller actions handles GET http method (single result or multiple result) */ accessors() { return new TransformableActionBuilder(this.map, ["list", "get"]) } /** * Configure ALL generic controller actions */ all() { return new ActionsBuilder(this.map, ["delete", "list", "get", "modify", "save", "replace"]) } toObject(): GenericControllerOptions { return { map: this.map, path: this.path, actions() { if (this.map.size === 0) return ["delete", "list", "get", "modify", "save", "replace"] return Array.from(this.map.keys()) } } } } class ActionsBuilder { constructor(private actions: ActionConfigMap, protected names: string[]) { this.setConfig(names, {}) } protected setConfig(names: string[], config: ActionConfig) { for (const action of names) { const cnf = this.actions.get(action)! this.actions.set(action, { ...cnf, ...config }) } return this } /** * Ignore (exclude) generic controller methods from route generation system */ ignore() { return this.setConfig(this.names, { ignore: true }) } /** * Set authorization access to generic controller methods * @param authorize */ authorize(...authorize: string[]) { return this.setConfig(this.names, { authorize }) } } class TransformableActionBuilder extends ActionsBuilder { /** * Set custom response transformer returned by generic controller action * @param target Response type model * @param fn Transformation logic */ transformer<T>(target: Class<T>, fn: ResponseTransformer<any, T>) { return this.setConfig(this.names, { transformer: { target, fn } }) } } class GetOneActionBuilder extends TransformableActionBuilder { /** * Override current generic controller action database query to provide different response result then the default one * @param responseType Response type, used to specify the response schema * @param query Custom database query */ custom<T>(responseType: Class | [Class], query: GetOneCustomQueryFunction<T>) { return this.setConfig(this.names, { getOneCustomQuery: { type: responseType, query } }) } } class GetManyActionBuilder extends TransformableActionBuilder { /** * Override current generic controller action database query to provide different response result then the default one * @param responseType Response type, used to specify the response schema * @param query Custom database query */ custom<T>(responseType: Class | [Class], query: GetManyCustomQueryFunction<T>) { return this.setConfig(this.names, { getManyCustomQuery: { type: responseType, query } }) } } type GenericControllerConfiguration = (c: ControllerBuilder) => void // --------------------------------------------------------------------- // // ---------------------- CONFIGURATION DECORATORS --------------------- // // --------------------------------------------------------------------- // function splitPath(path: string): [string, string] { const idx = path.lastIndexOf("/") const root = path.substring(0, idx) const id = path.substring(idx + 2) return [root, id] } function createRouteDecorators(path: string, map: { pid?: string, id: string }) { const [root, id] = splitPath(path)! return [ route.root(root, { map }), decorateRoute("post", "", { applyTo: "save" }), decorateRoute("get", "", { applyTo: "list" }), decorateRoute("get", `:${id}`, { applyTo: "get" }), decorateRoute("put", `:${id}`, { applyTo: "replace" }), decorateRoute("patch", `:${id}`, { applyTo: "modify" }), decorateRoute("delete", `:${id}`, { applyTo: "delete" }), ] } function ignoreActions(config: GenericControllerOptions): ((...args: any[]) => void) { const actions = config.actions() const applyTo = actions.filter(x => !!config.map.get(x)?.ignore) if (applyTo.length === 0) return (...args: any[]) => { } return route.ignore({ applyTo }) } function authorizeActions(config: GenericControllerOptions) { const actions = config.actions() const result = [] for (const action of actions) { const opt = config.map.get(action) if (!opt || !opt.authorize) continue result.push(authorize.custom(opt.authorize, { access: "route", applyTo: action, tag: opt.authorize.join("|") })) } return result } function decorateTransformers(config: GenericControllerOptions) { const result = [] for (const key of config.map.keys()) { const cnf = config.map.get(key) if (cnf && cnf.transformer) { const target = key === "get" ? cnf.transformer.target : [cnf.transformer.target] result.push(responseTransformer(target, cnf.transformer.fn, { applyTo: key })) } } return result } function decorateCustomQuery(config: GenericControllerOptions) { const result = [] const get = config.map.get("get") if (get && get.getOneCustomQuery) { result.push(decorateClass(<GetOneCustomQueryDecorator>{ kind: "plumier-meta:get-one-query", query: get.getOneCustomQuery.query })) result.push(responseType(get.getOneCustomQuery.type, { applyTo: "get" })) } const list = config.map.get("list") if (list && list.getManyCustomQuery) { result.push(decorateClass(<GetManyCustomQueryDecorator>{ kind: "plumier-meta:get-many-query", query: list.getManyCustomQuery.query })) result.push(responseType(list.getManyCustomQuery.type, { applyTo: "list" })) } return result } function decorateTagByClass(entity: Class, nameConversion: (x: string) => string) { const meta = reflect(entity) const tags = meta.decorators.filter((x: ApiTagDecorator) => x.kind === "ApiTag") if (tags.length === 0) return [api.tag(nameConversion(entity.name))] return tags.map(x => decorateClass(x)) } function decorateTagByRelation(info: EntityRelationInfo, nameConversion: (x: string) => string) { const meta = reflect(info.parent) const relProp = meta.properties.find(x => x.name === info.parentProperty || x.name === info.childProperty) if (relProp) { const tags = relProp.decorators.filter((x: ApiTagDecorator) => x.kind === "ApiTag") if (tags.length > 0) return tags.map(x => decorateClass(x)) } const parent = nameConversion(info.parent.name) const child = nameConversion(info.child.name) return [api.tag(`${parent} ${child}`)] } export { ControllerBuilder, GenericControllerOptions, GenericControllerConfiguration, splitPath, createRouteDecorators, ignoreActions, authorizeActions, decorateTransformers, decorateCustomQuery, decorateTagByRelation, decorateTagByClass }
the_stack
import { AnimationEvent } from '@angular/animations'; import { hasModifierKey } from '@angular/cdk/keycodes'; import { Platform } from '@angular/cdk/platform'; import { AfterContentChecked, ChangeDetectionStrategy, Component, ElementRef, EventEmitter, HostListener, Input, NgZone, OnDestroy, Output, Renderer2, ViewEncapsulation, } from '@angular/core'; import { KEYS } from '@terminus/ngx-tools/keycodes'; import { isUnset, untilComponentDestroyed, } from '@terminus/ngx-tools/utilities'; import { fromEvent, Observable, Subject, } from 'rxjs'; import { distinctUntilChanged, filter, map, take, } from 'rxjs/operators'; import { tsDrawerAnimations } from './drawer-animations'; /** * Result of the toggle promise that indicates the state of the drawer. */ export type TsDrawerToggleResult = 'open' | 'close'; /** * Type of drawer display mode */ export type TsDrawerModes = 'overlay' | 'push'; /** * Type of drawer position */ export type TsDrawerPosition = 'start' | 'end'; export const TS_DRAWER_DEFAULT_COLLAPSE_SIZE = '3.75rem'; export const TS_DRAWER_DEFAULT_EXPAND_SIZE = '12.5rem'; /** * This drawer component corresponds to a drawer that is nested inside a {@link TsDrawerContainerComponent} * * @example * <ts-drawer * [collapsedSize]="collapsedSize" * [expandedSize]="expandedSize" * [hideShadowWhenCollapsed]="true" * [isExpanded]="isExpanded" * [mode]="mode" * [position]="position" * [role]="role" * (expandedChange)="expandedChanged($event)" * (expandedStart)="expandedStarted($event)" * (collapsedStart)="collapsedStarted($event)" * (positionChange)="positionChanged($event)" * ></ts-drawer> * * <example-url>https://getterminus.github.io/ui-demos-release/components/drawer</example-url> */ @Component({ selector: 'ts-drawer', templateUrl: './drawer.component.html', styleUrls: ['./drawer.component.scss'], animations: [tsDrawerAnimations.transformDrawer], host: { 'class': 'ts-drawer', // set align to null is to prevent the browser from aligning text based on value '[attr.align]': 'null', '[attr.role]': 'role', '[class.ts-drawer--end]': 'position === "end"', '[class.ts-drawer--overlay]': 'mode === "overlay"', '[class.ts-drawer--push]': 'mode === "push"', 'tabIndex': '-1', '[@transform]': `{ value: animationState, params: { collapsedSize: collapsedSize, expandedSize: expandedSize } }`, }, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, exportAs: 'tsDrawer', }) export class TsDrawerComponent implements AfterContentChecked, OnDestroy { /** * Define animation state, defaults to void state */ public animationState: 'open-instant' | 'open' | 'void' | 'void-shadow' = this.hideShadowWhenCollapsed ? 'void' : 'void-shadow'; /** * Emits whenever the drawer has started animating. */ public animationStarted = new Subject<AnimationEvent>(); /** * Emits whenever the drawer is done animating. */ public animationEnd = new Subject<AnimationEvent>(); /** * Emits when the component is destroyed. */ private readonly destroyed = new Subject<void>(); /** * Whether the drawer is initialized. Used for disabling the initial animation. */ private enableAnimations = false; /** * An observable that emits when the drawer mode changes. This is used by the drawer container to * to know when the mode changes so it can adapt the margins on the content. */ public readonly modeChanged = new Subject(); /** * Collapsed drawer width * * @param value */ @Input() public set collapsedSize(value: string) { this._collapsedSize = isUnset(value) ? TS_DRAWER_DEFAULT_COLLAPSE_SIZE : value; } public get collapsedSize(): string { return this._collapsedSize; } public _collapsedSize = '3.75rem'; /** * Expanded drawer width * * @param value */ @Input() public set expandedSize(value: string) { this._expandedSize = isUnset(value) ? TS_DRAWER_DEFAULT_EXPAND_SIZE : value; } public get expandedSize(): string { return this._expandedSize; } public _expandedSize = '12.75rem'; /** * Hide shadow when drawer is collapsed * * @param value */ @Input() public set hideShadowWhenCollapsed(value: boolean) { this._hideShadowWhenCollapsed = value; } public get hideShadowWhenCollapsed(): boolean { return this._hideShadowWhenCollapsed; } private _hideShadowWhenCollapsed = true; /** * Define whether the drawer is open * * @param value */ @Input() public set isExpanded(value: boolean) { this.toggle(value); } public get isExpanded(): boolean { return this._isExpanded; } private _isExpanded = false; /** * Mode of the drawer, overlay or push * * @param value */ @Input() public set mode(value: TsDrawerModes) { this._mode = value; this.modeChanged.next(); } public get mode(): TsDrawerModes { return this._mode; } private _mode: TsDrawerModes = 'overlay'; /** * The side that the drawer is attached to. * * @param value */ @Input() public set position(value: TsDrawerPosition) { // Make sure we have a valid value. value = value === 'end' ? 'end' : 'start'; if (value !== this._position) { this._position = value; this.positionChanged.emit(); } } public get position(): TsDrawerPosition { return this._position; } private _position: TsDrawerPosition = 'start'; /** * Define the aria role label, default to nothing */ @Input() public role = ''; /** * Event emitted when the drawer open state is changed. * * NOTE: This has to be async in order to avoid some issues with two-way bindings - setting isAsync to true. */ @Output() public readonly expandedChange = new EventEmitter<boolean>(true); /** * Event emitted when the drawer has been expanded. */ @Output('isExpanded') public get expandedStream(): Observable<void> { return this.expandedChange.pipe(filter(o => o), map(() => {})); } /** * Event emitted when the drawer has started expanding. */ @Output() public get expandedStart(): Observable<void> { return this.animationStarted.pipe( filter(e => e.fromState !== e.toState && e.toState.indexOf('open') === 0), untilComponentDestroyed(this), map(() => {}), ); } /** * Event emitted when the drawer has been collapsed. */ @Output('closed') public get collapsedStream(): Observable<void> { return this.expandedChange.pipe(filter(o => !o), map(() => {})); } /** * Event emitted when the drawer has started collapsing. */ @Output() public get collapsedStart(): Observable<void> { return this.animationStarted.pipe( filter(e => e.fromState !== e.toState && e.toState === 'void'), untilComponentDestroyed(this), map(() => {}), ); } /** * Event emitted when the drawer's position changes. */ // eslint-disable-next-line @angular-eslint/no-output-rename @Output('positionChanged') public readonly positionChanged = new EventEmitter<void>(); constructor( public elementRef: ElementRef<HTMLElement>, private platform: Platform, private ngZone: NgZone, public renderer: Renderer2, ) { /** * Listen to `keydown` events outside the zone so that change detection is not run every * time a key is pressed. Re-enter the zone only if the `ESC` key is pressed */ this.ngZone.runOutsideAngular(() => { // TODO: Refactor deprecation // eslint-disable-next-line deprecation/deprecation (fromEvent(this.elementRef.nativeElement, 'keydown') as Observable<KeyboardEvent>) .pipe( filter(event => event.code === KEYS.ESCAPE.code && !hasModifierKey(event)), untilComponentDestroyed(this), ).subscribe(event => this.ngZone.run(() => { this.collapse(); event.stopPropagation(); event.preventDefault(); })); }); // We need a Subject with distinctUntilChanged, because the `done` event fires twice on some browsers. this.animationEnd.pipe( distinctUntilChanged((x, y) => x.fromState === y.fromState && x.toState === y.toState), untilComponentDestroyed(this), ).subscribe((event: AnimationEvent) => { const { fromState, toState } = event; if (( toState.indexOf('open') === 0 && (fromState === 'void' || fromState === 'void-shadow')) || (toState === 'void' && fromState.indexOf('open') === 0) || (toState === 'void-shadow' && fromState.indexOf('open') === 0)) { this.expandedChange.emit(this.isExpanded); } }); this.renderer.setStyle(this.elementRef.nativeElement, 'width', this.expandedSize); } /** * Enable the animations after the lifecycle hooks have run, in order to avoid animating drawers that are open by default. */ public ngAfterContentChecked(): void { if (this.platform.isBrowser) { this.enableAnimations = true; } } /** * Complete the observable on destroy */ public ngOnDestroy(): void { this.modeChanged.complete(); this.destroyed.next(); this.destroyed.complete(); } /** * Expand the drawer. * * @returns Promise<TsDrawerToggleResult> */ public expand(): Promise<TsDrawerToggleResult> { return this.toggle(true); } /** * Collapse the drawer. * * @returns Promise<TsDrawerToggleResult> */ public collapse(): Promise<TsDrawerToggleResult> { return this.toggle(false); } /** * Toggle this drawer. * * @param isOpen - whether the drawer should be open. * @returns Promise<TsDrawerToggleResult> */ public toggle(isOpen = !this.isExpanded): Promise<TsDrawerToggleResult> { this._isExpanded = isOpen; if (isOpen) { this.animationState = this.enableAnimations ? 'open' : 'open-instant'; } else { this.animationState = this.hideShadowWhenCollapsed ? 'void' : 'void-shadow'; } return new Promise<TsDrawerToggleResult>(resolve => { this.expandedChange.pipe(take(1)).subscribe(open => resolve(open ? 'open' : 'close')); }); } /** * We have to use a `HostListener` here in order to support both Ivy and ViewEngine. * In Ivy the `host` bindings will be merged when this class is extended, whereas in * ViewEngine they're overwritten. * TODO: we move this back into `host` once Ivy is turned on by default. * * @param event */ @HostListener('@transform.start', ['$event']) public animationStartListener(event: AnimationEvent) { this.animationStarted.next(event); } /** * We have to use a `HostListener` here in order to support both Ivy and ViewEngine. * In Ivy the `host` bindings will be merged when this class is extended, whereas in * ViewEngine they're overwritten. * TODO: move this back into `host` once Ivy is turned on by default. * * @param event */ @HostListener('@transform.done', ['$event']) public animationDoneListener(event: AnimationEvent) { this.animationEnd.next(event); } }
the_stack
import { ActionContext } from "vuex" import axios, { Canceler } from "axios" import { ElMessageBox } from "element-plus" import type { State as RootState, ApidocState, } from "@@/store" import type { ApidocDetail, Response, ApidocProperty, ApidocBodyMode, ApidocHttpRequestMethod, ApidocBodyRawType, ApidocContentType, ApidocMindParam } from "@@/global" import { axios as axiosInstance } from "@/api/api" import { router } from "@/router/index" import { store } from "@/store/index" import { apidocGenerateProperty, apidocGenerateApidoc, cloneDeep, forEachForest } from "@/helper/index" import shareRouter from "@/pages/modules/apidoc/doc-view/router/index" type EditApidocPropertyPayload<K extends keyof ApidocProperty> = { data: ApidocProperty, field: K, value: ApidocProperty[K] } //接口删除提示用户 function confirmInvalidDoc(projectId: string, delId: string) { ElMessageBox.confirm("当前接口不存在,可能已经被删除!", "提示", { confirmButtonText: "关闭接口", cancelButtonText: "取消", type: "warning", }).then(() => { store.dispatch("apidoc/tabs/deleteTabByIds", { projectId, ids: [delId] }); }).catch((err) => { if (err === "cancel" || err === "close") { return; } console.error(err); }); } //添加默认请求头 function getDefaultHeaders(contentType: ApidocContentType) { const defaultHeaders: ApidocProperty<"string">[] = []; const params = apidocGenerateProperty(); params.key = "Content-Length"; params.value = "<发送请求时候自动计算>"; params.description = "<消息的长度>"; defaultHeaders.push(params); //=========================================================================// const params2 = apidocGenerateProperty(); params2.key = "User-Agent"; params2.value = "<发送请求时候自动处理>"; params2.description = "<用户代理软件信息>"; defaultHeaders.push(params2); //=========================================================================// const params3 = apidocGenerateProperty(); params3.key = "Host"; params3.value = "<发送请求时候自动处理>"; params3.description = "<主机信息>"; defaultHeaders.push(params3); //=========================================================================// const params4 = apidocGenerateProperty(); params4.key = "Accept-Encoding"; params4.value = "gzip, deflate, br"; params4.description = "<客户端理解的编码方式>"; defaultHeaders.push(params4); //=========================================================================// const params5 = apidocGenerateProperty(); params5.key = "Connection"; params5.value = "keep-alive"; params5.description = "<当前的事务完成后,是否会关闭网络连接>"; defaultHeaders.push(params5); if (contentType) { const params6 = apidocGenerateProperty(); params6.key = "Content-type"; params6.value = contentType; params6.description = "<根据body类型自动处理>"; defaultHeaders.push(params6); } return defaultHeaders; } //过滤合法的联想参数(string、number) function filterValidParams(arrayParams: ApidocProperty[], type: ApidocMindParam["paramsPosition"]) { const result: ApidocMindParam[] = []; const projectId = router.currentRoute.value.query.id as string || shareRouter.currentRoute.value.query.id as string; forEachForest(arrayParams, (data) => { const isComplex = data.type === "object" || data.type === "array"; const copyData = cloneDeep(data) as ApidocMindParam; copyData.paramsPosition = type; copyData.projectId = projectId; if (!isComplex && data.key !== "" && data.value !== "" && data.description !== "") { //常规数据 result.push(copyData); } else if (isComplex && data.key !== "" && data.description !== "") { result.push(copyData); } }); return result; } const cancel: Canceler[] = [] //请求列表 const apidoc = { namespaced: true, state: { /** * 实时文档信息 */ apidoc: apidocGenerateApidoc(), /** * 原始文档信息 */ originApidoc: apidocGenerateApidoc(), /** * 默认请求头 */ defaultHeaders: [], /** * 是否正在加载数据 */ loading: false, /** * 是否正在保存接口 */ saveLoading: false, }, mutations: { /* |-------------------------------------------------------------------------- | url、host、method、name |-------------------------------------------------------------------------- */ //改变host值 changeApidocHost(state: ApidocState, host: string): void { state.apidoc.item.url.host = host; }, //改变url值 changeApidocUrl(state: ApidocState, path: string): void { state.apidoc.item.url.path = path; }, //改变请求method changeApidocMethod(state: ApidocState, method: ApidocHttpRequestMethod): void { state.apidoc.item.method = method; }, //改变接口名称 changeApidocName(state: ApidocState, name: string): void { state.apidoc.info.name = name; }, /* |-------------------------------------------------------------------------- | Params |-------------------------------------------------------------------------- */ //改变path参数 changePathParams(state: ApidocState, paths: ApidocProperty<"string">[]): void { state.apidoc.item.paths = paths }, //在头部插入查询参数 unshiftQueryParams(state: ApidocState, queryParams: ApidocProperty<"string">[]): void { queryParams.forEach((params) => { state.apidoc.item.queryParams.unshift(params); }) }, /* |-------------------------------------------------------------------------- | requestBody |-------------------------------------------------------------------------- */ //改变body参数mode类型 changeBodyMode(state: ApidocState, mode: ApidocBodyMode): void { state.apidoc.item.requestBody.mode = mode; }, //改变body参数raw的mime类型 changeBodyRawType(state: ApidocState, rawType: ApidocBodyRawType): void { state.apidoc.item.requestBody.raw.dataType = rawType; }, /* |-------------------------------------------------------------------------- | raw参数 |-------------------------------------------------------------------------- */ //改变raw的参数值 changeBodyRawValue(state: ApidocState, rawValue: string): void { state.apidoc.item.requestBody.raw.data = rawValue; }, //改变contentType值 changeContentType(state: ApidocState, contentType: ApidocContentType): void { state.apidoc.item.contentType = contentType; const matchedValue = state.defaultHeaders.find((val) => val.key === "Content-type"); const matchedIndex = state.defaultHeaders.findIndex((val) => val.key === "Content-type"); if (contentType && matchedValue) { //存在contentType并且默认header值也有 matchedValue.value = contentType } else if (contentType && !matchedValue) { //存在contentType但是默认header没有 const params = apidocGenerateProperty(); params.key = "Content-type"; params.value = contentType; params.description = "<根据body类型自动处理>"; state.defaultHeaders.push(params); } else if (!contentType && matchedIndex !== -1) { state.defaultHeaders.splice(matchedIndex, 1) } }, /* |-------------------------------------------------------------------------- | response参数 |-------------------------------------------------------------------------- */ //改变某个response的title参数 changeResponseParamsTitleByIndex(state: ApidocState, payload: { index: number, title: string }): void { const { index, title } = payload state.apidoc.item.responseParams[index].title = title; }, //改变某个response的statusCode值 changeResponseParamsCodeByIndex(state: ApidocState, payload: { index: number, code: number }): void { const { index, code } = payload state.apidoc.item.responseParams[index].statusCode = code; }, //改变某个response的dataType值 changeResponseParamsDataTypeByIndex(state: ApidocState, payload: { index: number, type: ApidocContentType }): void { const { index, type } = payload state.apidoc.item.responseParams[index].value.dataType = type; }, //改变某个response文本value值 changeResponseParamsTextValueByIndex(state: ApidocState, payload: { index: number, value: string }): void { const { index, value } = payload state.apidoc.item.responseParams[index].value.text = value; }, //根据index值改变response changeResponseByIndex(state: ApidocState, payload: { index: number, value: ApidocProperty[] }): void { const { index, value } = payload state.apidoc.item.responseParams[index].value.json = value; }, //新增一个response addResponseParam(state: ApidocState): void { const objectParams = apidocGenerateProperty("object"); objectParams.children[0] = apidocGenerateProperty(); state.apidoc.item.responseParams.push({ title: "返回参数名称", statusCode: 200, value: { dataType: "application/json", json: [objectParams], text: "", file: { url: "", raw: "", }, } }) }, //删除一个response deleteResponseByIndex(state: ApidocState, index: number): void { state.apidoc.item.responseParams.splice(index, 1); }, /* |-------------------------------------------------------------------------- | 其它 |-------------------------------------------------------------------------- | */ //重新赋值apidoc数据 changeApidoc(state: ApidocState, payload: ApidocDetail): void { // queryParams如果没有数据则默认添加一条空数据 if (payload.item.queryParams.length === 0) { payload.item.queryParams.push(apidocGenerateProperty()); } // bodyParams如果没有数据则默认添加一条空数据 if (payload.item.requestBody.json.length === 0) { const bodyRootParams = apidocGenerateProperty("object"); bodyRootParams.children[0] = apidocGenerateProperty(); payload.item.requestBody.json.push(bodyRootParams); } //formData如果没有数据则默认添加一条空数据 if (payload.item.requestBody.formdata.length === 0) { payload.item.requestBody.formdata.push(apidocGenerateProperty()); } //urlencoded如果没有数据则默认添加一条空数据 if (payload.item.requestBody.urlencoded.length === 0) { payload.item.requestBody.urlencoded.push(apidocGenerateProperty()); } //headers如果没有数据则默认添加一条空数据 if (payload.item.headers.length === 0) { payload.item.headers.push(apidocGenerateProperty()); } state.defaultHeaders = getDefaultHeaders(payload.item.contentType); //返回参数为json的如果没有数据则默认添加一条空数据 payload.item.responseParams.forEach((params) => { if (params.value.dataType === "application/json" && params.value.json.length === 0) { const objectParams = apidocGenerateProperty("object"); objectParams.children[0] = apidocGenerateProperty(); params.value.json.push(objectParams); } }) if (payload.item.headers.length === 0) { payload.item.headers.push(apidocGenerateProperty()); } state.apidoc = payload; }, //改变apidoc原始缓存值 changeOriginApidoc(state: ApidocState): void { state.originApidoc = cloneDeep(state.apidoc); }, //改变apidoc数据加载状态 changeApidocLoading(state: ApidocState, loading: boolean): void { state.loading = loading; }, //保存apidoc时候更新loading changeApidocSaveLoading(state: ApidocState, loading: boolean): void { state.saveLoading = loading; }, //添加一个请求参数数据 addProperty(state: ApidocState, payload: { data: ApidocProperty[], params: ApidocProperty }): void { payload.data.push(payload.params); }, //删除一个请求参数数据 deleteProperty(state: ApidocState, payload: { data: ApidocProperty[], index: number }): void { payload.data.splice(payload.index, 1); }, //改变请求参数某个属性的值 changePropertyValue<K extends keyof ApidocProperty>(state: ApidocState, payload: EditApidocPropertyPayload<K>): void { const { data, field, value } = payload; data[field] = value; }, }, actions: { /** * 获取项目基本信息 */ getApidocDetail(context: ActionContext<ApidocState, RootState>, payload: { id: string, projectId: string }): Promise<void> { if (cancel.length > 0) { cancel.forEach((c) => { c("取消请求"); }) } return new Promise((resolve, reject) => { context.commit("changeApidocLoading", true); const params = { projectId: payload.projectId, _id: payload.id, } axiosInstance.get<Response<ApidocDetail>, Response<ApidocDetail>>("/api/project/doc_detail", { params, cancelToken: new axios.CancelToken((c) => { cancel.push(c); }), }).then((res) => { if (res.data === null) { //接口不存在提示用户删除接口 confirmInvalidDoc(payload.projectId, payload.id); return; } context.commit("changeApidoc", res.data) context.commit("changeOriginApidoc") store.commit("apidoc/response/clearResponseInfo") resolve() }).catch((err) => { console.error(err); reject(err); }).finally(() => { context.commit("changeApidocLoading", false); }) }); }, /** * 保存接口 */ saveApidoc(context: ActionContext<ApidocState, RootState>): Promise<void> { return new Promise((resolve, reject) => { const projectId = router.currentRoute.value.query.id as string || shareRouter.currentRoute.value.query.id as string; const tabs = store.state["apidoc/tabs"].tabs[projectId]; const currentSelectTab = tabs?.find((tab) => tab.selected) || null; if (!currentSelectTab) { console.warn("缺少tab信息"); return; } const apidocDetail = context.state.apidoc; context.commit("changeApidocSaveLoading", true); context.dispatch("saveMindParams"); const params = { _id: currentSelectTab._id, projectId, info: apidocDetail.info, item: apidocDetail.item, }; axiosInstance.post("/api/project/fill_doc", params).then(() => { //改变tab请求方法 store.commit("apidoc/tabs/changeTabInfoById", { id: currentSelectTab._id, field: "head", value: { icon: params.item.method, color: "", }, }); //改变banner请求方法 store.commit("apidoc/banner/changeBannerInfoById", { id: currentSelectTab._id, field: "method", value: params.item.method, }) //改变origindoc的值 store.commit("apidoc/apidoc/changeOriginApidoc"); //改变tab未保存小圆点 store.commit("apidoc/tabs/changeTabInfoById", { id: currentSelectTab._id, field: "saved", value: true, }); resolve(); }).catch((err) => { //改变tab未保存小圆点 store.commit("apidoc/tabs/changeTabInfoById", { id: currentSelectTab._id, field: "saved", value: false, }); console.error(err); reject(err); }).finally(() => { context.commit("changeApidocSaveLoading", false) }); }) }, /** * 保存联想参数 */ saveMindParams(context: ActionContext<ApidocState, RootState>): void { const apidocDetail = context.state.apidoc; const projectId = router.currentRoute.value.query.id as string || shareRouter.currentRoute.value.query.id as string; const paths = filterValidParams(apidocDetail.item.paths, "paths"); const queryParams = filterValidParams(apidocDetail.item.queryParams, "queryParams"); const requestBody = filterValidParams(apidocDetail.item.requestBody.json, "requestBody"); const responseParams = filterValidParams(apidocDetail.item.responseParams[0].value.json, "responseParams"); console.log(paths, queryParams, requestBody, responseParams) const params = { projectId, mindParams: paths.concat(queryParams).concat(requestBody).concat(responseParams) }; axiosInstance.post("/api/project/doc_params_mind", params).then((res) => { if (res.data != null) { store.commit("apidoc/baseInfo/changeMindParams", res.data); } }).catch((err) => { console.error(err); }); }, }, } export { apidoc }
the_stack
import * as React from 'react'; import styles from './ListNotifications.module.scss'; import * as strings from 'TeamsChatNotificationsApplicationCustomizerStrings'; import services from '../../services/spservices'; import { IListNotificationsProps } from './IListNotificationsProps'; import { IListNotificationsState } from './IListNotificationsState'; import * as moment from 'moment'; import * as $ from 'jquery'; import { Stack, IStackTokens } from 'office-ui-fabric-react/lib/Stack'; import { getTheme } from 'office-ui-fabric-react/lib/Styling'; import * as loadash from 'lodash'; import { IListChatMessage } from '../../entities/IListChatMessage'; import { Link } from 'office-ui-fabric-react/lib/Link'; import { IPersonaSharedProps, PersonaSize, Persona, IPersonaProps } from 'office-ui-fabric-react/lib/Persona'; import { Label } from 'office-ui-fabric-react/lib/Label'; import { Spinner, SpinnerSize } from 'office-ui-fabric-react/lib/Spinner'; import { Dialog, DialogType, DialogFooter } from 'office-ui-fabric-react/lib/Dialog'; import { IUser } from '../../entities/IUser'; import { Text } from 'office-ui-fabric-react/lib/Text'; import { Facepile, IFacepilePersona, IFacepileProps } from 'office-ui-fabric-react/lib/Facepile'; import { IChatMember } from '../../entities/IChatMember'; import { Icon } from 'office-ui-fabric-react/lib/Icon'; import { initializeIcons } from '@uifabric/icons'; import { Image } from 'office-ui-fabric-react/lib/Image'; import { Attachment } from '../Attachment/Attachment'; import { AdaptiveCardAttachment } from '../attachment/AdaptiveCardAttachment'; import { PnPClientStorage } from '@pnp/pnpjs'; import { IListChat } from '../../entities/IListChat'; import * as lodash from 'lodash'; import * as cheerios from 'cheerio'; initializeIcons(); const storage = new PnPClientStorage(); const theme = getTheme(); const { palette, fonts } = theme; const stackTokens: IStackTokens = { childrenGap: 20 }; /** * * * @export * @class ListNotifications * @extends {React.Component<IListNotificationsProps, IListNotificationsState>} */ export class ListNotifications extends React.Component<IListNotificationsProps, IListNotificationsState> { private _renderMessages: JSX.Element[] = []; constructor(props: IListNotificationsProps) { super(props); // services.init(this.props.context); this.state = { isLoading: false, hasError: false, messageError: undefined, renderMessages: [], hideDialog: !this.props.showDialog }; } /** * * * @memberof ListNotifications */ public componentDidMount = (): void => { this.setState({ isLoading: true }); this._loadMessages(); }; /** * * * @param {IListNotificationsProps} prevProps * @param {IListNotificationsState} prevState * @memberof ListNotifications */ public componentDidUpdate(prevProps: IListNotificationsProps, prevState: IListNotificationsState): void {} /** * * * @private * @memberof ListNotifications */ private _loadMessages = async () => { try { let { listMessages } = this.props; this._renderMessages = []; const listChats: IListChat[] = storage.local.get('listChats'); for (const message of listMessages) { // totalNotifications++; let index: number = lodash.findIndex(listChats, { chat: { id: message.chat.id } }); const chatItem = listChats && listChats.length > 0 ? listChats[index] : null; const facepilePersonas = chatItem ? chatItem.chatMembers : null; const userInfo: IUser = await services.getUser(message.chatMessage.from.user.id); let personaCardProps: IPersonaSharedProps = {} as IPersonaSharedProps; let photoUrl: string = undefined; if (userInfo) { photoUrl = await services.getUserPhoto(userInfo.userPrincipalName); } personaCardProps = { text: message.chatMessage.from.user.displayName, imageUrl: photoUrl, size: PersonaSize.size40, secondaryText: moment(message.chatMessage.createdDateTime).format('D, MMM YYYY HH:mm:ss') }; const _message: any = await this._checkMessageContent(message); this._renderMessages.push( <> <div onClick={event => { event.preventDefault(); window.open(`https://teams.microsoft.com/_#/conversations/${message.chat.id}?ctx=chat`); }}> <div className={styles.card}> {facepilePersonas && facepilePersonas.length > 0 ? ( <div className={styles.facepileWarapper}> <Facepile personas={facepilePersonas} personaSize={PersonaSize.size24} maxDisplayablePersonas={8} styles={{ root: { marginBottom: 15 } }} /> </div> ) : null} <div className={styles.cardWrapper}> <Persona {...personaCardProps} styles={{ root: { marginBottom: 10 } }} /> <div style={{ margin: 15, height: 1, borderBottomColor: palette.neutralQuaternaryAlt, borderBottomWidth: 1, borderBottomStyle: 'solid' }}></div> {message.chatMessage.body.contentType == 'html' ? ( <> <div dangerouslySetInnerHTML={{ __html: _message }} /> {message.chatMessage.attachments.length > 0 && message.chatMessage.attachments.map(attachment => { return ( // ignore adaptive cards attachment.contentUrl ? ( <Attachment fileUrl={attachment.contentUrl} name={attachment.name} /> ) : ( <AdaptiveCardAttachment attachment={attachment}/> // adaptive cards ) ); })} </> ) : ( <> {message.chatMessage.body.contentType == 'text' && ( <Text styles={{ root: { marginTop: 15, color: palette.themeDarker } }} variant='mediumPlus'> {message.chatMessage.body.content.indexOf('<attachment') !== -1 ? message.chatMessage.body.content.substr(0, message.chatMessage.body.content.indexOf('<attachment')) : message.chatMessage.body.content} </Text> )} {message.chatMessage.body.contentType == 'text' && message.chatMessage.attachments.length > 0 && message.chatMessage.attachments.map(attachment => { return <Attachment fileUrl={attachment.contentUrl} name={attachment.name} />; })} </> )} </div> </div> </div> </> ); } this.setState({ isLoading: false, renderMessages: this._renderMessages, hasError: false, messageError: '' }); } catch (error) { console.log('error', error); this.setState({ isLoading: false, renderMessages: this._renderMessages, hasError: true, messageError: error.message }); } }; /** * * @private * @memberof ListNotifications */ private _checkMessageContent = async (message: IListChatMessage): Promise<string | JSX.Element | JSX.Element[]> => { console.log('message', message.chatMessage); // try { if (message.chatMessage.body.contentType == 'html') { const _ch = cheerios.load(message.chatMessage.body.content); _ch('a') .attr('href', '#') .attr('onclick', `window.open('${_ch('a').attr('href')}'`) .addClass(`${styles.link}`); _ch('img[itemtype!="http://schema.skype.com/Emoji"]') .css('width', '100%') .css('height', '100%'); // is sticker image get src to convert DataBase64 const _imgSrc: any = _ch('img[src*="$value"]').attr('src'); let _returnHtml = ''; if (_imgSrc && _imgSrc.length > 0) { const dataURI = await services.getHostedContentImage(_imgSrc); if (dataURI) { _ch('img[src*="$value"]').attr('src', dataURI); } else { // if can't get image send default message to click to open _returnHtml = '<div>Please click to see message</div>'; _ch('img[src*="$value"]').replaceWith(_returnHtml); } } // Return Message! return _ch.html(); } else { // is text message return message.chatMessage.body.content; } } catch (error) { console.log('Error getting HTML Content', error); return '<div>Please click to see message</div>'; } }; /** * * * @returns {React.ReactElement<IListNotificationsProps>} * @memberof ListNotifications */ public render(): React.ReactElement<IListNotificationsProps> { const { hideDialog } = this.state; return ( <div> <Dialog hidden={hideDialog} onDismiss={this.props.onDismiss} dialogContentProps={{ type: DialogType.largeHeader, title: strings.DialogTitle }} modalProps={{ isBlocking: false, isDarkOverlay: false, styles: { main: { maxWidth: 400, maxHeight: 650, position: 'absolute', marginLeft: 'auto', top: 90 } } }}> <div className={styles.listMessages}> <Stack tokens={stackTokens}> {this.state.isLoading ? ( <Spinner size={SpinnerSize.small}></Spinner> ) : this.state.hasError ? ( <Label style={{ color: 'red' }}>{this.state.messageError}</Label> ) : this.state.renderMessages.length > 0 ? ( this.state.renderMessages ) : ( <Stack horizontal tokens={{ childrenGap: 10 }} horizontalAlign='center' style={{ alignItems: 'center' }}> <Icon iconName='Info' style={{ fontSize: 22 }} /> <Label>{strings.NoMessages}</Label> </Stack> )} </Stack> </div> </Dialog> </div> ); } }
the_stack
import { ObjectID, FilterQuery } from 'mongodb'; import { advanceTo, advanceBy } from "jest-date-mock"; import { QueryFilter } from '@graphback/core'; import { buildQuery } from '../src/queryBuilder'; import { createTestingContext, Context } from "./__util__"; describe('MongoDBDataProvider Advanced Filtering', () => { interface Post { _id: ObjectID; text: string; likes: number; } let context: Context; const postSchema = ` """ @model """ type Post { _id: GraphbackObjectID text: String likes: Int } scalar GraphbackObjectID `; const defaultPostSeed = [ { text: 'post', likes: 300 }, { text: 'post2', likes: 50 }, { text: 'post3', likes: 1500 }, ] //Create a new database before each tests so that //all tests can run parallel afterEach(() => context?.server?.stop()); it('can filter ObjectID', async () => { context = await createTestingContext(postSchema); const newPost = await context.providers.Post.create({ text: 'hello', likes: 100 }); const findPost = await context.providers.Post.findBy({ filter: { _id: { eq: newPost._id } } }); expect(findPost).toHaveLength(1) expect(findPost[0].text).toEqual(newPost.text); }) it('can filter using AND', async () => { context = await createTestingContext(postSchema, { seedData: { Post: defaultPostSeed } }); const posts: Post[] = await context.providers.Post.findBy({ filter: { and: [ { text: { eq: 'post' } }, { likes: { eq: 300 } } ] } }); expect(posts.length).toBeGreaterThanOrEqual(1); for (const post of posts) { expect(post.text).toEqual('post'); expect(post.likes).toEqual(300); } }); it('can filter using OR', async () => { context = await createTestingContext(postSchema, { seedData: { Post: defaultPostSeed } }); const posts: Post[] = await context.providers.Post.findBy({ filter: { or: [ { likes: { eq: 300 } }, { text: { eq: 'post2' }, } ] } }); expect(posts.length).toEqual(2); for (const post of posts) { expect((post.text === 'post2') || (post.likes === 300)); } }); it('can filter using list of OR conditions', async () => { context = await createTestingContext(postSchema, { seedData: { Post: defaultPostSeed } }); const posts: Post[] = await context.providers.Post.findBy({ filter: { or: [ { text: { eq: 'post2' }, }, { likes: { eq: 300 }, }, { text: { eq: 'post3' } } ] } }); expect(posts.length).toEqual(3); }); it('can filter using NOT', async () => { context = await createTestingContext(postSchema, { seedData: { Post: defaultPostSeed } }); const posts: Post[] = await context.providers.Post.findBy({ filter: { not: [ { text: { eq: 'post2' } }, { likes: { eq: 300 } } ] } }); expect(posts.length).toBeGreaterThanOrEqual(1); for (const post of posts) { expect(post.text).not.toEqual('post2'); expect(post.likes).not.toEqual(300); } }); it('can filter using between operator', async () => { context = await createTestingContext(postSchema, { seedData: { Post: defaultPostSeed } }); const posts: Post[] = await context.providers.Post.findBy({ filter: { likes: { between: [250, 350] } } }); expect(posts.length).toBeGreaterThanOrEqual(1); for (const post of posts) { expect(post.likes).toBeLessThanOrEqual(350); expect(post.likes).toBeGreaterThanOrEqual(250); } }); it('can filter using nbetween operator', async () => { context = await createTestingContext(postSchema, { seedData: { Post: defaultPostSeed } }); const posts: Post[] = await context.providers.Post.findBy({ filter: { likes: { nbetween: [250, 350] } } }); expect(posts.length).toBeGreaterThanOrEqual(1); for (const post of posts) { expect((post.likes < 250) || (post.likes > 350)); } }); it('can use nested filters', async () => { context = await createTestingContext(postSchema, { seedData: { Post: defaultPostSeed } }); const posts: Post[] = await context.providers.Post.findBy({ filter: { and: [ { or: [ { likes: { between: [250, 350] } }, { likes: { between: [25, 75] } } ] }, { or: [ { text: { eq: 'post' } }, { text: { eq: 'post2' } } ] } ] } }); expect(posts.length).toBeGreaterThanOrEqual(1); for (const post of posts) { expect( ( (post.likes >= 250) && (post.likes <= 350) ) || ( (post.likes >= 25) && (post.likes <= 75) ) ); expect( (post.text === 'post') || (post.text === 'post2') ); } }); it('can use contains operator', async () => { context = await createTestingContext(postSchema, { seedData: { Post: defaultPostSeed } }); const posts: Post[] = await context.providers.Post.findBy({ filter: { text: { contains: 'post' } } }); expect(posts.length).toBeGreaterThanOrEqual(1); for (const post of posts) { expect(post.text).toEqual(expect.stringContaining('post')) } }); it('can use startsWith operator', async () => { context = await createTestingContext(postSchema, { seedData: { Post: defaultPostSeed } }); const posts: Post[] = await context.providers.Post.findBy({ filter: { text: { startsWith: 'post' } } }); expect(posts.length).toBeGreaterThanOrEqual(1); for (const post of posts) { expect(post.text).toEqual(expect.stringMatching(/^post/g)) } }); it('can use endsWith operator', async () => { context = await createTestingContext(postSchema, { seedData: { Post: defaultPostSeed } }); const posts: Post[] = await context.providers.Post.findBy({ filter: { text: { endsWith: 'post' } } }); expect(posts.length).toBeGreaterThanOrEqual(1); for (const post of posts) { expect(post.text).toEqual(expect.stringMatching(/post$/g)) } }); test('escaping regex strings', async () => { context = await createTestingContext(postSchema, { seedData: { Post: [ ...defaultPostSeed, { text: 'p..t', likes: 4500 } ] } }); const posts: Post[] = await context.providers.Post.findBy({ filter: { text: { contains: 'p..t' } } }); expect(posts.length).toBeGreaterThanOrEqual(1); for (const post of posts) { expect(post.text).toMatch(/p\.\.t/g) } }); }); describe('queryBuilder scalar filtering', () => { let context: Context; afterEach(() => context.server.stop()); it('can filter @versioned metadata fields', async () => { context = await createTestingContext(` """ @model @versioned """ type Post { _id: GraphbackObjectID text: String } scalar GraphbackObjectID `) const startTime = 1590679886048; advanceTo(startTime); // Create some posts for (const postTitle of ["hi guys", "not yet", "bye guys"]) { advanceBy(3000); await context.providers.Post.create({ text: postTitle }); } // Get all posts created since startTime const posts = await context.providers.Post.findBy({ filter: { createdAt: { gt: startTime } } }); expect(posts.length).toEqual(3); expect(posts.map((post: any) => post.text)).toEqual(["hi guys", "not yet", "bye guys"]); // Get all posts created after the first post const newPosts = await context.providers.Post.findBy({ filter: { createdAt: { gt: posts[0].createdAt } } }); expect(newPosts.length).toEqual(2); expect(newPosts.map((post: any) => post.text)).toEqual(["not yet", "bye guys"]); }); it('a && (b || c)', () => { const inputQuery: QueryFilter = { a: { eq: 1 }, or: [ { b: { eq: 2 } }, { c: { eq: 3 } } ] }; const outputQuery = buildQuery(inputQuery); const expected = { a: { $eq: 1 }, $or: [ { b: { $eq: 2 } }, { c: { $eq: 3 } } ] }; expect(outputQuery).toEqual(expected); }); it('a || b || c starting at root $or operator of query', () => { const inputQuery: QueryFilter = { or: [ { a: { eq: 1 } }, { b: { eq: 2 } }, { c: { eq: 3 } } ] } const outputQuery = buildQuery(inputQuery); const expected = [ { a: { $eq: 1 } }, { b: { $eq: 2 } }, { c: { $eq: 3 } } ]; outputQuery.$or.forEach((q: any) => expect(expected).toContainEqual(q)) expect(Object.keys(outputQuery)).toEqual(['$or']); }); it('(a && b) && (c || c)', () => { const inputQuery: QueryFilter = { or: [ { a: { eq: 1 }, b: { eq: 2 }, or: [ { c: { eq: 3 } }, { c: { eq: 2 } } ] } ] } const outputQuery = buildQuery(inputQuery); const expected: FilterQuery<any> = { $or: [ { a: { $eq: 1 }, b: { $eq: 2 }, $or: [ { c: { $eq: 3 } }, { c: { $eq: 2 } } ] }, ] } expect(outputQuery).toEqual(expected); }) it('a && b && (c || b) from query root (explicit AND)', () => { const inputQuery: QueryFilter = { a: { eq: 1 }, and: [{ b: { eq: 2 } }], or: [ { c: { eq: 3 } }, { b: { eq: 4 } } ] } const outputQuery = buildQuery(inputQuery); const expected: FilterQuery<any> = { a: { $eq: 1, }, $and: [ { b: { $eq: 2 } } ], $or: [ { c: { $eq: 3 } }, { b: { $eq: 4 } } ] } expect(outputQuery).toEqual(expected); }) });
the_stack
import { toAsyncIterable } from "@esfx/async-iter-fromsync"; import { AsyncHierarchyIterable } from "@esfx/async-iter-hierarchy"; import { Equaler } from "@esfx/equatable"; import { identity } from "@esfx/fn"; import * as assert from "@esfx/internal-assert"; import { Grouping, HierarchyGrouping } from "@esfx/iter-grouping"; import { HierarchyIterable } from "@esfx/iter-hierarchy"; import { HierarchyPage, Page } from "@esfx/iter-page"; import { createGroupingsAsync, flowHierarchy } from "./internal/utils"; class AsyncPageByIterable<T, R> implements AsyncIterable<R> { private _source: AsyncIterable<T>; private _pageSize: number; private _pageSelector: (page: number, offset: number, values: Iterable<T>) => R; constructor(source: AsyncIterable<T>, pageSize: number, pageSelector: (page: number, offset: number, values: Iterable<T>) => R) { this._source = source; this._pageSize = pageSize; this._pageSelector = pageSelector; } async *[Symbol.asyncIterator](): AsyncIterator<R> { const source = this._source; const pageSize = this._pageSize; const pageSelector = this._pageSelector; let elements: T[] = []; let page = 0; for await (const value of this._source) { elements.push(value); if (elements.length >= pageSize) { yield pageSelector(page, page * pageSize, flowHierarchy(elements, source)); elements = []; page++; } } if (elements.length > 0) { yield pageSelector(page, page * pageSize, flowHierarchy(elements, source)); } } } /** * Creates an `AsyncIterable` that splits an `AsyncIterable` into one or more pages. * While advancing from page to page is evaluated lazily, the elements of the page are * evaluated eagerly. * * @param source An `AsyncIterable` object. * @param pageSize The number of elements per page. * @category Subquery */ export function pageByAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, pageSize: number): AsyncIterable<HierarchyPage<TNode, T>>; /** * Creates an `AsyncIterable` that splits an `AsyncIterable` into one or more pages. * While advancing from page to page is evaluated lazily, the elements of the page are * evaluated eagerly. * * @param source An `AsyncIterable` object. * @param pageSize The number of elements per page. * @param pageSelector A callback used to create a result for a page. * @category Subquery */ export function pageByAsync<TNode, T extends TNode, R>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, pageSize: number, pageSelector: (page: number, offset: number, values: HierarchyIterable<TNode, T>) => R): AsyncIterable<R>; /** * Creates an `AsyncIterable` that splits an `AsyncIterable` into one or more pages. * While advancing from page to page is evaluated lazily, the elements of the page are * evaluated eagerly. * * @param source An `AsyncIterable` object. * @param pageSize The number of elements per page. * @category Subquery */ export function pageByAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, pageSize: number): AsyncIterable<Page<T>>; /** * Creates an `AsyncIterable` that splits an `AsyncIterable` into one or more pages. * While advancing from page to page is evaluated lazily, the elements of the page are * evaluated eagerly. * * @param source An `AsyncIterable` object. * @param pageSize The number of elements per page. * @param pageSelector A callback used to create a result for a page. * @category Subquery */ export function pageByAsync<T, R>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, pageSize: number, pageSelector: (page: number, offset: number, values: Iterable<T>) => R): AsyncIterable<R>; export function pageByAsync<T, R>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, pageSize: number, pageSelector: ((page: number, offset: number, values: Iterable<T>) => Page<T> | R) | ((page: number, offset: number, values: HierarchyIterable<unknown, T>) => Page<T> | R) = Page.from): AsyncIterable<Page<T> | R> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBePositiveNonZeroFiniteNumber(pageSize, "pageSize"); assert.mustBeFunction(pageSelector, "pageSelector"); return new AsyncPageByIterable(flowHierarchy(toAsyncIterable(source), source), pageSize, pageSelector as (page: number, offset: number, values: Iterable<T>) => R); } class AsyncSpanMapIterable<T, K, V, R> implements AsyncIterable<R> { private _source: AsyncIterable<T>; private _keySelector: (element: T) => K; private _keyEqualer: Equaler<K>; private _elementSelector: (element: T) => PromiseLike<V> | V; private _spanSelector: (key: K, elements: Iterable<T | V>) => PromiseLike<R> | R; constructor(source: AsyncIterable<T>, keySelector: (element: T) => K, keyEqualer: Equaler<K>, elementSelector: (element: T) => PromiseLike<V> | V, spanSelector: (key: K, elements: Iterable<T | V>) => PromiseLike<R> | R) { this._source = source; this._keySelector = keySelector; this._keyEqualer = keyEqualer; this._elementSelector = elementSelector; this._spanSelector = spanSelector; } async *[Symbol.asyncIterator](): AsyncIterator<R> { const source = this._source; const keySelector = this._keySelector; const keyEqualer = this._keyEqualer; const elementSelector = this._elementSelector; const spanSelector = this._spanSelector; let span: (T | V)[] | undefined; let previousKey!: K; for await (const element of source) { const key = keySelector(element); if (!span) { previousKey = key; span = []; } else if (!keyEqualer.equals(previousKey, key)) { yield spanSelector(previousKey, elementSelector === identity ? flowHierarchy(span, source as AsyncIterable<T | V>) : span); span = []; previousKey = key; } span.push(await elementSelector(element)); } if (span) { yield spanSelector(previousKey, elementSelector === identity ? flowHierarchy(span, source as AsyncIterable<T | V>) : span); } } } /** * Creates a subquery whose elements are the contiguous ranges of elements that share the same key. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for an element. * @param keyEqualer An `Equaler` used to compare key equality. * @category Grouping */ export function spanMapAsync<TNode, T extends TNode, K>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncIterable<HierarchyGrouping<K, TNode, T>>; /** * Creates a subquery whose elements are the contiguous ranges of elements that share the same key. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for an element. * @param elementSelector A callback used to select a value for an element. * @param spanSelector A callback used to select a result from a contiguous range. * @param keyEqualer An `Equaler` used to compare key equality. * @category Grouping */ export function spanMapAsync<TNode, T extends TNode, K, R>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, keySelector: (element: T) => K, elementSelector: undefined, spanSelector: (key: K, elements: HierarchyIterable<TNode, T>) => R, keyEqualer?: Equaler<K>): AsyncIterable<R>; /** * Creates a subquery whose elements are the contiguous ranges of elements that share the same key. * * @param source An [[AsyncQueryable]] object. * @param keySelector A callback used to select the key for an element. * @param keyEqualer An `Equaler` used to compare key equality. * @category Subquery */ export function spanMapAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncIterable<Grouping<K, T>>; /** * Creates a subquery whose values are computed from each element of the contiguous ranges of elements that share the same key. * * @param source An [[AsyncQueryable]] object. * @param keySelector A callback used to select the key for an element. * @param elementSelector A callback used to select a value for an element. * @param keyEqualer An `Equaler` used to compare key equality. * @category Subquery */ export function spanMapAsync<T, K, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, keyEqualer?: Equaler<K>): AsyncIterable<Grouping<K, V>>; /** * Creates a subquery whose values are computed from the contiguous ranges of elements that share the same key. * * @param source An [[AsyncQueryable]] object. * @param keySelector A callback used to select the key for an element. * @param elementSelector A callback used to select a value for an element. * @param spanSelector A callback used to select a result from a contiguous range. * @param keyEqualer An `Equaler` used to compare key equality. * @category Subquery */ export function spanMapAsync<T, K, V, R>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, spanSelector: (key: K, elements: Iterable<V>) => PromiseLike<R> | R, keyEqualer?: Equaler<K>): AsyncIterable<R>; export function spanMapAsync<T, K, V, R>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, elementSelector: ((element: T) => PromiseLike<T | V> | T | V) | Equaler<K> = identity, spanSelector: ((key: K, span: Iterable<T | V>) => PromiseLike<Grouping<K, T | V> | R> | Grouping<K, T | V> | R) | ((key: K, span: HierarchyIterable<unknown, T>) => PromiseLike<Grouping<K, T | V> | R> | Grouping<K, T | V> | R) | Equaler<K> = Grouping.from, keyEqualer: Equaler<K> = Equaler.defaultEqualer): AsyncIterable<Grouping<K, T | V> | R> { if (typeof elementSelector === "object") { keyEqualer = elementSelector; elementSelector = identity; } if (typeof spanSelector === "object") { keyEqualer = spanSelector; spanSelector = Grouping.from; } assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeFunction(elementSelector, "elementSelector"); assert.mustBeFunction(spanSelector, "spanSelector"); assert.mustBeType(Equaler.hasInstance, keyEqualer, "keyEqualer"); return new AsyncSpanMapIterable(flowHierarchy(toAsyncIterable(source), source), keySelector, keyEqualer, elementSelector, spanSelector as (key: K, span: Iterable<T | V>) => PromiseLike<Grouping<K, T | V> | R> | Grouping<K, T | V> | R); } class AsyncGroupByIterable<T, K, V, R> implements AsyncIterable<R> { private _source: AsyncIterable<T>; private _keySelector: (element: T) => K; private _elementSelector: (element: T) => T | V | PromiseLike<T | V>; private _resultSelector: (key: K, elements: Iterable<T | V>) => PromiseLike<R> | R; private _keyEqualer?: Equaler<K> constructor(source: AsyncIterable<T>, keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, resultSelector: (key: K, elements: Iterable<T | V>) => PromiseLike<R> | R, keyEqualer?: Equaler<K>) { this._source = source; this._keySelector = keySelector; this._elementSelector = elementSelector; this._resultSelector = resultSelector; this._keyEqualer = keyEqualer; } async *[Symbol.asyncIterator](): AsyncIterator<R> { const source = this._source; const elementSelector = this._elementSelector; const resultSelector = this._resultSelector; const map = await createGroupingsAsync(source, this._keySelector, this._elementSelector, this._keyEqualer); for (const [key, values] of map) { yield resultSelector(key, elementSelector === identity ? flowHierarchy(values, source as AsyncIterable<T | V>) : values); } } } /** * Groups each element of an `AsyncIterable` by its key. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for an element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ export function groupByAsync<TNode, T extends TNode, K>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncIterable<HierarchyGrouping<K, TNode, T>>; /** * Groups each element of an `AsyncIterable` by its key. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for an element. * @param elementSelector A callback used to select a value for an element. * @param resultSelector A callback used to select a result from a group. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ export function groupByAsync<TNode, T extends TNode, K, R>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, keySelector: (element: T) => K, elementSelector: undefined, resultSelector: (key: K, elements: HierarchyIterable<TNode, T>) => R, keyEqualer?: Equaler<K>): AsyncIterable<R>; /** * Groups each element of an `AsyncIterable` by its key. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for an element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ export function groupByAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncIterable<Grouping<K, T>>; /** * Groups each element of an `AsyncIterable` by its key. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for an element. * @param elementSelector A callback used to select a value for an element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ export function groupByAsync<T, K, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, keyEqualer?: Equaler<K>): AsyncIterable<Grouping<K, V>>; /** * Groups each element of an `AsyncIterable` by its key. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for an element. * @param elementSelector A callback used to select a value for an element. * @param resultSelector A callback used to select a result from a group. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ export function groupByAsync<T, K, V, R>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, resultSelector: (key: K, elements: Iterable<V>) => PromiseLike<R> | R, keyEqualer?: Equaler<K>): AsyncIterable<R>; export function groupByAsync<T, K, V, R>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, elementSelector: ((element: T) => PromiseLike<T | V> | T | V) | Equaler<K> = identity, resultSelector: ((key: K, elements: Iterable<T | V>) => PromiseLike<Grouping<K, T | V> | R> | Grouping<K, T | V> | R) | ((key: K, elements: HierarchyIterable<unknown, T>) => PromiseLike<Grouping<K, T | V> | R> | Grouping<K, T | V> | R) | Equaler<K> = Grouping.from, keyEqualer?: Equaler<K>): AsyncIterable<Grouping<K, T | V> | R> { if (typeof elementSelector !== "function") { resultSelector = elementSelector; elementSelector = identity; } if (typeof resultSelector !== "function") { keyEqualer = resultSelector; resultSelector = Grouping.from; } assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeFunction(elementSelector, "elementSelector"); assert.mustBeFunction(resultSelector, "resultSelector"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer"); return new AsyncGroupByIterable(flowHierarchy(toAsyncIterable(source), source), keySelector, elementSelector, resultSelector as (key: K, elements: Iterable<T | V>) => PromiseLike<Grouping<K, T | V> | R> | Grouping<K, T | V> | R); }
the_stack
declare module 'aurelia-validation' { import { metadata } from 'aurelia-metadata'; import { inject } from 'aurelia-dependency-injection'; import { customAttribute } from 'aurelia-templating'; import { ObserverLocator } from 'aurelia-binding'; export class Debouncer { constructor(debounceTimeout: any); debounce(func: any): any; } export class ValidationMetadata { static metadataKey: any; constructor(); getOrCreateProperty(propertyName: any): any; setup(validation: any): any; } class ValidationPropertyMetadata { constructor(propertyName: any); addSetupStep(setupStep: any): any; setup(validation: any): any; } export function ensure(setupStep: any): any; export class PathObserver { constructor(observerLocator: any, subject: any, path: any); // TODO: this should be replaced with reuse of the Binding system observeParts(propertyName: any): any; observePart(part: any): any; getObserver(): any; getValue(): any; subscribe(callback: any): any; unsubscribe(): any; } export class Utilities { static getValue(val: any): any; static isEmptyValue(val: any): any; } export class ValidateCustomAttribute { constructor(element: any); valueChanged(newValue: any): any; // this is just to tell the real validation instance (higher in the DOM) the exact property-path to bind to subscribeChangedHandlers(currentElement: any): any; attached(): any; } export class ValidationConfigDefaults { } export class ValidationConfig { constructor(innerConfig: any); getValue(identifier: any): any; setValue(identifier: any, value: any): any; // fluent API onLocaleChanged(callback: any): any; getDebounceTimeout(): any; useDebounceTimeout(value: any): any; getDependencies(): any; computedFrom(dependencies: any): any; useLocale(localeIdentifier: any): any; locale(): any; useViewStrategy(viewStrategy: any): any; getViewStrategy(): any; treatAllPropertiesAsMandatory(): any; treatAllPropertiesAsOptional(): any; } export class ValidationGroupBuilder { constructor(observerLocator: any, validationGroup: any); ensure(propertyName: any, configurationCallback: any): any; isNotEmpty(): any; canBeEmpty(): any; isGreaterThan(minimumValue: any): any; isGreaterThanOrEqualTo(minimumValue: any): any; isBetween(minimumValue: any, maximumValue: any): any; isIn(collection: any): any; isLessThan(maximumValue: any): any; isLessThanOrEqualTo(maximumValue: any): any; isEqualTo(otherValue: any, otherValueLabel: any): any; isNotEqualTo(otherValue: any, otherValueLabel: any): any; isEmail(): any; isURL(): any; hasMinLength(minimumValue: any): any; hasMaxLength(maximumValue: any): any; hasLengthBetween(minimumValue: any, maximumValue: any): any; isNumber(): any; containsNoSpaces(): any; containsOnlyDigits(): any; containsOnlyAlpha(): any; containsOnlyAlphaOrWhitespace(): any; containsOnlyAlphanumerics(): any; containsOnlyAlphanumericsOrWhitespace(): any; isStrongPassword(minimumComplexityLevel: any): any; containsOnly(regex: any): any; matches(regex: any): any; passes(customFunction: any, threshold: any): any; passesRule(validationRule: any): any; checkLast(): any; withMessage(message: any): any; if(conditionExpression: any): any; else(): any; endIf(): any; switch(conditionExpression: any): any; case(caseLabel: any): any; default(): any; endSwitch(): any; } /** * Encapsulates validation rules and their current validation state for a given subject * @class ValidationGroup * @constructor */ export class ValidationGroup { /** * Instantiates a new {ValidationGroup} * @param subject The subject to evaluate * @param observerLocator The observerLocator used to monitor changes on the subject * @param config The configuration */ constructor(subject: any, observerLocator: any, config: any); destroy(): any; // TODO: what else needs to be done for proper cleanup? clear(): any; onBreezeEntity(): any; /** * Causes complete re-evaluation: gets the latest value, marks the property as 'dirty' (unless false is passed), runs validation rules asynchronously and updates this.result * @returns {Promise} A promise that fulfils when valid, rejects when invalid. */ validate(forceDirty?: any, forceExecution?: any): any; onValidate(validationFunction: any, validationFunctionFailedCallback: any): any; onPropertyValidate(validationFunction: any): any; /** * Adds a validation property for the specified path * @param {String} bindingPath the path of the property/field, for example 'firstName' or 'address.muncipality.zipCode' * @param configCallback a configuration callback * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ ensure(bindingPath: any, configCallback: any): any; /** * Adds a validation rule that checks a value for being 'isNotEmpty', 'required' * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ isNotEmpty(): any; /** * Adds a validation rule that allows a value to be empty/null * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ canBeEmpty(): any; /** * Adds a validation rule that checks a value for being greater than or equal to a threshold * @param minimumValue the threshold * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ isGreaterThanOrEqualTo(minimumValue: any): any; /** * Adds a validation rule that checks a value for being greater than a threshold * @param minimumValue the threshold * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ isGreaterThan(minimumValue: any): any; /** * Adds a validation rule that checks a value for being greater than or equal to a threshold, and less than or equal to another threshold * @param minimumValue The minimum threshold * @param maximumValue The isLessThanOrEqualTo threshold * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ isBetween(minimumValue: any, maximumValue: any): any; /** * Adds a validation rule that checks a value for being less than a threshold * @param maximumValue The threshold * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ isLessThanOrEqualTo(maximumValue: any): any; /** * Adds a validation rule that checks a value for being less than or equal to a threshold * @param maximumValue The threshold * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ isLessThan(maximumValue: any): any; /** * Adds a validation rule that checks a value for being equal to a threshold * @param otherValue The threshold * @param otherValueLabel Optional: a label to use in the validation message * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ isEqualTo(otherValue: any, otherValueLabel: any): any; /** * Adds a validation rule that checks a value for not being equal to a threshold * @param otherValue The threshold * @param otherValueLabel Optional: a label to use in the validation message * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ isNotEqualTo(otherValue: any, otherValueLabel: any): any; /** * Adds a validation rule that checks a value for being a valid isEmail address * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ isEmail(): any; /** * Adds a validation rule that checks a value for being a valid URL * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ isURL(): any; /** * Adds a validation rule that checks a value for being equal to at least one other value in a particular collection * @param collection The threshold * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ isIn(collection: any): any; /** * Adds a validation rule that checks a value for having a length greater than or equal to a specified threshold * @param minimumValue The threshold * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ hasMinLength(minimumValue: any): any; /** * Adds a validation rule that checks a value for having a length less than a specified threshold * @param maximumValue The threshold * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ hasMaxLength(maximumValue: any): any; /** * Adds a validation rule that checks a value for having a length greater than or equal to a specified threshold and less than another threshold * @param minimumValue The min threshold * @param maximumValue The max threshold * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ hasLengthBetween(minimumValue: any, maximumValue: any): any; /** * Adds a validation rule that checks a value for being numeric, this includes formatted numbers like '-3,600.25' * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ isNumber(): any; /** * Adds a validation rule that checks a value for containing not a single whitespace * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ containsNoSpaces(): any; /** * Adds a validation rule that checks a value for being strictly numeric, this excludes formatted numbers like '-3,600.25' * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ containsOnlyDigits(): any; containsOnly(regex: any): any; containsOnlyAlpha(): any; containsOnlyAlphaOrWhitespace(): any; containsOnlyLetters(): any; containsOnlyLettersOrWhitespace(): any; /** * Adds a validation rule that checks a value for only containing alphanumerical characters * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ containsOnlyAlphanumerics(): any; /** * Adds a validation rule that checks a value for only containing alphanumerical characters or whitespace * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ containsOnlyAlphanumericsOrWhitespace(): any; /** * Adds a validation rule that checks a value for being a strong password. A strong password contains at least the specified of the following groups: lowercase characters, uppercase characters, digits and special characters. * @param minimumComplexityLevel {Number} Optionally, specifiy the number of groups to match. Default is 4. * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ isStrongPassword(minimumComplexityLevel: any): any; /** * Adds a validation rule that checks a value for matching a particular regex * @param regex the regex to match * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ matches(regex: any): any; /** * Adds a validation rule that checks a value for passing a custom function * @param customFunction {Function} The custom function that needs to pass, that takes two arguments: newValue (the value currently being evaluated) and optionally: threshold, and returns true/false. * @param threshold {Object} An optional threshold that will be passed to the customFunction * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ passes(customFunction: any, threshold: any): any; /** * Adds the {ValidationRule} * @param validationRule {ValudationRule} The rule that needs to pass * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ passesRule(validationRule: any): any; /** * Specifies that the next validation rules only need to be evaluated when the specified conditionExpression is true * @param conditionExpression {Function} a function that returns true of false. * @param threshold {Object} an optional treshold object that is passed to the conditionExpression * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ if(conditionExpression: any, threshold: any): any; /** * Specifies that the next validation rules only need to be evaluated when the previously specified conditionExpression is false. * See: if (conditionExpression, threshold) * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ else(): any; /** * Specifies that the execution of next validation rules no longer depend on the the previously specified conditionExpression. * See: if (conditionExpression, threshold) * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ endIf(): any; /** * Specifies that the next validation rules only need to be evaluated when they are preceded by a case that matches the conditionExpression * @param conditionExpression {Function} a function that returns a case label to execute. This is optional, when omitted the case label will be matched using the underlying property's value * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ switch(conditionExpression: any): any; /** * Specifies that the next validation rules only need to be evaluated when the caseLabel matches the value returned by a preceding switch statement * See: switch(conditionExpression) * @param caseLabel {Object} the case label * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ case(caseLabel: any): any; /** * Specifies that the next validation rules only need to be evaluated when not other caseLabel matches the value returned by a preceding switch statement * See: switch(conditionExpression) * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ default(): any; /** * Specifies that the execution of next validation rules no longer depend on the the previously specified conditionExpression. * See: switch(conditionExpression) * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ endSwitch(): any; /** * Specifies that the execution of the previous validation rule should use the specified error message if it fails * @param message either a static string or a function that takes two arguments: newValue (the value that has been evaluated) and threshold. * @returns {ValidationGroup} returns this ValidationGroup, to enable fluent API */ withMessage(message: any): any; } export class ValidationLocale { constructor(defaults: any, data: any); getValueFor(identifier: any, category: any): any; setting(settingIdentifier: any): any; translate(translationIdentifier: any, newValue: any, threshold: any): any; } class ValidationLocaleRepository { constructor(); load(localeIdentifier: any, basePath: any): any; addLocale(localeIdentifier: any, data: any): any; } export class ValidationProperty { constructor(observerLocator: any, propertyName: any, validationGroup: any, propertyResult: any, config: any); addValidationRule(validationRule: any): any; validateCurrentValue(forceDirty: any, forceExecution: any): any; clear(): any; destroy(): any; // TODO: what else needs to be done for proper cleanup? /** * returns a promise that fulfils and resolves to true/false */ validate(newValue: any, shouldBeDirty: any, forceExecution: any): any; } export class ValidationResult { constructor(); addProperty(name: any): any; checkValidity(): any; clear(): any; } export class ValidationResultProperty { constructor(group: any); clear(): any; onValidate(onValidateCallback: any): any; notifyObserversOfChange(): any; setValidity(validationResponse: any, shouldBeDirty: any): any; } export class ValidationRulesCollection { constructor(config: any); /** * Returns a promise that fulfils and resolves to simple result status object. */ validate(newValue: any, locale: any): any; addValidationRule(validationRule: any): any; addValidationRuleCollection(validationRulesCollection: any): any; isNotEmpty(): any; canBeEmpty(): any; withMessage(message: any): any; } export class SwitchCaseValidationRulesCollection { constructor(conditionExpression: any, config: any); case(caseLabel: any): any; // force creation default(): any; getCurrentCollection(caseLabel: any, createIfNotExists?: any): any; validate(newValue: any, locale: any): any; addValidationRule(validationRule: any): any; addValidationRuleCollection(validationRulesCollection: any): any; isNotEmpty(): any; canBeEmpty(): any; withMessage(message: any): any; } export class ValidationRule { constructor(threshold: any, onValidate: any, message: any, ruleName: any); withMessage(message: any): any; explain(): any; setResult(result: any, currentValue: any, locale: any): any; /** * Validation rules: return a promise that fulfills and resolves to true/false */ validate(currentValue: any, locale: any): any; } export class URLValidationRule extends ValidationRule { // https://github.com/chriso/validator.js/blob/master/LICENSE static isIP(str: any, version: any): any; static isFQDN(str: any, options: any): any; // threshold here renamed to startingThreshold because linter was mad, // probably not the best name constructor(startingThreshold: any); } export class EmailValidationRule extends ValidationRule { // https://github.com/chriso/validator.js/blob/master/LICENSE static testEmailUserUtf8Regex(user: any): any; static isFQDN(str: any): any; constructor(); } export class MinimumLengthValidationRule extends ValidationRule { constructor(minimumLength: any); } export class MaximumLengthValidationRule extends ValidationRule { constructor(maximumLength: any); } export class BetweenLengthValidationRule extends ValidationRule { constructor(minimumLength: any, maximumLength: any); } export class CustomFunctionValidationRule extends ValidationRule { constructor(customFunction: any, threshold: any); } export class NumericValidationRule extends ValidationRule { constructor(); } export class RegexValidationRule extends ValidationRule { constructor(startingRegex: any, ruleName: any); } export class ContainsOnlyValidationRule extends RegexValidationRule { constructor(regex: any); } export class MinimumValueValidationRule extends ValidationRule { constructor(minimumValue: any); } export class MinimumInclusiveValueValidationRule extends ValidationRule { constructor(minimumValue: any); } export class MaximumValueValidationRule extends ValidationRule { constructor(maximumValue: any); } export class MaximumInclusiveValueValidationRule extends ValidationRule { constructor(maximumValue: any); } export class BetweenValueValidationRule extends ValidationRule { constructor(minimumValue: any, maximumValue: any); } export class DigitValidationRule extends ValidationRule { constructor(); } export class NoSpacesValidationRule extends ValidationRule { constructor(); } export class AlphaNumericValidationRule extends ValidationRule { constructor(); } export class AlphaValidationRule extends ValidationRule { constructor(); } export class AlphaOrWhitespaceValidationRule extends ValidationRule { constructor(); } export class AlphaNumericOrWhitespaceValidationRule extends ValidationRule { constructor(); } export class MediumPasswordValidationRule extends ValidationRule { constructor(minimumComplexityLevel: any, ruleName: any); } export class StrongPasswordValidationRule extends MediumPasswordValidationRule { constructor(); } export class EqualityValidationRuleBase extends ValidationRule { constructor(startingOtherValue: any, equality: any, otherValueLabel: any, ruleName: any); } export class EqualityValidationRule extends EqualityValidationRuleBase { constructor(otherValue: any); } export class EqualityWithOtherLabelValidationRule extends EqualityValidationRuleBase { constructor(otherValue: any, otherLabel: any); } export class InEqualityValidationRule extends EqualityValidationRuleBase { constructor(otherValue: any); } export class InEqualityWithOtherLabelValidationRule extends EqualityValidationRuleBase { constructor(otherValue: any, otherLabel: any); } export class InCollectionValidationRule extends ValidationRule { constructor(startingCollection: any); } export class ValidationViewStrategy { constructor(); getValidationProperty(validation: any, element: any): any; prepareElement(validationProperty: any, element: any): any; updateElement(validationProperty: any, element: any): any; } /** * A lightweight validation plugin * @class Validation * @constructor */ export class Validation { /** * Instantiates a new {Validation} * @param observerLocator the observerLocator used to observer properties * @param validationConfig the configuration */ constructor(observerLocator: any, validationConfig: any); /** * Returns a new validation group on the subject * @param subject The subject to validate * @returns {ValidationGroup} A ValidationGroup that encapsulates the validation rules and current validation state for this subject */ on(subject: any, configCallback: any): any; onBreezeEntity(breezeEntity: any, configCallback: any): any; } export class TWBootstrapViewStrategyBase extends ValidationViewStrategy { constructor(appendMessageToInput: any, appendMessageToLabel: any, helpBlockClass: any); searchFormGroup(currentElement: any, currentDepth: any): any; findLabels(formGroup: any, inputId: any): any; findLabelsRecursively(currentElement: any, inputId: any, currentLabels: any, currentDepth: any): any; appendMessageToElement(element: any, validationProperty: any): any; appendUIVisuals(validationProperty: any, currentElement: any): any; prepareElement(validationProperty: any, element: any): any; updateElement(validationProperty: any, element: any): any; } export class TWBootstrapViewStrategy { } }
the_stack
import { CompressedStreamWriter } from './compression-writer'; import { Save } from '@syncfusion/ej2-file-utils'; const CRC32TABLE: number[] = []; /** * class provide compression library * ```typescript * let archive = new ZipArchive(); * archive.compressionLevel = 'Normal'; * let archiveItem = new ZipArchiveItem(archive, 'directoryName\fileName.txt'); * archive.addItem(archiveItem); * archive.save(fileName.zip); * ``` */ export class ZipArchive { private files: (ZipArchiveItem | string)[]; private level: CompressionLevel; /** * gets compression level */ get compressionLevel(): CompressionLevel { return this.level; } /** * sets compression level */ set compressionLevel(level: CompressionLevel) { this.level = level; } /** * gets items count */ get length(): number { if (this.files === undefined) { return 0; } return this.files.length; } /** * constructor for creating ZipArchive instance */ constructor() { if (CRC32TABLE.length === 0) { ZipArchive.initCrc32Table(); } this.files = []; this.level = 'Normal'; Save.isMicrosoftBrowser = !(!navigator.msSaveBlob); } /** * add new item to archive * @param {ZipArchiveItem} item - item to be added * @returns {void} */ public addItem(item: ZipArchiveItem): void { if (item === null || item === undefined) { throw new Error('ArgumentException: item cannot be null or undefined'); } for (let i: number = 0; i < this.files.length; i++) { let file: ZipArchiveItem = this.files[i] as ZipArchiveItem; if (file instanceof ZipArchiveItem) { if (file.name === item.name) { throw new Error('item with same name already exist'); } } } this.files.push(item as ZipArchiveItem); } /** * add new directory to archive * @param directoryName directoryName to be created * @returns {void} */ public addDirectory(directoryName: string): void { if (directoryName === null || directoryName === undefined) { throw new Error('ArgumentException: string cannot be null or undefined'); } if (directoryName.length === 0) { throw new Error('ArgumentException: string cannot be empty'); } if (directoryName.slice(-1) !== '/') { directoryName += '/'; } if (this.files.indexOf(directoryName) !== -1) { throw new Error('item with same name already exist'); } this.files.push(directoryName as string); } /** * gets item at specified index * @param {number} index - item index * @returns {ZipArchiveItem} */ public getItem(index: number): ZipArchiveItem { if (index >= 0 && index < this.files.length) { return this.files[index] as ZipArchiveItem; } return undefined; } /** * determines whether an element is in the collection * @param {string | ZipArchiveItem} item - item to search * @returns {boolean} */ public contains(item: string | ZipArchiveItem): boolean { return this.files.indexOf(item) !== -1 ? true : false; } /** * save archive with specified file name * @param {string} fileName save archive with specified file name * @returns {Promise<ZipArchive>} */ public save(fileName: string): Promise<ZipArchive> { if (fileName === null || fileName === undefined || fileName.length === 0) { throw new Error('ArgumentException: fileName cannot be null or undefined'); } if (this.files.length === 0) { throw new Error('InvalidOperation'); } let zipArchive: ZipArchive = this; let promise: Promise<ZipArchive>; return promise = new Promise((resolve: Function, reject: Function) => { zipArchive.saveInternal(fileName, false).then(() => { resolve(zipArchive); }); }); } /** * Save archive as blob * @return {Promise<Blob>} */ public saveAsBlob(): Promise<Blob> { let zipArchive: ZipArchive = this; let promise: Promise<Blob>; return promise = new Promise((resolve: Function, reject: Function) => { zipArchive.saveInternal('', true).then((blob: Blob) => { resolve(blob); }); }); } private saveInternal(fileName: string, skipFileSave: boolean): Promise<Blob> { let zipArchive: ZipArchive = this; let promise: Promise<Blob>; return promise = new Promise((resolve: Function, reject: Function) => { let zipData: ZippedObject[] = []; let dirLength: number = 0; for (let i: number = 0; i < zipArchive.files.length; i++) { let compressedObject: Promise<CompressedData> = this.getCompressedData(this.files[i]); compressedObject.then((data: CompressedData) => { dirLength = zipArchive.constructZippedObject(zipData, data, dirLength, data.isDirectory); if (zipData.length === zipArchive.files.length) { let blob: Blob = zipArchive.writeZippedContent(fileName, zipData, dirLength, skipFileSave); resolve(blob); } }); } }); } /** * release allocated un-managed resource * @returns {void} */ public destroy(): void { if (this.files !== undefined && this.files.length > 0) { for (let i: number = 0; i < this.files.length; i++) { let file: ZipArchiveItem | string = this.files[i]; if (file instanceof ZipArchiveItem) { (file as ZipArchiveItem).destroy(); } file = undefined; } this.files = []; } this.files = undefined; this.level = undefined; } private getCompressedData(item: ZipArchiveItem | string): Promise<CompressedData> { let zipArchive: ZipArchive = this; let promise: Promise<CompressedData> = new Promise((resolve: Function, reject: Function) => { if (item instanceof ZipArchiveItem) { let reader: FileReader = new FileReader(); reader.onload = () => { let input: Uint8Array = new Uint8Array(reader.result as ArrayBuffer); let data: CompressedData = { fileName: item.name, crc32Value: 0, compressedData: [], compressedSize: undefined, uncompressedDataSize: input.length, compressionType: undefined, isDirectory: false }; if (zipArchive.level === 'Normal') { zipArchive.compressData(input, data, CRC32TABLE); let length: number = 0; for (let i: number = 0; i < data.compressedData.length; i++) { length += data.compressedData[i].length; } data.compressedSize = length; data.compressionType = '\x08\x00'; //Deflated = 8 } else { data.compressedSize = input.length; data.crc32Value = zipArchive.calculateCrc32Value(0, input, CRC32TABLE); data.compressionType = '\x00\x00'; // Stored = 0 (data.compressedData as Uint8Array[]).push(input); } resolve(data); }; reader.readAsArrayBuffer(item.data as Blob); } else { let data: CompressedData = { fileName: item as string, crc32Value: 0, compressedData: '', compressedSize: 0, uncompressedDataSize: 0, compressionType: '\x00\x00', isDirectory: true }; resolve(data); } }); return promise; } private compressData(input: Uint8Array, data: CompressedData, crc32Table: number[]): void { let compressor: CompressedStreamWriter = new CompressedStreamWriter(true); let currentIndex: number = 0; let nextIndex: number = 0; do { if (currentIndex >= input.length) { compressor.close(); break; } nextIndex = Math.min(input.length, currentIndex + 16384); let subArray: Uint8Array = input.subarray(currentIndex, nextIndex); data.crc32Value = this.calculateCrc32Value(data.crc32Value, subArray, crc32Table); compressor.write(subArray, 0, nextIndex - currentIndex); currentIndex = nextIndex; } while (currentIndex <= input.length); data.compressedData = compressor.compressedData; compressor.destroy(); } private constructZippedObject(zipParts: ZippedObject[], data: CompressedData, dirLength: number, isDirectory: boolean): number { let extFileAttr: number = 0; let date: Date = new Date(); if (isDirectory) { extFileAttr = extFileAttr | 0x00010; // directory flag } extFileAttr = extFileAttr | (0 & 0x3F); let header: string = this.writeHeader(data, date); let localHeader: string = 'PK\x03\x04' + header + data.fileName; let centralDir: string = this.writeCentralDirectory(data, header, dirLength, extFileAttr); zipParts.push({ localHeader: localHeader, centralDir: centralDir, compressedData: data }); return dirLength + localHeader.length + data.compressedSize; } private writeHeader(data: CompressedData, date: Date): string { let zipHeader: string = ''; zipHeader += '\x0A\x00' + '\x00\x00'; // version needed to extract & general purpose bit flag zipHeader += data.compressionType; // compression method Deflate=8,Stored=0 zipHeader += this.getBytes(this.getModifiedTime(date), 2); // last modified Time zipHeader += this.getBytes(this.getModifiedDate(date), 2); // last modified date zipHeader += this.getBytes(data.crc32Value, 4); // crc-32 value zipHeader += this.getBytes(data.compressedSize, 4); // compressed file size zipHeader += this.getBytes(data.uncompressedDataSize, 4); // uncompressed file size zipHeader += this.getBytes(data.fileName.length, 2); // file name length zipHeader += this.getBytes(0, 2); // extra field length return zipHeader; } private writeZippedContent(fileName: string, zipData: ZippedObject[], localDirLen: number, skipFileSave: boolean): Blob { let cenDirLen: number = 0; let buffer: ArrayBuffer[] = []; for (let i: number = 0; i < zipData.length; i++) { let item: ZippedObject = zipData[i]; cenDirLen += item.centralDir.length; buffer.push(this.getArrayBuffer(item.localHeader)); while (item.compressedData.compressedData.length) { buffer.push((item.compressedData.compressedData as Uint8Array[]).shift().buffer); } } for (let i: number = 0; i < zipData.length; i++) { buffer.push(this.getArrayBuffer(zipData[i].centralDir)); } buffer.push(this.getArrayBuffer(this.writeFooter(zipData, cenDirLen, localDirLen))); let blob: Blob = new Blob(buffer, { type: 'application/zip' }); if (!skipFileSave) { Save.save(fileName, blob); } return blob; } private writeCentralDirectory(data: CompressedData, localHeader: string, offset: number, externalFileAttribute: number): string { let directoryHeader: string = 'PK\x01\x02' + this.getBytes(0x0014, 2) + localHeader + // inherit from file header this.getBytes(0, 2) + // comment length '\x00\x00' + '\x00\x00' + // internal file attributes this.getBytes(externalFileAttribute, 4) + // external file attributes this.getBytes(offset, 4) + // local fileHeader relative offset data.fileName; return directoryHeader; } private writeFooter(zipData: ZippedObject[], centralLength: number, localLength: number): string { let dirEnd: string = 'PK\x05\x06' + '\x00\x00' + '\x00\x00' + this.getBytes(zipData.length, 2) + this.getBytes(zipData.length, 2) + this.getBytes(centralLength, 4) + this.getBytes(localLength, 4) + this.getBytes(0, 2); return dirEnd; } private getArrayBuffer(input: string): ArrayBuffer { let a: Uint8Array = new Uint8Array(input.length); for (let j: number = 0; j < input.length; ++j) { a[j] = input.charCodeAt(j) & 0xFF; } return a.buffer; } private getBytes(value: number, offset: number): string { let bytes: string = ''; for (let i: number = 0; i < offset; i++) { bytes += String.fromCharCode(value & 0xff); value = value >>> 8; } return bytes; } private getModifiedTime(date: Date): number { let modTime: number = date.getHours(); modTime = modTime << 6; modTime = modTime | date.getMinutes(); modTime = modTime << 5; return modTime = modTime | date.getSeconds() / 2; } private getModifiedDate(date: Date): number { let modiDate: number = date.getFullYear() - 1980; modiDate = modiDate << 4; modiDate = modiDate | (date.getMonth() + 1); modiDate = modiDate << 5; return modiDate = modiDate | date.getDate(); } private calculateCrc32Value(crc32Value: number, input: Uint8Array, crc32Table: number[]): number { crc32Value ^= -1; for (let i: number = 0; i < input.length; i++) { crc32Value = (crc32Value >>> 8) ^ crc32Table[(crc32Value ^ input[i]) & 0xFF]; } return (crc32Value ^ (-1)); } /** * construct cyclic redundancy code table * @private */ public static initCrc32Table(): void { let i: number; for (let j: number = 0; j < 256; j++) { i = j; for (let k: number = 0; k < 8; k++) { i = ((i & 1) ? (0xEDB88320 ^ (i >>> 1)) : (i >>> 1)); } CRC32TABLE[j] = i; } } } /** * Class represent unique ZipArchive item * ```typescript * let archiveItem = new ZipArchiveItem(archive, 'directoryName\fileName.txt'); * ``` */ export class ZipArchiveItem { public data: Blob | ArrayBuffer; private fileName: string; /** * Get the name of archive item * @returns string */ get name(): string { return this.fileName; } /** * Set the name of archive item * @param {string} value */ set name(value: string) { this.fileName = value; } /** * constructor for creating {ZipArchiveItem} instance * @param {Blob|ArrayBuffer} data file data * @param {itemName} itemName absolute file path */ constructor(data: Blob | ArrayBuffer, itemName: string) { if (data === null || data === undefined) { throw new Error('ArgumentException: data cannot be null or undefined'); } if (itemName === null || itemName === undefined) { throw new Error('ArgumentException: string cannot be null or undefined'); } if (itemName.length === 0) { throw new Error('string cannot be empty'); } this.data = data; this.name = itemName; } /** * release allocated un-managed resource * @returns {void} */ public destroy(): void { this.fileName = undefined; this.data = undefined; } } export interface CompressedData { fileName: string; compressedData: Uint8Array[] | string; uncompressedDataSize: number; compressedSize: number; crc32Value: number; compressionType: string; isDirectory: boolean; } export interface ZippedObject { localHeader: string; centralDir: string; compressedData: CompressedData; } /** * Compression level. */ export type CompressionLevel = /* Pack without compression */ 'NoCompression' | /* Use normal compression, middle between speed and size*/ 'Normal';
the_stack
namespace fgui { export type AssetTypes = PIXI.Texture | BitmapFont | Frame[] | utils.XmlNode | PIXI.loaders.Resource; type UIPackageDictionary = { [key: string]: UIPackage } type PackageItemDictionary = { [key: string]: PackageItem } type BitmapFontDictionary = { [key: string]: BitmapFont } type ResDataDictionary = { [key: string]: string } class AtlasConfig { public atlasName: string; public texCacheID: string; public frame: PIXI.Rectangle; public orig: PIXI.Rectangle; public trim: PIXI.Rectangle; public rotate: number; public constructor(atlasName:string, frame?:PIXI.Rectangle, orig?:PIXI.Rectangle, trim?:PIXI.Rectangle, rotate?:number) { this.atlasName = atlasName; this.frame = frame; this.orig = orig; this.trim = trim; this.rotate = rotate; } } type AtlasDictionary = { [key: string]: AtlasConfig } type StringSource = { [key: string]: string } type StringSourceMap = { [key: string]: StringSource } export class UIPackage { private $id: string; private $name: string; private $resKey: string; private $items: PackageItem[]; private $itemsById: PackageItemDictionary; private $itemsByName: PackageItemDictionary; private $resData: ResDataDictionary; private $customId: string; private $atlasConfigs: AtlasDictionary; /**@internal */ static $constructingObjects: number = 0; private static $packageInstById: UIPackageDictionary = {}; private static $packageInstByName: UIPackageDictionary = {}; private static $bitmapFonts: BitmapFontDictionary = {}; private static $stringsSource: StringSourceMap = null; private static sep0: string = ","; private static sep1: string = "\n"; private static sep2: string = " "; private static sep3: string = "="; public constructor() { this.$items = []; this.$atlasConfigs = {}; } public static getById(id: string): UIPackage { return UIPackage.$packageInstById[id]; } public static getByName(name: string): UIPackage { return UIPackage.$packageInstByName[name]; } public static addPackage(resKey: string): UIPackage { let pkg: UIPackage = new UIPackage(); pkg.create(resKey); UIPackage.$packageInstById[pkg.id] = pkg; UIPackage.$packageInstByName[pkg.name] = pkg; pkg.customId = resKey; return pkg; } public static removePackage(packageId: string): void { let pkg: UIPackage = UIPackage.$packageInstById[packageId]; pkg.dispose(); delete UIPackage.$packageInstById[pkg.id]; if (pkg.$customId != null) delete UIPackage.$packageInstById[pkg.$customId]; delete UIPackage.$packageInstByName[pkg.name]; } public static createObject(pkgName: string, resName: string, userClass?: { new():GObject }): GObject { let pkg: UIPackage = UIPackage.getByName(pkgName); if (pkg) return pkg.createObject(resName, userClass); else return null; } public static createObjectFromURL(url: string, userClass?: { new():GObject }): GObject { let pi: PackageItem = UIPackage.getItemByURL(url); if (pi) return pi.owner.internalCreateObject(pi, userClass); else return null; } public static getItemURL(pkgName: string, resName: string): string { let pkg: UIPackage = UIPackage.getByName(pkgName); if (!pkg) return null; let pi: PackageItem = pkg.$itemsByName[resName]; if (!pi) return null; return `ui://${pkg.id}${pi.id}`; } public static getItemByURL(url: string): PackageItem { let pos1: number = url.indexOf("//"); if (pos1 == -1) return null; let pos2: number = url.indexOf("/", pos1 + 2); let pkg: UIPackage; if (pos2 == -1) { if (url.length > 13) { let pkgId: string = url.substr(5, 8); pkg = UIPackage.getById(pkgId); if (pkg != null) { let srcId: string = url.substr(13); return pkg.getItemById(srcId); } } } else { let pkgName: string = url.substr(pos1 + 2, pos2 - pos1 - 2); pkg = UIPackage.getByName(pkgName); if (pkg != null) { let srcName: string = url.substr(pos2 + 1); return pkg.getItemByName(srcName); } } return null; } public static getBitmapFontByURL(url: string): BitmapFont { return UIPackage.$bitmapFonts[url]; } public static setStringsSource(source: string): void { UIPackage.$stringsSource = {}; let xmlroot: utils.XmlNode = utils.XmlParser.tryParse(source); xmlroot.children.forEach(cxml => { if (cxml.nodeName == "string") { let key: string = cxml.attributes.name; let i: number = key.indexOf("-"); if (i == -1) return; let text: string = cxml.children.length > 0 ? cxml.children[0].text : ""; let key2: string = key.substr(0, i); let key3: string = key.substr(i + 1); let col: StringSource = UIPackage.$stringsSource[key2]; if (!col) { col = {}; UIPackage.$stringsSource[key2] = col; } col[key3] = text; } }); } /** * format the URL from old version to new version * @param url url with old version format */ public static normalizeURL(url: string): string { if (url == null) return null; let pos1: number = url.indexOf("//"); if (pos1 == -1) return null; let pos2: number = url.indexOf("/", pos1 + 2); if (pos2 == -1) return url; let pkgName: string = url.substr(pos1 + 2, pos2 - pos1 - 2); let srcName: string = url.substr(pos2 + 1); return UIPackage.getItemURL(pkgName, srcName); } private create(resKey: string): void { this.$resKey = resKey; let buf: PIXI.loaders.Resource = utils.AssetLoader.resourcesPool[this.$resKey]; if (!buf) buf = utils.AssetLoader.resourcesPool[`${this.$resKey}_fui`]; if (!buf) throw new Error(`Resource '${this.$resKey}' not found, please make sure that you use "new fgui.utils.AssetLoader" to load resources instead of " PIXI.loaders.Loader".`); if (!buf.data || !(buf.data instanceof ArrayBuffer)) throw new Error(`Resource '${this.$resKey}' is not a proper binary resource, please load it as binary format by calling yourLoader.add(name, url, { loadType:PIXI.loaders.Resource.LOAD_TYPE.XHR, xhrType: PIXI.loaders.Resource.XHR_RESPONSE_TYPE.BUFFER })`); this.decompressPackage(buf.data); let str = this.getResDescriptor("sprites.bytes"); str && str.split(UIPackage.sep1).forEach((str, index) => { if(index >= 1 && str && str.length) { let arr: string[] = str.split(UIPackage.sep2); let texID: string; let itemId: string = arr[0]; let binIndex: number = parseInt(arr[1]); if (binIndex >= 0) texID = `atlas${binIndex}`; else { let pos: number = itemId.indexOf("_"); if (pos == -1) texID = `atlas_${itemId}`; else texID = `atlas_${itemId.substr(0, pos)}`; } let cfg: AtlasConfig = new AtlasConfig(texID); cfg.frame = new PIXI.Rectangle(parseInt(arr[2]), parseInt(arr[3]), parseInt(arr[4]), parseInt(arr[5])); cfg.rotate = arr[6] == "1" ? 6 : 0; //refer to PIXI.GroupD8, the editors rotate image by -90deg cfg.orig = cfg.rotate != 0 ? new PIXI.Rectangle(0, 0, cfg.frame.height, cfg.frame.width) : null; /* cfg.trim = trimed; //ignored for now - editor not support */ this.$atlasConfigs[itemId] = cfg; } }); str = this.getResDescriptor("package.xml"); let xml: utils.XmlNode = utils.XmlParser.tryParse(str); this.$id = xml.attributes.id; this.$name = xml.attributes.name; let resources: utils.XmlNode[] = xml.children[0].children; this.$itemsById = {}; this.$itemsByName = {}; resources.forEach(cxml => { let pi = new PackageItem(); pi.type = ParsePackageItemType(cxml.nodeName); pi.id = cxml.attributes.id; pi.name = cxml.attributes.name; pi.file = cxml.attributes.file; str = cxml.attributes.size; if (str) { let arr = str.split(UIPackage.sep0); pi.width = parseInt(arr[0]); pi.height = parseInt(arr[1]); } switch (pi.type) { case PackageItemType.Image: { str = cxml.attributes.scale; if (str == "9grid") { str = cxml.attributes.scale9grid; if (str) { let arr = str.split(UIPackage.sep0); let rect = new PIXI.Rectangle( parseInt(arr[0]), parseInt(arr[1]), parseInt(arr[2]), parseInt(arr[3]) ); pi.scale9Grid = rect; str = cxml.attributes.gridTile; if (str) pi.tiledSlices = parseInt(str); } } else if (str == "tile") pi.scaleByTile = true; break; } } pi.owner = this; this.$items.push(pi); this.$itemsById[pi.id] = pi; if (pi.name != null) this.$itemsByName[pi.name] = pi; }, this); this.$items.forEach(pi => { if (pi.type == PackageItemType.Font) { this.loadFont(pi); UIPackage.$bitmapFonts[pi.bitmapFont.id] = pi.bitmapFont; } }, this); } private decompressPackage(buf: ArrayBuffer): void { this.$resData = {}; let inflater: Zlib.RawInflate = new Zlib.RawInflate(buf); let data: Uint8Array = inflater.decompress(); let source: string = utils.RawByte.decodeUTF8(data); let curr: number = 0; let fn: string; let size: number; while (true) { let pos: number = source.indexOf("|", curr); if (pos == -1) break; fn = source.substring(curr, pos); curr = pos + 1; pos = source.indexOf("|", curr); size = parseInt(source.substring(curr, pos)); curr = pos + 1; this.$resData[fn] = source.substr(curr, size); curr += size; } } public dispose(): void { this.$items.forEach(pi => { let texture: PIXI.Texture = pi.texture; if (texture != null) { texture.destroy(); //texture.baseTexture.destroy(); PIXI.Texture.removeFromCache(texture); } else if (pi.frames != null) { pi.frames.forEach(f => { texture = f.texture; if(texture) { texture.destroy(); //texture.baseTexture.destroy(); PIXI.Texture.removeFromCache(texture); } }); } else if (pi.bitmapFont != null) delete UIPackage.$bitmapFonts[pi.bitmapFont.id]; let cfg = this.$atlasConfigs[pi.id]; if(cfg) utils.AssetLoader.destroyResource(`${this.$resKey}@${cfg.atlasName}`); }, this); utils.AssetLoader.destroyResource(`${this.$resKey}`); } public get id(): string { return this.$id; } public get name(): string { return this.$name; } public get customId(): string { return this.$customId; } public set customId(value: string) { if (this.$customId != null) delete UIPackage.$packageInstById[this.$customId]; this.$customId = value; if (this.$customId != null) UIPackage.$packageInstById[this.$customId] = this; } public createObject(resName: string, userClass?: { new():GObject }): GObject { let pi: PackageItem = this.$itemsByName[resName]; if (pi) return this.internalCreateObject(pi, userClass); else return null; } public internalCreateObject(item: PackageItem, userClass: { new(): GObject; } = null): GObject { let g: GObject = item.type == PackageItemType.Component && userClass != null ? new userClass() : UIObjectFactory.newObject(item); if (g == null) return null; UIPackage.$constructingObjects++; g.packageItem = item; g.constructFromResource(); UIPackage.$constructingObjects--; return g; } public getItemById(itemId: string): PackageItem { return this.$itemsById[itemId]; } public getItemByName(resName: string): PackageItem { return this.$itemsByName[resName]; } public getItemAssetByName(resName: string): AssetTypes { let pi: PackageItem = this.$itemsByName[resName]; if (pi == null) throw new Error(`Resource '${resName}' not found`); return this.getItemAsset(pi); } private createSpriteTexture(cfgName:string, cfg: AtlasConfig): PIXI.Texture { let atlasItem: PackageItem = this.$itemsById[cfg.atlasName]; if (atlasItem != null) { let atlasTexture: PIXI.Texture = this.getItemAsset(atlasItem) as PIXI.Texture; if (!atlasTexture || !atlasTexture.baseTexture) return null; if(!cfg.texCacheID) cfg.texCacheID = `${this.$resKey}@${cfg.atlasName}@${cfgName}`; let tex = PIXI.utils.TextureCache[cfg.texCacheID]; if(!tex) { tex = new PIXI.Texture(atlasTexture.baseTexture, cfg.frame, cfg.orig, cfg.trim, cfg.rotate); PIXI.Texture.addToCache(tex, cfg.texCacheID); } return tex; } else return null; } public getItemAsset(item: PackageItem): AssetTypes { switch (item.type) { case PackageItemType.Image: if (!item.decoded) { item.decoded = true; let cfg: AtlasConfig = this.$atlasConfigs[item.id]; if (cfg != null) item.texture = this.createSpriteTexture(item.id, cfg); } return item.texture; case PackageItemType.Atlas: if (!item.decoded) { item.decoded = true; let fileName: string = (item.file != null && item.file.length > 0) ? item.file : (`${item.id}.png`); let resName: string = `${this.$resKey}@${utils.StringUtil.getFileName(fileName)}`; let res: PIXI.loaders.Resource = utils.AssetLoader.resourcesPool[resName]; if (!res) throw new Error(`${resName} not found in fgui.utils.AssetLoader.resourcesPool, please use new AssetLoader() to load assets instead of using new PIXI.loaders.Loader(). besides, AssetLoader is a sub-class from PIXI.loaders.Loader so they have the same usage.`); item.texture = res.texture; if (!item.texture) { res = utils.AssetLoader.resourcesPool[`${this.$resKey}@${fileName.replace("\.", "_")}`]; item.texture = res.texture; } } return item.texture; case PackageItemType.Sound: //ignored, maybe integrate with PIXI.Sound item.decoded = false; return null; case PackageItemType.Font: if (!item.decoded) { item.decoded = true; this.loadFont(item); } return item.bitmapFont; case PackageItemType.MovieClip: if (!item.decoded) { item.decoded = true; this.loadMovieClip(item); } return item.frames; case PackageItemType.Component: if (!item.decoded) { item.decoded = true; let str: string = this.getResDescriptor(`${item.id}.xml`); let xml: utils.XmlNode = utils.XmlParser.tryParse(str); item.componentData = xml; this.loadComponentChildren(item); this.loadComponentTranslation(item); } return item.componentData; default: return utils.AssetLoader.resourcesPool[`${this.$resKey}@${item.id}`]; } } private loadComponentChildren(item: PackageItem): void { let listNode: utils.XmlNode[] = utils.XmlParser.getChildNodes(item.componentData, "displayList"); if (listNode != null && listNode.length > 0) { item.displayList = []; listNode[0].children.forEach(cxml => { let tagName: string = cxml.nodeName; let di: DisplayListItem; let src: string = cxml.attributes.src; if (src) { let pkgId: string = cxml.attributes.pkg; let pkg: UIPackage; if (pkgId && pkgId != item.owner.id) pkg = UIPackage.getById(pkgId); else pkg = item.owner; let pi: PackageItem = pkg != null ? pkg.getItemById(src) : null; if (pi != null) di = new DisplayListItem(pi, null); else di = new DisplayListItem(null, tagName); } else { if (tagName == "text" && cxml.attributes.input == "true") di = new DisplayListItem(null, "inputtext"); else di = new DisplayListItem(null, tagName); } di.desc = cxml; item.displayList.push(di); }); } else item.displayList = []; } private getResDescriptor(fn: string): string { return this.$resData[fn]; } private loadComponentTranslation(item: PackageItem): void { if (UIPackage.$stringsSource == null) return; let strings: StringSource = UIPackage.$stringsSource[this.id + item.id]; if (strings == null) return; let value: string; let cxml: utils.XmlNode, dxml: utils.XmlNode; let ename: string; let elementId: string; let str: string; item.displayList.forEach(item => { cxml = item.desc; ename = cxml.nodeName; elementId = cxml.attributes.id; str = cxml.attributes.tooltips; if (str) { value = strings[`${elementId}-tips`]; if (value != undefined) cxml.attributes.tooltips = value; } let cs: utils.XmlNode[] = utils.XmlParser.getChildNodes(cxml, "gearText"); dxml = cs && cs[0]; if (dxml) { value = strings[`${elementId}-texts`]; if (value != undefined) dxml.attributes.values = value; value = strings[`${elementId}-texts_def`]; if (value != undefined) dxml.attributes.default = value; } if (ename == "text" || ename == "richtext") { value = strings[elementId]; if (value != undefined) cxml.attributes.text = value; value = strings[`${elementId}-prompt`]; if (value != undefined) cxml.attributes.prompt = value; } else if (ename == "list") { cxml.children.forEach((exml, index) => { if (exml.nodeName != "item") return; value = strings[`${elementId}-${index}`]; if (value != undefined) exml.attributes.title = value; }); } else if (ename == "component") { cs = utils.XmlParser.getChildNodes(cxml, "Button"); dxml = cs && cs[0]; if (dxml) { value = strings[elementId]; if (value != undefined) dxml.attributes.title = value; value = strings[`${elementId}-0`]; if (value != undefined) dxml.attributes.selectedTitle = value; return; } cs = utils.XmlParser.getChildNodes(cxml, "Label"); dxml = cs && cs[0]; if (dxml) { value = strings[elementId]; if (value != undefined) dxml.attributes.title = value; return; } cs = utils.XmlParser.getChildNodes(cxml, "ComboBox"); dxml = cs && cs[0]; if (dxml) { value = strings[elementId]; if (value != undefined) dxml.attributes.title = value; dxml.children.forEach((exml, index) => { if (exml.nodeName != "item") return; value = strings[`${elementId}-${index}`]; if (value != undefined) exml.attributes.title = value; }); return; } } }); } private loadMovieClip(item: PackageItem): void { let xml: utils.XmlNode = utils.XmlParser.tryParse(this.getResDescriptor(`${item.id}.xml`)); let str: string; str = xml.attributes.interval; if (str != null) item.interval = parseInt(str); str = xml.attributes.swing; if (str != null) item.swing = str == "true"; str = xml.attributes.repeatDelay; if (str != null) item.repeatDelay = parseInt(str); item.frames = []; let frameNodes: utils.XmlNode[] = xml.children[0].children; frameNodes.forEach((node, index) => { let frame: Frame = new Frame(); str = node.attributes.rect; let arr = str.split(UIPackage.sep0); let trimRect: PIXI.Rectangle = new PIXI.Rectangle(parseInt(arr[0]), parseInt(arr[1]), parseInt(arr[2]), parseInt(arr[3])); str = node.attributes.addDelay; if (str) frame.addDelay = parseInt(str); item.frames.push(frame); if (trimRect.width <= 0) return; str = node.attributes.sprite; if (str) str = `${item.id}_${str}`; else str = `${item.id}_${index}`; let cfg: AtlasConfig = this.$atlasConfigs[str]; if(cfg != null) { cfg.trim = trimRect; frame.texture = this.createSpriteTexture(str, cfg); } }); } private loadFont(item: PackageItem): void { let font: BitmapFont = new BitmapFont(); font.id = `ui://${this.id}${item.id}`; let str: string = this.getResDescriptor(`${item.id}.fnt`); let lines: string[] = str.split(UIPackage.sep1); let kv: { [key: string]: string } = {}; let ttf: boolean = false; let size: number = 0; let xadvance: number = 0; let resizable: boolean = false; let colorable: boolean = false; let atlasOffsetX: number = 0, atlasOffsetY: number = 0; let charImg: PackageItem; let mainTexture: PIXI.Texture; let lineHeight: number = 0; let maxCharHeight:number = 0; lines.forEach(line => { if(line && line.length) { str = utils.StringUtil.trim(line); let arr: string[] = str.split(UIPackage.sep2); arr.forEach(v => { let at = v.split(UIPackage.sep3); kv[at[0]] = at[1]; }); str = arr[0]; if (str == "char") { let bg: BMGlyph = new BMGlyph(); bg.x = parseInt(kv.x) || 0; bg.y = parseInt(kv.y) || 0; bg.offsetX = parseInt(kv.xoffset) || 0; bg.offsetY = parseInt(kv.yoffset) || 0; bg.width = parseInt(kv.width) || 0; bg.height = parseInt(kv.height) || 0; maxCharHeight = Math.max(bg.height, maxCharHeight); bg.advance = parseInt(kv.xadvance) || 0; if (kv.chnl != undefined) { bg.channel = parseInt(kv.chnl); if (bg.channel == 15) bg.channel = 4; else if (bg.channel == 1) bg.channel = 3; else if (bg.channel == 2) bg.channel = 2; else bg.channel = 1; } if (!ttf) { if (kv.img) { charImg = this.$itemsById[kv.img]; if (charImg != null) { charImg.load(); bg.width = charImg.width; bg.height = charImg.height; bg.texture = charImg.texture; } } } else if (mainTexture != null) { bg.texture = new PIXI.Texture(mainTexture.baseTexture, new PIXI.Rectangle(bg.x + atlasOffsetX, bg.y + atlasOffsetY, bg.width, bg.height)); } if (ttf) bg.lineHeight = lineHeight; else { if (bg.advance == 0) { if (xadvance == 0) bg.advance = bg.offsetX + bg.width; else bg.advance = xadvance; } bg.lineHeight = bg.offsetY < 0 ? bg.height : (bg.offsetY + bg.height); if (size > 0 && bg.lineHeight < size) bg.lineHeight = size; } font.glyphs[String.fromCharCode(+kv.id | 0)] = bg; } else if (str == "info") { ttf = kv.face != null; if (kv.size) size = parseInt(kv.size); resizable = kv.resizable == "true"; colorable = kv.colored == "true"; if (ttf) { let cfg: AtlasConfig = this.$atlasConfigs[item.id]; if (cfg != null) { atlasOffsetX = cfg.frame.x; atlasOffsetY = cfg.frame.y; let atlasItem: PackageItem = this.$itemsById[cfg.atlasName]; if (atlasItem != null) mainTexture = this.getItemAsset(atlasItem) as PIXI.Texture; } } } else if (str == "common") { if (kv.lineHeight) lineHeight = parseInt(kv.lineHeight); if (size == 0) size = lineHeight; else if (lineHeight == 0) lineHeight = size; if (kv.xadvance) xadvance = parseInt(kv.xadvance); } } }); if (size == 0 && maxCharHeight > 0) size = maxCharHeight; font.ttf = ttf; font.size = size; font.resizable = resizable; font.colorable = colorable; item.bitmapFont = font; } } }
the_stack
import './index'; import { expect } from 'chai'; import { DotsSk } from './dots-sk'; import { commits, traces } from './demo_data'; import { dotToCanvasX, dotToCanvasY, DOT_FILL_COLORS, DOT_FILL_COLORS_HIGHLIGHTED, DOT_RADIUS, DOT_STROKE_COLORS, MAX_UNIQUE_DIGESTS, TRACE_LINE_COLOR, } from './constants'; import { eventPromise, setUpElementUnderTest } from '../../../infra-sk/modules/test_util'; import { Commit } from '../rpc_types'; describe('dots-sk constants', () => { it('DOT_FILL_COLORS has the expected number of entries', () => { expect(DOT_FILL_COLORS).to.have.length(MAX_UNIQUE_DIGESTS); }); it('DOT_FILL_COLORS_HIGHLIGHTED has the expected number of entries', () => { expect(DOT_FILL_COLORS_HIGHLIGHTED).to.have.length(MAX_UNIQUE_DIGESTS); }); it('DOT_STROKE_COLORS has the expected number of entries', () => { expect(DOT_STROKE_COLORS).to.have.length(MAX_UNIQUE_DIGESTS); }); }); describe('dots-sk', () => { const newInstance = setUpElementUnderTest<DotsSk>('dots-sk'); let dotsSk: DotsSk; let dotsSkCanvas: HTMLCanvasElement; let dotsSkCanvasCtx: CanvasRenderingContext2D; beforeEach(() => { dotsSk = newInstance((el) => { // All test cases use the same set of traces and commits. el.value = traces; el.commits = commits; }); dotsSkCanvas = dotsSk.querySelector('canvas')!; dotsSkCanvasCtx = dotsSkCanvas.getContext('2d')!; }); it('renders correctly', () => { expect(dotsSkCanvas.clientWidth).to.equal(210); expect(dotsSkCanvas.clientHeight).to.equal(40); // We specify the traces as an array and then join them instead of using a string literal // to avoid having invisible (but important to the test) trailing spaces. expect(canvasToAscii(dotsSkCanvasCtx)).to.equal([ 'iihgfddeeddddccbbbaa', ' bb-b-bbaa--aaaa ', ' ccccbbbbbbaaaa', ].join('\n')); }); it('highlights traces when hovering', async () => { // Hover over first trace. (X coordinate does not matter.) await hoverOverDot(dotsSkCanvas, 0, 0); expect(canvasToAscii(dotsSkCanvasCtx)).to.equal([ 'IIHGFDDEEDDDDCCBBBAA', ' bb-b-bbaa--aaaa ', ' ccccbbbbbbaaaa', ].join('\n')); // Hover over second trace. await hoverOverDot(dotsSkCanvas, 15, 1); expect(canvasToAscii(dotsSkCanvasCtx)).to.equal([ 'iihgfddeeddddccbbbaa', ' BB-B-BBAA--AAAA ', ' ccccbbbbbbaaaa', ].join('\n')); // Hover over third trace. await hoverOverDot(dotsSkCanvas, 10, 2); expect(canvasToAscii(dotsSkCanvasCtx)).to.equal([ 'iihgfddeeddddccbbbaa', ' bb-b-bbaa--aaaa ', ' CCCCBBBBBBAAAA', ].join('\n')); }); it('emits "hover" event when a trace is hovered', async () => { // Hover over first trace. (X coordinate does not matter.) let traceLabel = await hoverOverDotAndCatchHoverEvent(dotsSkCanvas, 0, 0); expect(traceLabel).to.equal(',alpha=first-trace,beta=hello,gamma=world,'); // Hover over second trace. traceLabel = await hoverOverDotAndCatchHoverEvent(dotsSkCanvas, 15, 1); expect(traceLabel).to.equal(',alpha=second-trace,beta=foo,gamma=bar,'); // Hover over third trace. traceLabel = await hoverOverDotAndCatchHoverEvent(dotsSkCanvas, 10, 2); expect(traceLabel).to.equal(',alpha=third-trace,beta=baz,gamma=qux,'); }); it('emits "showblamelist" event when a dot is clicked', async () => { // First trace, most recent commit. let dotCommits = await clickDotAndCatchShowBlamelistEvent(dotsSkCanvas, 19, 0); expect(dotCommits).to.deep.equal([commits[19], commits[18]]); // First trace, middle-of-the-tile commit. dotCommits = await clickDotAndCatchShowBlamelistEvent(dotsSkCanvas, 10, 0); expect(dotCommits).to.deep.equal([commits[10], commits[9]]); // First trace, oldest commit. dotCommits = await clickDotAndCatchShowBlamelistEvent(dotsSkCanvas, 0, 0); expect(dotCommits).to.deep.equal([commits[0]]); // Second trace, most recent commit with data dotCommits = await clickDotAndCatchShowBlamelistEvent(dotsSkCanvas, 17, 1); expect(dotCommits).to.deep.equal([commits[17], commits[16]]); // Second trace, middle-of-the-tile dot preceded by two missing dots. dotCommits = await clickDotAndCatchShowBlamelistEvent(dotsSkCanvas, 14, 1); expect(dotCommits).to.deep.equal([commits[14], commits[13], commits[12], commits[11]]); // Second trace, oldest commit with data preceded by three missing dots. dotCommits = await clickDotAndCatchShowBlamelistEvent(dotsSkCanvas, 3, 1); expect(dotCommits).to.deep.equal( [commits[3], commits[2], commits[1], commits[0]], ); // Third trace, most recent commit. dotCommits = await clickDotAndCatchShowBlamelistEvent(dotsSkCanvas, 19, 2); expect(dotCommits).to.deep.equal([commits[19], commits[18]]); // Third trace, middle-of-the-tile commit. dotCommits = await clickDotAndCatchShowBlamelistEvent(dotsSkCanvas, 10, 2); expect(dotCommits).to.deep.equal([commits[10], commits[9]]); // Third trace, oldest commit. dotCommits = await clickDotAndCatchShowBlamelistEvent(dotsSkCanvas, 6, 2); expect(dotCommits).to.deep.equal([ commits[6], commits[5], commits[4], commits[3], commits[2], commits[1], commits[0], ]); }); }); // Returns an ASCII-art representation of the canvas based on function // dotToAscii. function canvasToAscii(dotsSkCanvasCtx: CanvasRenderingContext2D): string { const ascii = []; for (let y = 0; y < traces.traces!.length; y++) { const trace = []; for (let x = 0; x < traces.traces![0].data!.length; x++) { trace.push(dotToAscii(dotsSkCanvasCtx, x, y)); } ascii.push(trace.join('')); } return ascii.join('\n'); } // Returns a character representing the dot at (x, y) in dotspace. // - A trace line is represented with '-'. // - A non-highlighted dot is represented with a character in {'a', 'b', ...}, // where 'a' represents the dot color for the most recent commit. // - A highlighted dot is represented with a character in {'A', 'B', ...}. // - A blank position is represented with ' '. function dotToAscii(dotsSkCanvasCtx: CanvasRenderingContext2D, x: number, y: number): string { const canvasX = dotToCanvasX(x); const canvasY = dotToCanvasY(y); // Sample a few pixels (north, east, south, west, center) from the bounding // box for the potential dot at (x, y). We'll use these to determine whether // there's a dot or a trace line at (x, y), what the color of the dot is, // whether or not it's highlighted, etc. const n = pixelAt(dotsSkCanvasCtx, canvasX, canvasY - DOT_RADIUS); const e = pixelAt(dotsSkCanvasCtx, canvasX + DOT_RADIUS, canvasY); const s = pixelAt(dotsSkCanvasCtx, canvasX, canvasY + DOT_RADIUS); const w = pixelAt(dotsSkCanvasCtx, canvasX - DOT_RADIUS, canvasY); const c = pixelAt(dotsSkCanvasCtx, canvasX, canvasY); // Determines whether the sampled pixels match the given expected colors. const exactColorMatch = (en: string, ee: string, es: string, ew: string, ec: string) => [n, e, s, w, c].toString() === [en, ee, es, ew, ec].toString(); // Is it empty? const white = '#FFFFFF'; if (exactColorMatch(white, white, white, white, white)) { return ' '; } // Is it a trace line? if (exactColorMatch(white, TRACE_LINE_COLOR, white, TRACE_LINE_COLOR, TRACE_LINE_COLOR)) { return '-'; } // Iterate over all possible dot colors. for (let i = 0; i <= MAX_UNIQUE_DIGESTS; i++) { // Is it a dot of the i-th color? Let's look at the pixels in the potential // circumference of the dot. Do they match the current color? // Note: we look for the closest match instead of an exact match due to // canvas anti-aliasing. if (closestColor(n, DOT_STROKE_COLORS) === DOT_STROKE_COLORS[i] && closestColor(e, DOT_STROKE_COLORS) === DOT_STROKE_COLORS[i] && closestColor(s, DOT_STROKE_COLORS) === DOT_STROKE_COLORS[i] && closestColor(w, DOT_STROKE_COLORS) === DOT_STROKE_COLORS[i]) { // Is it a non-highlighted dot? (In other words, is it filled with the // corresponding non-highlighted color?) if (c === DOT_FILL_COLORS[i]) { return 'abcdefghijklmnopqrstuvwxyz'[i]; } // Is it a highlighted dot? (In other words, is it filled with the // corresponding highlighted color?) if (c === DOT_FILL_COLORS_HIGHLIGHTED[i]) { return 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i]; } } } throw `unrecognized dot at (${x}, ${y})`; } // Returns the color for the pixel at (x, y) in the canvas, represented as a hex // string, e.g. "#AABBCC". function pixelAt(dotsSkCanvasCtx: CanvasRenderingContext2D, x: number, y: number): string { const pixel = dotsSkCanvasCtx.getImageData(x, y, 1, 1).data; const r = pixel[0].toString(16).padStart(2, '0'); const g = pixel[1].toString(16).padStart(2, '0'); const b = pixel[2].toString(16).padStart(2, '0'); return `#${r}${g}${b}`.toUpperCase(); } // Finds the color in the haystack with the minimum Euclidean distance to the // needle. This is necessary for pixels in the circumference of a dot due to // canvas anti-aliasing. All colors are hex strings, e.g. "#AABBCC". function closestColor(needle: string, haystack: string[]): string { return haystack .map((color) => ({ color: color, dist: euclideanDistanceSq(needle, color) })) .reduce((acc, cur) => ((acc.dist < cur.dist) ? acc : cur)) .color; } // Takes two colors represented as hex strings (e.g. "#AABBCC") and computes the // squared Euclidean distance between them. function euclideanDistanceSq(color1: string, color2: string): number { const rgb1 = hexToRgb(color1); const rgb2 = hexToRgb(color2); return (rgb1[0] - rgb2[0]) ** 2 + (rgb1[1] - rgb2[1]) ** 2 + (rgb1[2] - rgb2[2]) ** 2; } // Takes e.g. "#FF8000" and returns [256, 128, 0]. function hexToRgb(hex: string): [number, number, number] { // Borrowed from https://stackoverflow.com/a/5624139. const res = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)!; return [ parseInt(res[1], 16), parseInt(res[2], 16), parseInt(res[3], 16), ]; } // Simulate hovering over a dot. async function hoverOverDot(dotsSkCanvas: HTMLCanvasElement, x: number, y: number) { dotsSkCanvas.dispatchEvent(new MouseEvent('mousemove', { clientX: dotsSkCanvas.getBoundingClientRect().left + dotToCanvasX(x), clientY: dotsSkCanvas.getBoundingClientRect().top + dotToCanvasY(y), })); // Give mousemove event a chance to be processed. Necessary due to how // mousemove events are processed in batches by dots-sk every 40 ms. await new Promise((resolve) => setTimeout(resolve, 50)); } // Simulate hovering over a dot, and return the trace label in the "hover" event details. async function hoverOverDotAndCatchHoverEvent( dotsSkCanvas: HTMLCanvasElement, x: number, y: number, ): Promise<string> { // const eventPromise = dotsSkEventPromise(dotsSk, 'hover'); const event = eventPromise<CustomEvent<string>>('hover'); await hoverOverDot(dotsSkCanvas, x, y); return (await event).detail; } // Simulate clicking on a dot. function clickDot(dotsSkCanvas: HTMLCanvasElement, x: number, y: number) { dotsSkCanvas.dispatchEvent(new MouseEvent('click', { clientX: dotsSkCanvas.getBoundingClientRect().left + dotToCanvasX(x), clientY: dotsSkCanvas.getBoundingClientRect().top + dotToCanvasY(y), })); } // Simulate clicking on a dot, and return the list of commits in the "showblamelist" event details. async function clickDotAndCatchShowBlamelistEvent( dotsSkCanvas: HTMLCanvasElement, x: number, y: number, ): Promise<Commit[]> { const event = eventPromise<CustomEvent<Commit[]>>('showblamelist'); clickDot(dotsSkCanvas, x, y); return (await event).detail; }
the_stack
import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpEvent } from '@angular/common/http'; import { Inject, Injectable, InjectionToken, Optional } from '@angular/core'; import { UserAPIClientInterface } from './user-api-client.interface'; import { Observable } from 'rxjs';import { DefaultHttpOptions, HttpOptions } from '../../types'; import * as models from '../../models'; export const USE_DOMAIN = new InjectionToken<string>('UserAPIClient_USE_DOMAIN'); export const USE_HTTP_OPTIONS = new InjectionToken<HttpOptions>('UserAPIClient_USE_HTTP_OPTIONS'); type APIHttpOptions = HttpOptions & { headers: HttpHeaders; params: HttpParams; }; @Injectable() export class UserAPIClient implements UserAPIClientInterface { readonly options: APIHttpOptions; readonly domain: string = `https://api.github.com`; constructor( private readonly http: HttpClient, @Optional() @Inject(USE_DOMAIN) domain?: string, @Optional() @Inject(USE_HTTP_OPTIONS) options?: DefaultHttpOptions, ) { if (domain != null) { this.domain = domain; } this.options = { headers: new HttpHeaders(options && options.headers ? options.headers : {}), params: new HttpParams(options && options.params ? options.params : {}), ...(options && options.reportProgress ? { reportProgress: options.reportProgress } : {}), ...(options && options.withCredentials ? { withCredentials: options.withCredentials } : {}) }; } /** * Get the authenticated user. * Response generated for [ 200 ] HTTP response code. */ getUser( args?: UserAPIClientInterface['getUserParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.User>; getUser( args?: UserAPIClientInterface['getUserParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.User>>; getUser( args?: UserAPIClientInterface['getUserParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.User>>; getUser( args: UserAPIClientInterface['getUserParams'] = {}, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.User | HttpResponse<models.User> | HttpEvent<models.User>> { const path = `/user`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.User>(`${this.domain}${path}`, options); } /** * Update the authenticated user. * Response generated for [ 200 ] HTTP response code. */ patchUser( args: Exclude<UserAPIClientInterface['patchUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.User>; patchUser( args: Exclude<UserAPIClientInterface['patchUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.User>>; patchUser( args: Exclude<UserAPIClientInterface['patchUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.User>>; patchUser( args: Exclude<UserAPIClientInterface['patchUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.User | HttpResponse<models.User> | HttpEvent<models.User>> { const path = `/user`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.patch<models.User>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Delete email address(es). * You can include a single email address or an array of addresses. * * Response generated for [ 204 ] HTTP response code. */ deleteUserEmails( args: Exclude<UserAPIClientInterface['deleteUserEmailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteUserEmails( args: Exclude<UserAPIClientInterface['deleteUserEmailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteUserEmails( args: Exclude<UserAPIClientInterface['deleteUserEmailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; deleteUserEmails( args: Exclude<UserAPIClientInterface['deleteUserEmailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/user/emails`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.delete<void>(`${this.domain}${path}`, options); } /** * List email addresses for a user. * In the final version of the API, this method will return an array of hashes * with extended information for each email address indicating if the address * has been verified and if it's primary email address for GitHub. * Until API v3 is finalized, use the application/vnd.github.v3 media type to * get other response format. * * Response generated for [ 200 ] HTTP response code. */ getUserEmails( args?: UserAPIClientInterface['getUserEmailsParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.UserEmails>; getUserEmails( args?: UserAPIClientInterface['getUserEmailsParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.UserEmails>>; getUserEmails( args?: UserAPIClientInterface['getUserEmailsParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.UserEmails>>; getUserEmails( args: UserAPIClientInterface['getUserEmailsParams'] = {}, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.UserEmails | HttpResponse<models.UserEmails> | HttpEvent<models.UserEmails>> { const path = `/user/emails`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.UserEmails>(`${this.domain}${path}`, options); } /** * Add email address(es). * You can post a single email address or an array of addresses. * * Response generated for [ default ] HTTP response code. */ postUserEmails( args: Exclude<UserAPIClientInterface['postUserEmailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; postUserEmails( args: Exclude<UserAPIClientInterface['postUserEmailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; postUserEmails( args: Exclude<UserAPIClientInterface['postUserEmailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; postUserEmails( args: Exclude<UserAPIClientInterface['postUserEmailsParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/user/emails`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.post<void>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * List the authenticated user's followers * Response generated for [ 200 ] HTTP response code. */ getUserFollowers( args?: UserAPIClientInterface['getUserFollowersParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Users>; getUserFollowers( args?: UserAPIClientInterface['getUserFollowersParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Users>>; getUserFollowers( args?: UserAPIClientInterface['getUserFollowersParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Users>>; getUserFollowers( args: UserAPIClientInterface['getUserFollowersParams'] = {}, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Users | HttpResponse<models.Users> | HttpEvent<models.Users>> { const path = `/user/followers`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Users>(`${this.domain}${path}`, options); } /** * List who the authenticated user is following. * Response generated for [ 200 ] HTTP response code. */ getUserFollowing( args?: UserAPIClientInterface['getUserFollowingParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Users>; getUserFollowing( args?: UserAPIClientInterface['getUserFollowingParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Users>>; getUserFollowing( args?: UserAPIClientInterface['getUserFollowingParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Users>>; getUserFollowing( args: UserAPIClientInterface['getUserFollowingParams'] = {}, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Users | HttpResponse<models.Users> | HttpEvent<models.Users>> { const path = `/user/following`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Users>(`${this.domain}${path}`, options); } /** * Unfollow a user. * Unfollowing a user requires the user to be logged in and authenticated with * basic auth or OAuth with the user:follow scope. * * Response generated for [ 204 ] HTTP response code. */ deleteUserFollowingUsername( args: Exclude<UserAPIClientInterface['deleteUserFollowingUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteUserFollowingUsername( args: Exclude<UserAPIClientInterface['deleteUserFollowingUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteUserFollowingUsername( args: Exclude<UserAPIClientInterface['deleteUserFollowingUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; deleteUserFollowingUsername( args: Exclude<UserAPIClientInterface['deleteUserFollowingUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/user/following/${args.username}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.delete<void>(`${this.domain}${path}`, options); } /** * Check if you are following a user. * Response generated for [ 204 ] HTTP response code. */ getUserFollowingUsername( args: Exclude<UserAPIClientInterface['getUserFollowingUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getUserFollowingUsername( args: Exclude<UserAPIClientInterface['getUserFollowingUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getUserFollowingUsername( args: Exclude<UserAPIClientInterface['getUserFollowingUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; getUserFollowingUsername( args: Exclude<UserAPIClientInterface['getUserFollowingUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/user/following/${args.username}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<void>(`${this.domain}${path}`, options); } /** * Follow a user. * Following a user requires the user to be logged in and authenticated with * basic auth or OAuth with the user:follow scope. * * Response generated for [ 204 ] HTTP response code. */ putUserFollowingUsername( args: Exclude<UserAPIClientInterface['putUserFollowingUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; putUserFollowingUsername( args: Exclude<UserAPIClientInterface['putUserFollowingUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; putUserFollowingUsername( args: Exclude<UserAPIClientInterface['putUserFollowingUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; putUserFollowingUsername( args: Exclude<UserAPIClientInterface['putUserFollowingUsernameParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/user/following/${args.username}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.put<void>(`${this.domain}${path}`, null, options); } /** * List issues. * List all issues across owned and member repositories for the authenticated * user. * * Response generated for [ 200 ] HTTP response code. */ getUserIssues( args: Exclude<UserAPIClientInterface['getUserIssuesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Issues>; getUserIssues( args: Exclude<UserAPIClientInterface['getUserIssuesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Issues>>; getUserIssues( args: Exclude<UserAPIClientInterface['getUserIssuesParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Issues>>; getUserIssues( args: Exclude<UserAPIClientInterface['getUserIssuesParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Issues | HttpResponse<models.Issues> | HttpEvent<models.Issues>> { const path = `/user/issues`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('filter' in args) { options.params = options.params.set('filter', String(args.filter)); } if ('state' in args) { options.params = options.params.set('state', String(args.state)); } if ('labels' in args) { options.params = options.params.set('labels', String(args.labels)); } if ('sort' in args) { options.params = options.params.set('sort', String(args.sort)); } if ('direction' in args) { options.params = options.params.set('direction', String(args.direction)); } if ('since' in args) { options.params = options.params.set('since', String(args.since)); } if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Issues>(`${this.domain}${path}`, options); } /** * List your public keys. * Lists the current user's keys. Management of public keys via the API requires * that you are authenticated through basic auth, or OAuth with the 'user', 'write:public_key' scopes. * * Response generated for [ 200 ] HTTP response code. */ getUserKeys( args?: UserAPIClientInterface['getUserKeysParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Gitignore>; getUserKeys( args?: UserAPIClientInterface['getUserKeysParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Gitignore>>; getUserKeys( args?: UserAPIClientInterface['getUserKeysParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Gitignore>>; getUserKeys( args: UserAPIClientInterface['getUserKeysParams'] = {}, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Gitignore | HttpResponse<models.Gitignore> | HttpEvent<models.Gitignore>> { const path = `/user/keys`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Gitignore>(`${this.domain}${path}`, options); } /** * Create a public key. * Response generated for [ 201 ] HTTP response code. */ postUserKeys( args: Exclude<UserAPIClientInterface['postUserKeysParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.UserKeysKeyId>; postUserKeys( args: Exclude<UserAPIClientInterface['postUserKeysParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.UserKeysKeyId>>; postUserKeys( args: Exclude<UserAPIClientInterface['postUserKeysParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.UserKeysKeyId>>; postUserKeys( args: Exclude<UserAPIClientInterface['postUserKeysParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.UserKeysKeyId | HttpResponse<models.UserKeysKeyId> | HttpEvent<models.UserKeysKeyId>> { const path = `/user/keys`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.post<models.UserKeysKeyId>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * Delete a public key. Removes a public key. Requires that you are authenticated via Basic Auth or via OAuth with at least admin:public_key scope. * Response generated for [ 204 ] HTTP response code. */ deleteUserKeysKeyId( args: Exclude<UserAPIClientInterface['deleteUserKeysKeyIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteUserKeysKeyId( args: Exclude<UserAPIClientInterface['deleteUserKeysKeyIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteUserKeysKeyId( args: Exclude<UserAPIClientInterface['deleteUserKeysKeyIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; deleteUserKeysKeyId( args: Exclude<UserAPIClientInterface['deleteUserKeysKeyIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/user/keys/${args.keyId}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.delete<void>(`${this.domain}${path}`, options); } /** * Get a single public key. * Response generated for [ 200 ] HTTP response code. */ getUserKeysKeyId( args: Exclude<UserAPIClientInterface['getUserKeysKeyIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.UserKeysKeyId>; getUserKeysKeyId( args: Exclude<UserAPIClientInterface['getUserKeysKeyIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.UserKeysKeyId>>; getUserKeysKeyId( args: Exclude<UserAPIClientInterface['getUserKeysKeyIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.UserKeysKeyId>>; getUserKeysKeyId( args: Exclude<UserAPIClientInterface['getUserKeysKeyIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.UserKeysKeyId | HttpResponse<models.UserKeysKeyId> | HttpEvent<models.UserKeysKeyId>> { const path = `/user/keys/${args.keyId}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.UserKeysKeyId>(`${this.domain}${path}`, options); } /** * List public and private organizations for the authenticated user. * Response generated for [ 200 ] HTTP response code. */ getUserOrgs( args?: UserAPIClientInterface['getUserOrgsParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Gitignore>; getUserOrgs( args?: UserAPIClientInterface['getUserOrgsParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Gitignore>>; getUserOrgs( args?: UserAPIClientInterface['getUserOrgsParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Gitignore>>; getUserOrgs( args: UserAPIClientInterface['getUserOrgsParams'] = {}, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Gitignore | HttpResponse<models.Gitignore> | HttpEvent<models.Gitignore>> { const path = `/user/orgs`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Gitignore>(`${this.domain}${path}`, options); } /** * List repositories for the authenticated user. Note that this does not include * repositories owned by organizations which the user can access. You can lis * user organizations and list organization repositories separately. * * Response generated for [ 200 ] HTTP response code. */ getUserRepos( args?: UserAPIClientInterface['getUserReposParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Repos>; getUserRepos( args?: UserAPIClientInterface['getUserReposParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Repos>>; getUserRepos( args?: UserAPIClientInterface['getUserReposParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Repos>>; getUserRepos( args: UserAPIClientInterface['getUserReposParams'] = {}, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Repos | HttpResponse<models.Repos> | HttpEvent<models.Repos>> { const path = `/user/repos`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('type' in args) { options.params = options.params.set('type', String(args.type)); } if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Repos>(`${this.domain}${path}`, options); } /** * Create a new repository for the authenticated user. OAuth users must supply * repo scope. * * Response generated for [ 201 ] HTTP response code. */ postUserRepos( args: Exclude<UserAPIClientInterface['postUserReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Repos>; postUserRepos( args: Exclude<UserAPIClientInterface['postUserReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Repos>>; postUserRepos( args: Exclude<UserAPIClientInterface['postUserReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Repos>>; postUserRepos( args: Exclude<UserAPIClientInterface['postUserReposParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Repos | HttpResponse<models.Repos> | HttpEvent<models.Repos>> { const path = `/user/repos`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.post<models.Repos>(`${this.domain}${path}`, JSON.stringify(args.body), options); } /** * List repositories being starred by the authenticated user. * Response generated for [ 200 ] HTTP response code. */ getUserStarred( args?: UserAPIClientInterface['getUserStarredParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Gitignore>; getUserStarred( args?: UserAPIClientInterface['getUserStarredParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Gitignore>>; getUserStarred( args?: UserAPIClientInterface['getUserStarredParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Gitignore>>; getUserStarred( args: UserAPIClientInterface['getUserStarredParams'] = {}, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.Gitignore | HttpResponse<models.Gitignore> | HttpEvent<models.Gitignore>> { const path = `/user/starred`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('direction' in args) { options.params = options.params.set('direction', String(args.direction)); } if ('sort' in args) { options.params = options.params.set('sort', String(args.sort)); } if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.Gitignore>(`${this.domain}${path}`, options); } /** * Unstar a repository * Response generated for [ 204 ] HTTP response code. */ deleteUserStarredOwnerRepo( args: Exclude<UserAPIClientInterface['deleteUserStarredOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteUserStarredOwnerRepo( args: Exclude<UserAPIClientInterface['deleteUserStarredOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteUserStarredOwnerRepo( args: Exclude<UserAPIClientInterface['deleteUserStarredOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; deleteUserStarredOwnerRepo( args: Exclude<UserAPIClientInterface['deleteUserStarredOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/user/starred/${args.owner}/${args.repo}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.delete<void>(`${this.domain}${path}`, options); } /** * Check if you are starring a repository. * Response generated for [ 204 ] HTTP response code. */ getUserStarredOwnerRepo( args: Exclude<UserAPIClientInterface['getUserStarredOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getUserStarredOwnerRepo( args: Exclude<UserAPIClientInterface['getUserStarredOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getUserStarredOwnerRepo( args: Exclude<UserAPIClientInterface['getUserStarredOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; getUserStarredOwnerRepo( args: Exclude<UserAPIClientInterface['getUserStarredOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/user/starred/${args.owner}/${args.repo}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<void>(`${this.domain}${path}`, options); } /** * Star a repository. * Response generated for [ 204 ] HTTP response code. */ putUserStarredOwnerRepo( args: Exclude<UserAPIClientInterface['putUserStarredOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; putUserStarredOwnerRepo( args: Exclude<UserAPIClientInterface['putUserStarredOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; putUserStarredOwnerRepo( args: Exclude<UserAPIClientInterface['putUserStarredOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; putUserStarredOwnerRepo( args: Exclude<UserAPIClientInterface['putUserStarredOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/user/starred/${args.owner}/${args.repo}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.put<void>(`${this.domain}${path}`, null, options); } /** * List repositories being watched by the authenticated user. * Response generated for [ 200 ] HTTP response code. */ getUserSubscriptions( args?: UserAPIClientInterface['getUserSubscriptionsParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.UserIdSubscribitions>; getUserSubscriptions( args?: UserAPIClientInterface['getUserSubscriptionsParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.UserIdSubscribitions>>; getUserSubscriptions( args?: UserAPIClientInterface['getUserSubscriptionsParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.UserIdSubscribitions>>; getUserSubscriptions( args: UserAPIClientInterface['getUserSubscriptionsParams'] = {}, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.UserIdSubscribitions | HttpResponse<models.UserIdSubscribitions> | HttpEvent<models.UserIdSubscribitions>> { const path = `/user/subscriptions`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.UserIdSubscribitions>(`${this.domain}${path}`, options); } /** * Stop watching a repository * Response generated for [ 204 ] HTTP response code. */ deleteUserSubscriptionsOwnerRepo( args: Exclude<UserAPIClientInterface['deleteUserSubscriptionsOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteUserSubscriptionsOwnerRepo( args: Exclude<UserAPIClientInterface['deleteUserSubscriptionsOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteUserSubscriptionsOwnerRepo( args: Exclude<UserAPIClientInterface['deleteUserSubscriptionsOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; deleteUserSubscriptionsOwnerRepo( args: Exclude<UserAPIClientInterface['deleteUserSubscriptionsOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/user/subscriptions/${args.owner}/${args.repo}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.delete<void>(`${this.domain}${path}`, options); } /** * Check if you are watching a repository. * Response generated for [ 204 ] HTTP response code. */ getUserSubscriptionsOwnerRepo( args: Exclude<UserAPIClientInterface['getUserSubscriptionsOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; getUserSubscriptionsOwnerRepo( args: Exclude<UserAPIClientInterface['getUserSubscriptionsOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; getUserSubscriptionsOwnerRepo( args: Exclude<UserAPIClientInterface['getUserSubscriptionsOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; getUserSubscriptionsOwnerRepo( args: Exclude<UserAPIClientInterface['getUserSubscriptionsOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/user/subscriptions/${args.owner}/${args.repo}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<void>(`${this.domain}${path}`, options); } /** * Watch a repository. * Response generated for [ 204 ] HTTP response code. */ putUserSubscriptionsOwnerRepo( args: Exclude<UserAPIClientInterface['putUserSubscriptionsOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; putUserSubscriptionsOwnerRepo( args: Exclude<UserAPIClientInterface['putUserSubscriptionsOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; putUserSubscriptionsOwnerRepo( args: Exclude<UserAPIClientInterface['putUserSubscriptionsOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; putUserSubscriptionsOwnerRepo( args: Exclude<UserAPIClientInterface['putUserSubscriptionsOwnerRepoParams'], undefined>, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<void | HttpResponse<void> | HttpEvent<void>> { const path = `/user/subscriptions/${args.owner}/${args.repo}`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.put<void>(`${this.domain}${path}`, null, options); } /** * List all of the teams across all of the organizations to which the authenticated user belongs. This method requires user or repo scope when authenticating via OAuth. * Response generated for [ 200 ] HTTP response code. */ getUserTeams( args?: UserAPIClientInterface['getUserTeamsParams'], requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.TeamsList>; getUserTeams( args?: UserAPIClientInterface['getUserTeamsParams'], requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.TeamsList>>; getUserTeams( args?: UserAPIClientInterface['getUserTeamsParams'], requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.TeamsList>>; getUserTeams( args: UserAPIClientInterface['getUserTeamsParams'] = {}, requestHttpOptions?: HttpOptions, observe: any = 'body', ): Observable<models.TeamsList | HttpResponse<models.TeamsList> | HttpEvent<models.TeamsList>> { const path = `/user/teams`; const options = { ...this.options, ...requestHttpOptions, observe, }; if ('xGitHubMediaType' in args) { options.headers = options.headers.set('X-GitHub-Media-Type', String(args.xGitHubMediaType)); } if ('accept' in args) { options.headers = options.headers.set('Accept', String(args.accept)); } if ('xRateLimit' in args) { options.headers = options.headers.set('X-RateLimit-Limit', String(args.xRateLimit)); } if ('xRateLimitRemaining' in args) { options.headers = options.headers.set('X-RateLimit-Remaining', String(args.xRateLimitRemaining)); } if ('xRateLimitReset' in args) { options.headers = options.headers.set('X-RateLimit-Reset', String(args.xRateLimitReset)); } if ('xGitHubRequestId' in args) { options.headers = options.headers.set('X-GitHub-Request-Id', String(args.xGitHubRequestId)); } return this.http.get<models.TeamsList>(`${this.domain}${path}`, options); } }
the_stack
import { Component, DebugElement } from '@angular/core'; import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { Cloudinary } from './cloudinary.service'; import CloudinaryConfiguration from './cloudinary-configuration.class'; import { CloudinaryImage } from './cloudinary-image.component'; import { CloudinaryTransformationDirective } from './cloudinary-transformation.directive'; import {LazyLoadDirective } from './cloudinary-lazy-load.directive'; import { CloudinaryPlaceHolder } from'./cloudinary-placeholder.component'; describe('CloudinaryImage', () => { let localCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@' } as CloudinaryConfiguration); beforeEach(() => { spyOn(localCloudinary, 'toCloudinaryAttributes').and.callThrough(); spyOn(localCloudinary, 'url').and.callThrough(); spyOn(localCloudinary, 'responsive').and.callThrough(); }); describe('responsive images without nested transformations', () => { @Component({ template: `<cl-image responsive id="image1" width="300" crop="scale" effect="blackwhite" public-id="responsive_sample.jpg"></cl-image>` }) class TestComponent { } let fixture: ComponentFixture<TestComponent>; let des: DebugElement; // the elements w/ the directive beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: localCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding expect(localCloudinary.responsive).toHaveBeenCalled(); // all elements with an attached CloudinaryImage des = fixture.debugElement.query(By.directive(CloudinaryImage)); }); it('creates an img element which encodes the directive attributes to the URL', () => { const img = des.children[0].nativeElement as HTMLImageElement; // http://res.cloudinary.com/@@fake_angular2_sdk@@/image/upload/c_scale,e_blackwhite,w_300/responsive_sample.jpg expect(img.attributes.getNamedItem('src').value).toEqual(jasmine.stringMatching(/c_scale,e_blackwhite,w_300\/responsive_sample.jpg/)); expect(img.attributes.getNamedItem('data-src').value).toEqual(jasmine.stringMatching(/c_scale,e_blackwhite,w_300\/responsive_sample.jpg/)); }); }); describe('responsive images with nested transformations', () => { @Component({ template: `<cl-image responsive id="image1" public-id="responsive_sample.jpg"> <cl-transformation width="300" crop="scale" overlay="text:roboto_25_bold:SDK"></cl-transformation> <cl-transformation effect="art:hokusai" gravity="auto"></cl-transformation> <cl-transformation fetch-format="auto"></cl-transformation> </cl-image>` }) class TestComponent { } let fixture: ComponentFixture<TestComponent>; let des: DebugElement; // the elements w/ the directive beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: localCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached CloudinaryImage des = fixture.debugElement.query(By.directive(CloudinaryImage)); }); it('creates an img element which encodes the directive attributes to the URL', () => { const img = des.children[0].nativeElement as HTMLImageElement; expect(img.src).toEqual(jasmine.stringMatching (/c_scale,l_text:roboto_25_bold:SDK,w_300\/e_art:hokusai,g_auto\/f_auto\/responsive_sample.jpg/)); expect(img.attributes.getNamedItem('data-src').value).toEqual(jasmine.stringMatching( /c_scale,l_text:roboto_25_bold:SDK,w_300\/e_art:hokusai,g_auto\/f_auto\/responsive_sample.jpg/)); }); }); describe('images with overlay/underlay', () => { @Component({ template: ` <cl-image responsive id="image1" public-id="responsive_sample.jpg"> <cl-transformation overlay="fetch:http://cloudinary.com/images/old_logo.png"></cl-transformation> <cl-transformation underlay="fetch:http://cloudinary.com/images/old_logo.png"></cl-transformation> </cl-image> <cl-image responsive id="image2" public-id="responsive_sample.jpg"> <cl-transformation overlay="fetch:https://upload.wikimedia.org/wikipedia/commons/2/2b/고창갯벌.jpg"></cl-transformation> <cl-transformation underlay="fetch:https://upload.wikimedia.org/wikipedia/commons/2/2b/고창갯벌.jpg"></cl-transformation> </cl-image> ` }) class TestComponent { } let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: localCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached CloudinaryImage des = fixture.debugElement.queryAll(By.directive(CloudinaryImage)); }); it('should serialize a fetch URL', () => { const img = des[0].children[0].nativeElement as HTMLImageElement; expect(img.src).toEqual(jasmine.stringMatching (/l_fetch:aHR0cDovL2Nsb3VkaW5hcnkuY29tL2ltYWdlcy9vbGRfbG9nby5wbmc=\/u_fetch:aHR0cDovL2Nsb3VkaW5hcnkuY29tL2ltYWdlcy9vbGRfbG9nby5wbmc=\/responsive_sample.jpg/)); expect(img.attributes.getNamedItem('data-src').value).toEqual(jasmine.stringMatching( /l_fetch:aHR0cDovL2Nsb3VkaW5hcnkuY29tL2ltYWdlcy9vbGRfbG9nby5wbmc=\/u_fetch:aHR0cDovL2Nsb3VkaW5hcnkuY29tL2ltYWdlcy9vbGRfbG9nby5wbmc=\/responsive_sample.jpg/)); }); it('should support unicode URLs', () => { const img = des[1].children[0].nativeElement as HTMLImageElement; expect(img.src).toEqual(jasmine.stringMatching( new RegExp('l_fetch:aHR0cHM6Ly91cGxvYWQud2lraW1lZGlhLm9yZy93aWtpcGVkaWEvY29tbW9ucy8yLzJiLyVFQSVCMyVB' + 'MCVFQyVCMCVCRCVFQSVCMCVBRiVFQiVCMiU4Qy5qcGc=/u_fetch:aHR0cHM6Ly91cGxvYWQud2lraW1lZGlhLm9yZy93aWtpcGVkaWEv' + 'Y29tbW9ucy8yLzJiLyVFQSVCMyVBMCVFQyVCMCVCRCVFQSVCMCVBRiVFQiVCMiU4Qy5qcGc=/responsive_sample.jpg'))); expect(img.attributes.getNamedItem('data-src').value).toEqual(jasmine.stringMatching( new RegExp('l_fetch:aHR0cHM6Ly91cGxvYWQud2lraW1lZGlhLm9yZy93aWtpcGVkaWEvY29tbW9ucy8yLzJiLyVFQSVCMyVB' + 'MCVFQyVCMCVCRCVFQSVCMCVBRiVFQiVCMiU4Qy5qcGc=/u_fetch:aHR0cHM6Ly91cGxvYWQud2lraW1lZGlhLm9yZy93aWtpcGVkaWEv' + 'Y29tbW9ucy8yLzJiLyVFQSVCMyVBMCVFQyVCMCVCRCVFQSVCMCVBRiVFQiVCMiU4Qy5qcGc=/responsive_sample.jpg'))); }); }); describe('transformation attributes: quality', () => { @Component({ template: ` <cl-image responsive id="image1" public-id="responsive_sample.jpg"> <cl-transformation quality="0.4"></cl-transformation> </cl-image> <cl-image responsive id="image2" public-id="responsive_sample.jpg"> <cl-transformation quality="auto"></cl-transformation> </cl-image> <cl-image responsive id="image3" public-id="responsive_sample.jpg"> <cl-transformation quality="auto:good"></cl-transformation> </cl-image> ` }) class TestComponent { } let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: localCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached CloudinaryImage des = fixture.debugElement.queryAll(By.directive(CloudinaryImage)); }); it('creates an img element which encodes the quality parameter to URL', () => { const testResults = ['q_0.4', 'q_auto', 'q_auto:good']; testResults.forEach((result, index) => { const img = des[index].children[0].nativeElement as HTMLImageElement; expect(img.src).toEqual(jasmine.stringMatching (new RegExp(`\/${result}\/responsive_sample.jpg`))); }); }); }); describe('missing public-id', () => { @Component({ template: '<cl-image responsive id="image1"></cl-image>' }) class TestComponent { } it('throws if the directive is missing a public-id attribute', () => { const fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: localCloudinary }] }).createComponent(TestComponent); expect(() => { fixture.detectChanges(); }).toThrowError(/You must set the public id of the image to load/i); }); }); describe('non-responsive images with nested transformations', () => { @Component({ template: `<cl-image id="image1" public-id="responsive_sample.jpg"> <cl-transformation width="300" crop="scale" overlay="text:roboto_35_bold:SDK"></cl-transformation> <cl-transformation effect="art:hokusai"></cl-transformation> <cl-transformation fetch-format="auto"></cl-transformation> <cl-transformation if="initialWidth > 400" effect="grayscale"></cl-transformation> <cl-transformation if="initialHeight < 200" effect="blur"></cl-transformation> </cl-image>` }) class TestComponent { } let fixture: ComponentFixture<TestComponent>; let des: DebugElement; // the elements w/ the directive beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: localCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached CloudinaryImage des = fixture.debugElement.query(By.directive(CloudinaryImage)); }); it('creates an img element which encodes the directive attributes to the URL', () => { const img = des.children[0].nativeElement as HTMLImageElement; expect(img.src).toEqual(jasmine.stringMatching (/c_scale,l_text:roboto_35_bold:SDK,w_300\/e_art:hokusai\/f_auto\/if_iw_gt_400,e_grayscale\/if_ih_lt_200,e_blur\/responsive_sample.jpg/)); expect(img.attributes.getNamedItem('data-src')).toBeNull(); }); it('updates the underlying img dynamically by updating attributes', (done) => { // Couldn't get this to work with Angular's async or fakesync // Add another mutation observer on the node to be able to // verify the change const observer = new MutationObserver(() => { const img = des.children[0].nativeElement as HTMLImageElement; expect(img.src).toEqual(jasmine.stringMatching (/c_scale,l_text:roboto_35_bold:SDK,w_300\/e_art:hokusai\/f_auto\/if_iw_gt_400,e_grayscale\/if_ih_lt_200,e_blur\/o_50\/responsive_sample.jpg/)); observer.disconnect(); done(); }); // Observe changes to attributes or child transformations to re-render the image const config = { attributes: true, childList: true }; // pass in the target node, as well as the observer options observer.observe(des.nativeElement, config); des.nativeElement.setAttribute('opacity', '50'); }); }); describe('should support custom function remote', () => { @Component({ template: ` <cl-image public-id="sample"> <cl-transformation custom_function='{"function_type":"remote", "source": "https://df34ra4a.execute-api.us-west-2.amazonaws.com/default/cloudinaryFunction"}'></cl-transformation> </cl-image> ` }) class TestComponent { } let fixture: ComponentFixture<TestComponent>; let des: DebugElement; // the elements w/ the directive beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: localCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // Our element under test, which is attached to CloudinaryImage des = fixture.debugElement.query(By.directive(CloudinaryImage)); }); it('creates an img element which encodes the directive attributes to the URL', () => { const img = des.children[0].nativeElement as HTMLImageElement; expect(img.src).toEqual(jasmine.stringMatching (/fn_remote:aHR0cHM6Ly9kZjM0cmE0YS5leGVjdXRlLWFwaS51cy13ZXN0LTIuYW1hem9uYXdzLmNvbS9kZWZhdWx0L2Nsb3VkaW5hcnlGdW5jdGlvbg==\/sample/)); expect(img.attributes.getNamedItem('data-src')).toBeNull(); }); }); describe('should support custom function wasm', () => { @Component({ template: ` <cl-image public-id="sample"> <cl-transformation custom_function='{"function_type":"wasm", "source": "blur.wasm"}'></cl-transformation> </cl-image> ` }) class TestComponent { } let fixture: ComponentFixture<TestComponent>; let des: DebugElement; // the elements w/ the directive beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: localCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // Our element under test, which is attached to CloudinaryImage des = fixture.debugElement.query(By.directive(CloudinaryImage)); }); it('creates an img element which encodes the directive attributes to the URL', () => { const img = des.children[0].nativeElement as HTMLImageElement; expect(img.src).toEqual(jasmine.stringMatching (/fn_wasm:blur.wasm\/sample/)); expect(img.attributes.getNamedItem('data-src')).toBeNull(); }); }); describe('should support user variables', () => { @Component({ template: ` <cl-image public-id="sample"> <cl-transformation variables="[['$imgWidth','150']]"></cl-transformation> <cl-transformation width="$imgWidth" crop="crop" ></cl-transformation> </cl-image> ` }) class TestComponent { } let fixture: ComponentFixture<TestComponent>; let des: DebugElement; // the elements w/ the directive beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: localCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // Our element under test, which is attached to CloudinaryImage des = fixture.debugElement.query(By.directive(CloudinaryImage)); }); it('creates an img element with user variables', () => { const img = des.children[0].nativeElement as HTMLImageElement; expect(img.attributes.getNamedItem('src').value).toEqual('http://res.cloudinary.com/@@fake_angular2_sdk@@/image/upload/$imgWidth_150/c_crop,w_$imgWidth/sample'); }); }); describe('should support user variables with keyword $width', () => { @Component({ template: ` <cl-image public-id="sample"> <cl-transformation variables="[['$width','150']]"></cl-transformation> <cl-transformation width="$width" crop="crop" ></cl-transformation> </cl-image> ` }) class TestComponent { } let fixture: ComponentFixture<TestComponent>; let des: DebugElement; // the elements w/ the directive beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: localCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // Our element under test, which is attached to CloudinaryImage des = fixture.debugElement.query(By.directive(CloudinaryImage)); }); it('creates an img element with user variables $width', () => { const img = des.children[0].nativeElement as HTMLImageElement; expect(img.attributes.getNamedItem('src').value).toEqual('http://res.cloudinary.com/@@fake_angular2_sdk@@/image/upload/$width_150/c_crop,w_$width/sample'); }); }); describe('Sample code presented in README', () => { @Component({ template: ` <cl-image public-id="readme" class="thumbnail inline" angle="20" format="jpg"> <cl-transformation height="150" width="150" crop="fill" effect="sepia" radius="20"></cl-transformation> <cl-transformation overlay="text:arial_60:readme" gravity="north" y="20"></cl-transformation> </cl-image> ` }) class TestComponent { } let fixture: ComponentFixture<TestComponent>; let des: DebugElement; // the elements w/ the directive beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: localCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // Our element under test, which is attached to CloudinaryImage des = fixture.debugElement.query(By.directive(CloudinaryImage)); }); it('creates an img element which encodes the directive attributes to the URL', () => { const img = des.children[0].nativeElement as HTMLImageElement; expect(img.src).toEqual(jasmine.stringMatching (/c_fill,e_sepia,h_150,r_20,w_150\/g_north,l_text:arial_60:readme,y_20\/a_20\/readme.jpg/)); expect(img.attributes.getNamedItem('data-src')).toBeNull(); }); }); describe('Bound public-id', () => { @Component({ template: `<cl-image id="image1" [public-id]="publicId"></cl-image>` }) class TestComponent { publicId: string = 'sample'; } let fixture: ComponentFixture<TestComponent>; let des: DebugElement; // the elements w/ the directive beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: localCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached CloudinaryImage des = fixture.debugElement.query(By.directive(CloudinaryImage)); }); it('creates an img element with a bound public-id', () => { const img = des.children[0].nativeElement as HTMLImageElement; expect(img.src).toEqual(jasmine.stringMatching(/image\/upload\/sample/)); // Update data-bound publicId fixture.componentInstance.publicId = 'updatedId'; fixture.detectChanges(); // Verify that the img src has updated expect(img.src).toEqual(jasmine.stringMatching(/image\/upload\/updatedId/)); }); }); describe('event emitters', () => { let onImageLoad; let onImageError; let des: DebugElement; // the elements w/ the directive @Component({ template: `<cl-image id="image1" [public-id]="publicId"></cl-image>` }) class TestComponent { publicId: string = 'sample'; } let fixture: ComponentFixture<TestComponent>; beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: localCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached CloudinaryImage des = fixture.debugElement.query(By.directive(CloudinaryImage)); onImageLoad = jasmine.createSpy('onImageLoad'); onImageError = jasmine.createSpy('onImageError'); des.componentInstance.onLoad.subscribe(onImageLoad); des.componentInstance.onError.subscribe(onImageError); }); it('calls the onLoad callback when image loads successfully', () => { // Simulate the load event const img = des.children[0].nativeElement as HTMLImageElement; img.dispatchEvent(new Event('load')); expect(onImageLoad).toHaveBeenCalled(); expect(onImageError).not.toHaveBeenCalled(); }); it('calls the onError callback when image fails to load', () => { // Simulate the error event const img = des.children[0].nativeElement as HTMLImageElement; img.dispatchEvent(new CustomEvent('error', { detail: 'Eitan was here' })); expect(onImageLoad).not.toHaveBeenCalled(); expect(onImageError).toHaveBeenCalled(); }); }); describe('responsive images with nested transformations using the cld-responsive attribute', () => { @Component({ template: `<cl-image cld-responsive id="image1" public-id="responsive_sample.jpg"> <cl-transformation width="300" crop="scale" overlay="text:roboto_25_bold:SDK"></cl-transformation> <cl-transformation effect="art:hokusai"></cl-transformation> <cl-transformation fetch-format="auto"></cl-transformation> </cl-image>` }) class TestComponent { } let fixture: ComponentFixture<TestComponent>; let des: DebugElement; // the elements w/ the directive beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: localCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding expect(localCloudinary.responsive).toHaveBeenCalled(); // all elements with an attached CloudinaryImage des = fixture.debugElement.query(By.directive(CloudinaryImage)); }); it('creates an img element which encodes the directive attributes to the URL', () => { const img = des.children[0].nativeElement as HTMLImageElement; expect(img.src).toEqual(jasmine.stringMatching (/c_scale,l_text:roboto_25_bold:SDK,w_300\/e_art:hokusai\/f_auto\/responsive_sample.jpg/)); expect(img.attributes.getNamedItem('data-src').value).toEqual(jasmine.stringMatching( /c_scale,l_text:roboto_25_bold:SDK,w_300\/e_art:hokusai\/f_auto\/responsive_sample.jpg/)); }); }); describe('responsive images with locally configured client hints', () => { @Component({ template: `<cl-image public-id="sample.jpg" [client-hints]="true" responsive> <cl-transformation crop='scale' width='auto' dpr='auto'></cl-transformation> </cl-image>` }) class TestComponent { } let fixture: ComponentFixture<TestComponent>; let des: DebugElement; // the elements w/ the directive beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: localCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached CloudinaryImage des = fixture.debugElement.query(By.directive(CloudinaryImage)); }); it('should not implement responsive behaviour if client hints attribute is true', () => { const img = des.children[0].nativeElement as HTMLImageElement; expect(img.hasAttribute('class')).toBe(false); expect(img.hasAttribute('data-src')).toBe(false); expect(img.attributes.getNamedItem('src').value).toEqual(jasmine.stringMatching(/c_scale,dpr_auto,w_auto/)); }); }); describe('responsive images with global configured client hints', () => { @Component({ template: `<cl-image id="image_1" public-id="sample.jpg" responsive> <cl-transformation crop='scale' width='auto' dpr='auto'></cl-transformation> </cl-image> <cl-image id="image_2" public-id="sample.jpg" [client-hints]="false" responsive> <cl-transformation crop='scale' width='auto' dpr='auto'></cl-transformation> </cl-image>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached CloudinaryImage des = fixture.debugElement.queryAll(By.directive(CloudinaryImage)); }); it('should not implement responsive behaviour if client hints set in config', () => { const img = des[0].children[0].nativeElement as HTMLImageElement; expect(img.hasAttribute('class')).toBe(false); expect(img.hasAttribute('data-src')).toBe(false); expect(img.attributes.getNamedItem('src').value).toEqual(jasmine.stringMatching(/c_scale,dpr_auto,w_auto/)); }); it('should allow to override global client_hints option with tag attribute', () => { const img = des[1].children[0].nativeElement as HTMLImageElement; expect(img.hasAttribute('class')).toBe(true); expect(img.attributes.getNamedItem('src').value).toEqual(jasmine.stringMatching(/c_scale,dpr_auto,w_auto/)); }); }); describe('cl-image styling without placeholder', () => { @Component({ template: `<cl-image public-id="sample.jpg" ></cl-image>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached CloudinaryImage des = fixture.debugElement.queryAll(By.directive(CloudinaryImage)); }); it('should not have style opacity and position', () => { const img = des[0].children[0].nativeElement as HTMLImageElement; expect(img.getAttribute('style')).toEqual(jasmine.stringMatching('')); }); }); describe('cl-image styling with placeholder', () => { @Component({ template: `<div style="margin-top: 4000px"></div> <cl-image public-id="sample.jpg" loading="lazy"> <cl-placeholder></cl-placeholder> </cl-image>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent, CloudinaryPlaceHolder], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached CloudinaryImage des = fixture.debugElement.queryAll(By.directive(CloudinaryImage)); }); it('should have style opacity and position', () => { const img = des[0].children[0].nativeElement as HTMLImageElement; expect(img.getAttribute('style')).toEqual(jasmine.stringMatching('opacity: 0; position: absolute;')); }); }); describe('placeholder with secure', () => { @Component({ template: ` <cl-image public-id="sample.jpg" secure="true"> <cl-placeholder></cl-placeholder> </cl-image>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let placeholder: DebugElement[]; let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(fakeAsync(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent, LazyLoadDirective, CloudinaryPlaceHolder], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached CloudinaryImage placeholder = fixture.debugElement.queryAll(By.directive(CloudinaryPlaceHolder)); tick(); fixture.detectChanges(); })); it('placeholder should have secure URL', () => { const placeholderImg = placeholder[0].children[0].nativeElement as HTMLImageElement; expect(placeholderImg.getAttribute('src')).toEqual('https://res.cloudinary.com/@@fake_angular2_sdk@@/image/upload/e_blur:2000,f_auto,q_1/sample.jpg'); }); }); describe('cl-image with placeholder and html style', () => { @Component({ template: `<div style="margin-top: 4000px"></div> <cl-image loading="lazy" public-id="sample" width="500" crop="fit" style="max-height: 100%"> <cl-placeholder type="blur"></cl-placeholder> </cl-image>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent, CloudinaryPlaceHolder], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached CloudinaryImage des = fixture.debugElement.queryAll(By.directive(CloudinaryImage)); }); it('should have style opacity and position when style is passed', () => { const img = des[0].children[0].nativeElement as HTMLImageElement; expect(img.getAttribute('style')).toEqual(jasmine.stringMatching('max-height: 100%; opacity: 0; position: absolute;')); }); }); describe('cl-image with placeholder and opacity', () => { @Component({ template: `<div></div> <cl-image public-id="sample" style="opacity: 0.5"> <cl-placeholder type="blur"></cl-placeholder> </cl-image>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent, CloudinaryPlaceHolder], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached CloudinaryImage des = fixture.debugElement.queryAll(By.directive(CloudinaryImage)); }); it('should not overwrite input opacity', () => { const img = des[0].nativeElement as HTMLImageElement; expect(img.getAttribute('style')).toEqual(jasmine.stringMatching('opacity: 0.5')); }); }); describe('lazy load image', async () => { @Component({ template: ` <div class="startWindow"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div> <div style="margin-top: 300px"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div> <div style="margin-top: 300px"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div> <div style="margin-top: 300px"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div> <div style="margin-top: 300px"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div> <div style="margin-top: 300px"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div> <div style="margin-top: 300px"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div> <div class="endWindow" style="margin-top: 300px"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent, LazyLoadDirective], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached CloudinaryImage des = fixture.debugElement.queryAll(By.directive(CloudinaryImage)); }); it('should load eagerly', () => { const img = des[0].children[0].nativeElement as HTMLImageElement; expect(img.hasAttribute('data-src')).toBe(true); expect(img.attributes.getNamedItem('data-src').value).toEqual(jasmine.stringMatching('image/upload/bear')); }); it('Should lazy load post scroll', async() => { const delay = 300; const wait = (ms) => new Promise(res => setTimeout(res, ms)); const count = async () => document.querySelectorAll('.startWindow').length; const scrollDown = async () => { document.querySelector('.endWindow') .scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'end' }); } let preCount = 0; let postCount = 0; do { preCount = await count(); await scrollDown(); await wait(delay); postCount = await count(); } while (postCount > preCount); await wait(delay); const img = des[3].children[0].nativeElement as HTMLImageElement; expect(img.hasAttribute('src')).toBe(true); expect(img.attributes.getNamedItem('src').value).toEqual(jasmine.stringMatching('image/upload/bear')); }); }); describe('lazy load image with pixelate placeholder', async () => { @Component({ template: ` <div class="startWindow"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div> <div style="margin-top: 300px"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div> <div style="margin-top: 300px"> <cl-image loading="lazy" width="300" public-id="bear"> <cl-placeholder type="pixelate"></cl-placeholder> </cl-image> </div> <div style="margin-top: 300px"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div> <div class="endWindow" style="margin-top: 300px"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent, LazyLoadDirective, CloudinaryPlaceHolder], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached CloudinaryImage des = fixture.debugElement.queryAll(By.directive(CloudinaryPlaceHolder)); }); it('should load placeholder eagerly', fakeAsync(() => { tick(); fixture.detectChanges(); const img = des[0].children[0].nativeElement as HTMLImageElement; expect(img.attributes.getNamedItem('src').value).toEqual(jasmine.stringMatching('image/upload/e_pixelate,f_auto,q_1/bear')); })); }); describe('placeholder default', () => { @Component({ template: `<cl-image public-id="bear"> <cl-placeholder></cl-placeholder> </cl-image>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent, CloudinaryPlaceHolder], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding des = fixture.debugElement.queryAll(By.directive(CloudinaryPlaceHolder)); }); it('creates an img element with placeholder', fakeAsync(() => { tick(); fixture.detectChanges(); const img = des[0].children[0].nativeElement as HTMLImageElement; expect(img.attributes.getNamedItem('src').value).toEqual(jasmine.stringMatching('image/upload/e_blur:2000,f_auto,q_1/bear')); })); it('creates an img element without styling', fakeAsync(() => { tick(); fixture.detectChanges(); const img = des[0].children[0].nativeElement as HTMLImageElement; expect(img.getAttribute('style')).toEqual(null); })); }); describe('placeholder type blur', () => { @Component({ template: `<cl-image public-id="bear" width="300" crop="fit"> <cl-placeholder type="blur"></cl-placeholder> </cl-image>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent, CloudinaryPlaceHolder], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding des = fixture.debugElement.queryAll(By.directive(CloudinaryPlaceHolder)); }); it('creates an img element with placeholder', fakeAsync(() => { tick(); fixture.detectChanges(); const img = des[0].children[0].nativeElement as HTMLImageElement; expect(img.attributes.getNamedItem('src').value).toEqual(jasmine.stringMatching('c_fit,w_300/e_blur:2000,f_auto,q_1/bear')); })); }); describe('placeholder type pixelate', () => { @Component({ template: `<cl-image public-id="bear" width="300" crop="fit"> <cl-placeholder type="pixelate"></cl-placeholder> </cl-image>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent, CloudinaryPlaceHolder], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding des = fixture.debugElement.queryAll(By.directive(CloudinaryPlaceHolder)); }); it('creates an img element with placeholder', fakeAsync(() => { tick(); fixture.detectChanges(); const img = des[0].children[0].nativeElement as HTMLImageElement; expect(img.attributes.getNamedItem('src').value).toEqual(jasmine.stringMatching('image/upload/c_fit,w_300/e_pixelate,f_auto,q_1/bear')); })); }); describe('placeholder type predominant-color with exact dimensions', () => { @Component({ template: `<cl-image public-id="bear" width="300" height="300" crop="fit"> <cl-placeholder type="predominant-color"></cl-placeholder> </cl-image>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent, CloudinaryPlaceHolder], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding des = fixture.debugElement.queryAll(By.directive(CloudinaryPlaceHolder)); }); it('creates an img element with placeholder size 1 pxl', fakeAsync(() => { tick(); fixture.detectChanges(); const img = des[0].children[0].nativeElement as HTMLImageElement; expect(img.attributes.getNamedItem('src').value).toEqual(jasmine.stringMatching('image/upload/c_fit,h_300,w_300/ar_1,b_auto,' + 'c_pad,w_iw_div_2/c_crop,g_north_east,h_1,w_1/f_auto,q_auto/bear')); })); }); describe('placeholder type predominant-color', () => { @Component({ template: `<cl-image public-id="bear" width="300" crop="fit"> <cl-placeholder type="predominant-color"></cl-placeholder> </cl-image>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent, CloudinaryPlaceHolder], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding des = fixture.debugElement.queryAll(By.directive(CloudinaryPlaceHolder)); }); it('creates an img element with placeholder', fakeAsync(() => { tick(); fixture.detectChanges(); const img = des[0].children[0].nativeElement as HTMLImageElement; expect(img.attributes.getNamedItem('src').value).toEqual('http://res.cloudinary.com/@@fake_angular2_sdk@@/image/' + 'upload/c_fit,w_300/$currWidth_w,$currHeight_h/ar_1,b_auto,c_pad,w_iw_div_2/c_crop,g_north_east,h_10,w_10/c_fill,h_$currHeight,w_$currWidth/f_auto,q_auto/bear'); })); }); describe('placeholder type vectorize', () => { @Component({ template: `<cl-image public-id="bear" width="300" crop="fit"> <cl-placeholder type="vectorize"></cl-placeholder> </cl-image>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent, CloudinaryPlaceHolder], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding des = fixture.debugElement.queryAll(By.directive(CloudinaryPlaceHolder)); }); it('creates an img element with placeholder', fakeAsync(() => { tick(); fixture.detectChanges(); const img = des[0].children[0].nativeElement as HTMLImageElement; expect(img.attributes.getNamedItem('src').value).toEqual(jasmine.stringMatching('image/upload/c_fit,w_300/e_vectorize:3:0.1,f_svg/bear')); })); }); describe('placeholder with cl-transformation', () => { @Component({ template: `<cl-image public-id="bear" width="300" crop="fit"> <cl-transformation effect="sepia"></cl-transformation> <cl-placeholder type="blur"></cl-placeholder> </cl-image>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent, CloudinaryPlaceHolder], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding des = fixture.debugElement.queryAll(By.directive(CloudinaryPlaceHolder)); }); it('creates an img element with placeholder and cl-transformations', fakeAsync(() => { tick(); fixture.detectChanges(); const img = des[0].children[0].nativeElement as HTMLImageElement; expect(img.attributes.getNamedItem('src').value).toEqual(jasmine.stringMatching('e_sepia/c_fit,w_300/e_blur:2000,f_auto,q_1/bear')); })); }); describe('cl-image with acessibility modes', () => { @Component({ template: `<cl-image public-id="bear" accessibility="darkmode"></cl-image> <cl-image public-id="bear" accessibility="monochrome"></cl-image> <cl-image public-id="bear" accessibility="brightmode"></cl-image> <cl-image public-id="bear" accessibility="colorblind"></cl-image>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding des = fixture.debugElement.queryAll(By.directive(CloudinaryImage)); }); it('creates an img element with accessibility darkmode', fakeAsync(() => { const img = des[0].children[0].nativeElement as HTMLImageElement; expect(img.attributes.getNamedItem('src').value).toEqual(jasmine.stringMatching('e_tint:75:black/bear')); })); it('creates an img element with accessibility monochrome', fakeAsync(() => { const img = des[1].children[0].nativeElement as HTMLImageElement; expect(img.attributes.getNamedItem('src').value).toEqual(jasmine.stringMatching('e_grayscale/bear')); })); it('creates an img element with accessibility brightmode', fakeAsync(() => { const img = des[2].children[0].nativeElement as HTMLImageElement; expect(img.attributes.getNamedItem('src').value).toEqual(jasmine.stringMatching('e_tint:50:white/bear')); })); it('creates an img element with accessibility colorblind', fakeAsync(() => { const img = des[3].children[0].nativeElement as HTMLImageElement; expect(img.attributes.getNamedItem('src').value).toEqual(jasmine.stringMatching('e_assist_colorblind/bear')); })); }); describe('cl-image with acessibility modes and transformation', () => { @Component({ template: `<cl-image public-id="bear" accessibility="darkmode" effect="grayscale" overlay="sample"> <cl-transformation effect="sepia"></cl-transformation> </cl-image>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding des = fixture.debugElement.queryAll(By.directive(CloudinaryImage)); }); it('creates an img element with accessibility darkmode without overwriting effect', fakeAsync(() => { const img = des[0].children[0].nativeElement as HTMLImageElement; expect(img.attributes.getNamedItem('src').value).toEqual(jasmine.stringMatching('e_sepia/e_grayscale,l_sample/e_tint:75:black/bear')); })); }); describe('cl-image with responsive and lazy-load', async () => { @Component({ template: `<cl-image loading="lazy" width="300" public-id="bear"></cl-image>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive let placeholder: DebugElement[]; let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(fakeAsync(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent, LazyLoadDirective], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached CloudinaryImage des = fixture.debugElement.queryAll(By.directive(CloudinaryImage)); tick(); fixture.detectChanges(); })); it('src should not exist on Firefox', () => { const img = des[0].children[0].nativeElement as HTMLImageElement; if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) { expect(img).not.toContain('src'); } }); }); describe('cl-image with responsive and placeholder on lazy load', async () => { @Component({ template: `<div class="startWindow"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div> <div style="margin-top: 700px"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div> <div style="margin-top: 700px"><cl-image loading="lazy" public-id="bear" responsive width="auto" crop="scale"> <cl-placeholder></cl-placeholder> </cl-image></div> <div style="margin-top: 700px"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div> <div style="margin-top: 700px"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div> <div style="margin-top: 700px"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div> <div style="margin-top: 700px"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div> <div class="endWindow" style="margin-top: 700px"><cl-image loading="lazy" width="300" public-id="bear"></cl-image></div>` }) class TestComponent {} let fixture: ComponentFixture<TestComponent>; let des: DebugElement[]; // the elements w/ the directive let placeholder: DebugElement[]; let testLocalCloudinary: Cloudinary = new Cloudinary(require('cloudinary-core'), { cloud_name: '@@fake_angular2_sdk@@', client_hints: true } as CloudinaryConfiguration); beforeEach(fakeAsync(() => { fixture = TestBed.configureTestingModule({ declarations: [CloudinaryTransformationDirective, CloudinaryImage, TestComponent, LazyLoadDirective, CloudinaryPlaceHolder], providers: [{ provide: Cloudinary, useValue: testLocalCloudinary }] }).createComponent(TestComponent); fixture.detectChanges(); // initial binding // all elements with an attached CloudinaryImage des = fixture.debugElement.queryAll(By.directive(CloudinaryImage)); placeholder = fixture.debugElement.queryAll(By.directive(CloudinaryPlaceHolder)); tick(); fixture.detectChanges(); })); it('Placeholder width should equal img width on Firefox', async () => { const placeholderimg = placeholder[0].children[0].nativeElement as HTMLImageElement; const img = des[2].children[0].nativeElement as HTMLImageElement; const delay = 300; const wait = (ms) => new Promise(res => setTimeout(res, ms)); const count = async () => document.querySelectorAll('.startWindow').length; const scrollDown = async () => { document.querySelector('.endWindow') .scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'end' }); } let preCount = 0; let postCount = 0; do { preCount = await count(); await scrollDown(); await wait(delay); postCount = await count(); } while (postCount > preCount); await wait(delay); if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) { expect(placeholderimg.attributes.getNamedItem('width')).toEqual(img.attributes.getNamedItem('width')); } }); }); });
the_stack
import { ApprovalRequestData } from "../../../ComplexProperties/ApprovalRequestData"; import { ConflictResolutionMode } from "../../../Enumerations/ConflictResolutionMode"; import { EmailAddress } from "../../../ComplexProperties/EmailAddress"; import { EmailAddressCollection } from "../../../ComplexProperties/EmailAddressCollection"; import { ExchangeService } from "../../ExchangeService"; import { ExchangeVersion } from "../../../Enumerations/ExchangeVersion"; import { FolderId } from "../../../ComplexProperties/FolderId"; import { ItemAttachment } from "../../../ComplexProperties/ItemAttachment"; import { ItemId } from "../../../ComplexProperties/ItemId"; import { MessageBody } from "../../../ComplexProperties/MessageBody"; import { MessageDisposition } from "../../../Enumerations/MessageDisposition"; import { Promise } from '../../../Promise'; import { PropertySet } from "../../PropertySet"; import { ResponseMessage } from "../ResponseObjects/ResponseMessage"; import { ResponseMessageType } from "../../../Enumerations/ResponseMessageType"; import { Schemas } from "../Schemas/Schemas"; import { ServiceObjectSchema } from "../Schemas/ServiceObjectSchema"; import { SuppressReadReceipt } from "../ResponseObjects/SuppressReadReceipt"; import { VotingInformation } from "../../../ComplexProperties/VotingInformation"; import { WellKnownFolderName } from "../../../Enumerations/WellKnownFolderName"; import { XmlElementNames } from "../../XmlElementNames"; import { Item } from "./Item"; /** * Represents an **e-mail message**. Properties available on e-mail messages are defined in the *EmailMessageSchema* class. * */ export class EmailMessage extends Item { /** required to check [Attachable] attribute, AttachmentCollection.AddItemAttachment<TItem>() checks for non inherited [Attachable] attribute. */ public static get Attachable(): boolean { return (<any>this).name === "EmailMessage"; }; /** * Gets the list of To recipients for the e-mail message. * */ get ToRecipients(): EmailAddressCollection { return <EmailAddressCollection>this.PropertyBag._getItem(Schemas.EmailMessageSchema.ToRecipients); } /** * Gets the list of Bcc recipients for the e-mail message. * */ get BccRecipients(): EmailAddressCollection { return <EmailAddressCollection>this.PropertyBag._getItem(Schemas.EmailMessageSchema.BccRecipients); } /** * Gets the list of Cc recipients for the e-mail message. * */ get CcRecipients(): EmailAddressCollection { return <EmailAddressCollection>this.PropertyBag._getItem(Schemas.EmailMessageSchema.CcRecipients); } /** * Gets the conversation topic of the e-mail message. * */ get ConversationTopic(): string { return <string>this.PropertyBag._getItem(Schemas.EmailMessageSchema.ConversationTopic); } /** * Gets the conversation index of the e-mail message. * */ get ConversationIndex(): number[] { return <number[]>this.PropertyBag._getItem(Schemas.EmailMessageSchema.ConversationIndex); } /** * Gets or sets the "on behalf" sender of the e-mail message. * */ get From(): EmailAddress { return <EmailAddress>this.PropertyBag._getItem(Schemas.EmailMessageSchema.From); } set From(value: EmailAddress) { this.PropertyBag._setItem(Schemas.EmailMessageSchema.From, value); } /** * Gets or sets a value indicating whether this is an associated message. * */ get IsAssociated(): boolean { return this.IsAssociated; } set IsAssociated(value: boolean) { this.PropertyBag._setItem(Schemas.ItemSchema.IsAssociated, value); } /** * Gets or sets a value indicating whether a read receipt is requested for the e-mail message. * */ get IsDeliveryReceiptRequested(): boolean { return <boolean>this.PropertyBag._getItem(Schemas.EmailMessageSchema.IsDeliveryReceiptRequested); } set IsDeliveryReceiptRequested(value: boolean) { this.PropertyBag._setItem(Schemas.EmailMessageSchema.IsDeliveryReceiptRequested, value); } /** * Gets or sets a value indicating whether the e-mail message is read. * */ get IsRead(): boolean { return <boolean>this.PropertyBag._getItem(Schemas.EmailMessageSchema.IsRead); } set IsRead(value: boolean) { this.PropertyBag._setItem(Schemas.EmailMessageSchema.IsRead, value); } /** * Gets or sets a value indicating whether a read receipt is requested for the e-mail message. * */ get IsReadReceiptRequested(): boolean { return <boolean>this.PropertyBag._getItem(Schemas.EmailMessageSchema.IsReadReceiptRequested); } set IsReadReceiptRequested(value: boolean) { this.PropertyBag._setItem(Schemas.EmailMessageSchema.IsReadReceiptRequested, value); } /** * Gets or sets a value indicating whether a response is requested for the e-mail message. * */ get IsResponseRequested(): boolean { return <boolean>this.PropertyBag._getItem(Schemas.EmailMessageSchema.IsResponseRequested); } set IsResponseRequested(value: boolean) { this.PropertyBag._setItem(Schemas.EmailMessageSchema.IsResponseRequested, value); } /** * Gets the Internat Message Id of the e-mail message. * */ get InternetMessageId(): string { return <string>this.PropertyBag._getItem(Schemas.EmailMessageSchema.InternetMessageId); } /** * Gets or sets the references of the e-mail message. * */ get References(): string { return <string>this.PropertyBag._getItem(Schemas.EmailMessageSchema.References); } set References(value: string) { this.PropertyBag._setItem(Schemas.EmailMessageSchema.References, value); } /** * Gets a list of e-mail addresses to which replies should be addressed. * */ get ReplyTo(): EmailAddressCollection { return <EmailAddressCollection>this.PropertyBag._getItem(Schemas.EmailMessageSchema.ReplyTo); } /** * Gets or sets the sender of the e-mail message. * */ get Sender(): EmailAddress { return <EmailAddress>this.PropertyBag._getItem(Schemas.EmailMessageSchema.Sender); } set Sender(value: EmailAddress) { this.PropertyBag._setItem(Schemas.EmailMessageSchema.Sender, value); } /** * Gets the ReceivedBy property of the e-mail message. * */ get ReceivedBy(): EmailAddress { return <EmailAddress>this.PropertyBag._getItem(Schemas.EmailMessageSchema.ReceivedBy); } /** * Gets the ReceivedRepresenting property of the e-mail message. * */ get ReceivedRepresenting(): EmailAddress { return <EmailAddress>this.PropertyBag._getItem(Schemas.EmailMessageSchema.ReceivedRepresenting); } /** * Gets the ApprovalRequestData property of the e-mail message. * */ get ApprovalRequestData(): ApprovalRequestData { return <ApprovalRequestData>this.PropertyBag._getItem(Schemas.EmailMessageSchema.ApprovalRequestData); } /** * Gets the VotingInformation property of the e-mail message. * */ get VotingInformation(): VotingInformation { return <VotingInformation>this.PropertyBag._getItem(Schemas.EmailMessageSchema.VotingInformation); } /** * Initializes an unsaved local instance of **EmailMessage**. To bind to an existing e-mail message, use EmailMessage.Bind() instead. * * @param {ExchangeService} service The ExchangeService object to which the e-mail message will be bound. */ constructor(service: ExchangeService); /** * @internal Initializes a new instance of the **EmailMessage** class. * * @param {ItemAttachment} parentAttachment The parent attachment. */ constructor(parentAttachment: ItemAttachment); /** * @internal ~~**used for super call, easier to manage, do not use in Actual code. //todo:fix - [ ] remove from d.ts file**~~. */ constructor(serviceOrParentAttachment: ExchangeService | ItemAttachment); constructor(serviceOrParentAttachment: ExchangeService | ItemAttachment) { super(serviceOrParentAttachment); } /** * Binds to an existing e-mail message and loads its first class properties. Calling this method results in a call to EWS. * * @param {ExchangeService} service The service to use to bind to the e-mail message. * @param {ItemId} id The Id of the e-mail message to bind to. * @return {Promise<EmailMessage>} An EmailMessage instance representing the e-mail message corresponding to the specified Id :Promise. */ static Bind(service: ExchangeService, id: ItemId): Promise<EmailMessage>; /** * Binds to an existing e-mail message and loads the specified set of properties. Calling this method results in a call to EWS. * * @param {ExchangeService} service The service to use to bind to the e-mail message. * @param {ItemId} id The Id of the e-mail message to bind to. * @param {PropertySet} propertySet The set of properties to load. * @return {Promise<EmailMessage>} An EmailMessage instance representing the e-mail message corresponding to the specified Id :Promise. */ static Bind(service: ExchangeService, id: ItemId, propertySet: PropertySet): Promise<EmailMessage>; static Bind(service: ExchangeService, id: ItemId, propertySet: PropertySet = PropertySet.FirstClassProperties): Promise<EmailMessage> { return service.BindToItem<EmailMessage>(id, propertySet, EmailMessage); } /** * Creates a forward response to the message. * * @return {ResponseMessage} A ResponseMessage representing the forward response that can subsequently be modified and sent. */ CreateForward(): ResponseMessage { this.ThrowIfThisIsNew(); return new ResponseMessage(this, ResponseMessageType.Forward); } /** * Creates a reply response to the message. * * @param {boolean} replyAll Indicates whether the reply should go to all of the original recipients of the message. * @return {ResponseMessage} A ResponseMessage representing the reply response that can subsequently be modified and sent. */ CreateReply(replyAll: boolean): ResponseMessage { this.ThrowIfThisIsNew(); return new ResponseMessage( this, replyAll ? ResponseMessageType.ReplyAll : ResponseMessageType.Reply); } //Forward(bodyPrefix: MessageBody, toRecipients: EmailAddress[]): Promise<void> { throw new Error("EmailMessage.ts - Forward : Not implemented."); } //Forward(bodyPrefix: MessageBody, toRecipients: System.Collections.Generic.IEnumerable<T>): Promise<void> { throw new Error("EmailMessage.ts - Forward : Not implemented."); } /** * Forwards the message. Calling this method results in a call to EWS. * * @param {MessageBody} bodyPrefix The prefix to prepend to the original body of the message. * @param {EmailAddress[]} toRecipients The recipients to forward the message to. */ Forward(bodyPrefix: MessageBody, toRecipients: EmailAddress[]): Promise<void> { var responseMessage: ResponseMessage = this.CreateForward(); responseMessage.BodyPrefix = bodyPrefix; responseMessage.ToRecipients.AddRange(toRecipients); return responseMessage.SendAndSaveCopy(); } /** * @internal Gets the minimum required server version. * * @return {ExchangeVersion} Earliest Exchange version in which this service object type is supported. */ GetMinimumRequiredServerVersion(): ExchangeVersion { return ExchangeVersion.Exchange2007_SP1; } /** * @internal Internal method to return the schema associated with this type of object. * * @return {ServiceObjectSchema} The schema associated with this type of object. */ GetSchema(): ServiceObjectSchema { return Schemas.EmailMessageSchema.Instance; } /** * @internal Gets the element name of item in XML * * @return {string} name of elelment */ GetXmlElementName(): string { return XmlElementNames.Message; } /** * Send message. * * @param {FolderId} parentFolderId The parent folder id. * @param {MessageDisposition} messageDisposition The message disposition. */ private InternalSend(parentFolderId: FolderId, messageDisposition: MessageDisposition): Promise<void> { this.ThrowIfThisIsAttachment(); if (this.IsNew) { if ((this.Attachments.Count == 0) || (messageDisposition == MessageDisposition.SaveOnly)) { return this.InternalCreate( parentFolderId, messageDisposition, null); } else { // If the message has attachments, save as a draft (and add attachments) before sending. return this.InternalCreate( null, // null means use the Drafts folder in the mailbox of the authenticated user. MessageDisposition.SaveOnly, null).then<void>(() => { return this.Service.SendItem(this, parentFolderId); }); } } else { // Regardless of whether item is dirty or not, if it has unprocessed // attachment changes, process them now. //debugger; //todo: check - check for attachment save() promise. return Promise.resolve( // Validate and save attachments before sending. this.HasUnprocessedAttachmentChanges() ? this.Attachments.ValidateAndSave() : void 0) .then(() => { if (this.PropertyBag.GetIsUpdateCallNecessary()) { return <any>this.InternalUpdate( //ref: //info: <any> to supress cast error, returning promise is required, this time it is not void but no action is taken on this promise. parentFolderId, ConflictResolutionMode.AutoResolve, messageDisposition, null); } else { return this.Service.SendItem(this, parentFolderId); } }); } } /** * Replies to the message. Calling this method results in a call to EWS. * * @param {MessageBody} bodyPrefix The prefix to prepend to the original body of the message. * @param {boolean} replyAll Indicates whether the reply should be sent to all of the original recipients of the message. */ Reply(bodyPrefix: MessageBody, replyAll: boolean): Promise<void> { var responseMessage: ResponseMessage = this.CreateReply(replyAll); responseMessage.BodyPrefix = bodyPrefix; return responseMessage.SendAndSaveCopy(); } /** * Sends this e-mail message. Calling this method results in at least one call to EWS. */ Send(): Promise<void> { return this.InternalSend(null, MessageDisposition.SendOnly); } /** * Sends this e-mail message and saves a copy of it in the Sent Items folder. SendAndSaveCopy does not work if the message has unsaved attachments. In that case, the message must first be saved and then sent. Calling this method results in a call to EWS. * */ SendAndSaveCopy(): Promise<void>; /** * Sends this e-mail message and saves a copy of it in the specified folder. SendAndSaveCopy does not work if the message has unsaved attachments. In that case, the message must first be saved and then sent. Calling this method results in a call to EWS. * * @param {WellKnownFolderName} destinationFolderName The name of the folder in which to save the copy. */ SendAndSaveCopy(destinationFolderName: WellKnownFolderName): Promise<void>; /** * Sends this e-mail message and saves a copy of it in the specified folder. SendAndSaveCopy does not work if the message has unsaved attachments. In that case, the message must first be saved and then sent. Calling this method results in a call to EWS. * * @param {FolderId} destinationFolderId The Id of the folder in which to save the copy. */ SendAndSaveCopy(destinationFolderId: FolderId): Promise<void>; SendAndSaveCopy(destinationFolderIdOrName?: FolderId | WellKnownFolderName): Promise<void> { var destinationFolderId: FolderId = new FolderId(WellKnownFolderName.SentItems); if (arguments.length === 1) { if (typeof destinationFolderIdOrName === "number") { destinationFolderId = new FolderId(destinationFolderIdOrName); } else { //EwsUtilities.ValidateParam(destinationFolderIdOrName, "destinationFolderId"); destinationFolderId = destinationFolderIdOrName; } } return this.InternalSend(destinationFolderId, MessageDisposition.SendAndSaveCopy); } /** * Suppresses the read receipt on the message. Calling this method results in a call to EWS. * */ SuppressReadReceipt(): Promise<void> { this.ThrowIfThisIsNew(); return (new SuppressReadReceipt(this)).InternalCreate(null, null); } }
the_stack
import type { ElementLocation } from 'parse5'; import type { EcmarkupError, Options } from './ecmarkup'; import type { OneOfList, RightHandSide, SourceFile, Production as GMDProduction, } from 'grammarkdown'; import type { Context } from './Context'; import type { AlgorithmBiblioEntry, ExportedBiblio, StepBiblioEntry, Type } from './Biblio'; import type { BuilderInterface } from './Builder'; import * as path from 'path'; import * as fs from 'fs'; import * as crypto from 'crypto'; import * as yaml from 'js-yaml'; import * as utils from './utils'; import * as hljs from 'highlight.js'; // Builders import Import, { EmuImportElement } from './Import'; import Clause from './Clause'; import ClauseNumbers from './clauseNums'; import Algorithm from './Algorithm'; import Dfn from './Dfn'; import Example from './Example'; import Figure from './Figure'; import Note from './Note'; import Toc from './Toc'; import makeMenu from './Menu'; import Production from './Production'; import NonTerminal from './NonTerminal'; import ProdRef from './ProdRef'; import Grammar from './Grammar'; import Xref from './Xref'; import Eqn from './Eqn'; import Biblio from './Biblio'; import Meta from './Meta'; import H1 from './H1'; import { autolink, replacerForNamespace, NO_CLAUSE_AUTOLINK, YES_CLAUSE_AUTOLINK, } from './autolinker'; import { lint } from './lint/lint'; import { CancellationToken } from 'prex'; import type { JSDOM } from 'jsdom'; import type { OrderedListItemNode, parseAlgorithm, UnorderedListItemNode } from 'ecmarkdown'; import { getProductions, rhsMatches, getLocationInGrammarFile } from './lint/utils'; import type { AugmentedGrammarEle } from './Grammar'; const DRAFT_DATE_FORMAT: Intl.DateTimeFormatOptions = { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'UTC', }; const STANDARD_DATE_FORMAT: Intl.DateTimeFormatOptions = { year: 'numeric', month: 'long', timeZone: 'UTC', }; const NO_EMD = new Set(['PRE', 'CODE', 'EMU-PRODUCTION', 'EMU-ALG', 'EMU-GRAMMAR', 'EMU-EQN']); const YES_EMD = new Set(['EMU-GMOD']); // these are processed even if they are nested in NO_EMD contexts interface VisitorMap { [k: string]: BuilderInterface; } interface TextNodeContext { clause: Spec | Clause; node: Node; inAlg: boolean; currentId: string | null; } const builders: BuilderInterface[] = [ Clause, Algorithm, Xref, Dfn, Eqn, Grammar, Production, Example, Figure, NonTerminal, ProdRef, Note, Meta, H1, ]; const visitorMap = builders.reduce((map, T) => { T.elements.forEach(e => (map[e] = T)); return map; }, {} as VisitorMap); // NOTE: This is the public API for spec as used in the types. Do not remove. export default interface Spec { spec: this; opts: Options; rootPath: string; rootDir: string; namespace: string; exportBiblio(): any; generatedFiles: Map<string | null, string>; } export type Warning = | { type: 'global'; ruleId: string; message: string; } | { type: 'node'; node: Text | Element; ruleId: string; message: string; } | { type: 'attr'; node: Element; attr: string; ruleId: string; message: string; } | { type: 'attr-value'; node: Element; attr: string; ruleId: string; message: string; } | { type: 'contents'; node: Text | Element; ruleId: string; message: string; nodeRelativeLine: number; nodeRelativeColumn: number; } | { type: 'raw'; ruleId: string; message: string; line: number; column: number; file?: string; source?: string; }; function wrapWarn(source: string, spec: Spec, warn: (err: EcmarkupError) => void) { return (e: Warning) => { const { message, ruleId } = e; let line: number | undefined; let column: number | undefined; let nodeType: string; let file: string | undefined = undefined; switch (e.type) { case 'global': line = undefined; column = undefined; nodeType = 'html'; break; case 'raw': ({ line, column } = e); nodeType = 'html'; if (e.file != null) { file = e.file; source = e.source!; } break; case 'node': if (e.node.nodeType === 3 /* Node.TEXT_NODE */) { const loc = spec.locate(e.node); if (loc) { file = loc.file; source = loc.source; ({ startLine: line, startCol: column } = loc); } nodeType = 'text'; } else { const loc = spec.locate(e.node as Element); if (loc) { file = loc.file; source = loc.source; ({ startLine: line, startCol: column } = loc.startTag); } nodeType = (e.node as Element).tagName.toLowerCase(); } break; case 'attr': { const loc = spec.locate(e.node); if (loc) { file = loc.file; source = loc.source; ({ line, column } = utils.attrLocation(source, loc, e.attr)); } nodeType = e.node.tagName.toLowerCase(); break; } case 'attr-value': { const loc = spec.locate(e.node); if (loc) { file = loc.file; source = loc.source; ({ line, column } = utils.attrValueLocation(source, loc, e.attr)); } nodeType = e.node.tagName.toLowerCase(); break; } case 'contents': { const { nodeRelativeLine, nodeRelativeColumn } = e; if (e.node.nodeType === 3 /* Node.TEXT_NODE */) { // i.e. a text node, which does not have a tag const loc = spec.locate(e.node); if (loc) { file = loc.file; source = loc.source; line = loc.startLine + nodeRelativeLine - 1; column = nodeRelativeLine === 1 ? loc.startCol + nodeRelativeColumn - 1 : nodeRelativeColumn; } nodeType = 'text'; } else { const loc = spec.locate(e.node); if (loc) { file = loc.file; source = loc.source; line = loc.startTag.endLine + nodeRelativeLine - 1; if (nodeRelativeLine === 1) { column = loc.startTag.endCol + nodeRelativeColumn - 1; } else { column = nodeRelativeColumn; } } nodeType = (e.node as Element).tagName.toLowerCase(); } break; } } warn({ message, ruleId, // we omit source for global errors so that we don't get a codeframe source: e.type === 'global' ? undefined : source, file, nodeType, line, column, }); }; } function isEmuImportElement(node: Node): node is EmuImportElement { return node.nodeType === 1 && node.nodeName === 'EMU-IMPORT'; } export type WorklistItem = { aoid: string | null; effects: string[] }; export function maybeAddClauseToEffectWorklist( effectName: string, clause: Clause, worklist: WorklistItem[] ) { if ( !worklist.some(i => i.aoid === clause.aoid) && clause.canHaveEffect(effectName) && !clause.effects.includes(effectName) ) { clause.effects.push(effectName); worklist.push(clause); } } /*@internal*/ export default class Spec { spec: this; opts: Options; rootPath: string; rootDir: string; sourceText: string; namespace: string; biblio: Biblio; dom: JSDOM; doc: Document; imports: Import[]; node: HTMLElement; nodeIds: Set<string>; subclauses: Clause[]; replacementAlgorithmToContainedLabeledStepEntries: Map<Element, StepBiblioEntry[]>; // map from re to its labeled nodes labeledStepsToBeRectified: Set<string>; replacementAlgorithms: { element: Element; target: string }[]; cancellationToken: CancellationToken; generatedFiles: Map<string | null, string>; log: (msg: string) => void; warn: (err: Warning) => void | undefined; _figureCounts: { [type: string]: number }; _xrefs: Xref[]; _ntRefs: NonTerminal[]; _ntStringRefs: { name: string; loc: { line: number; column: number }; node: Element | Text; namespace: string; }[]; _prodRefs: ProdRef[]; _textNodes: { [s: string]: [TextNodeContext] }; _effectWorklist: Map<string, WorklistItem[]>; _effectfulAOs: Map<string, string[]>; _emuMetasToRender: Set<HTMLElement>; _emuMetasToRemove: Set<HTMLElement>; refsByClause: { [refId: string]: [string] }; private _fetch: (file: string, token: CancellationToken) => PromiseLike<string>; constructor( rootPath: string, fetch: (file: string, token: CancellationToken) => PromiseLike<string>, dom: JSDOM, opts: Options, sourceText: string, token = CancellationToken.none ) { opts = opts || {}; this.spec = this; this.opts = {}; this.rootPath = rootPath; this.rootDir = path.dirname(this.rootPath); this.sourceText = sourceText; this.doc = dom.window.document; this.dom = dom; this._fetch = fetch; this.subclauses = []; this.imports = []; this.node = this.doc.body; this.nodeIds = new Set(); this.replacementAlgorithmToContainedLabeledStepEntries = new Map(); this.labeledStepsToBeRectified = new Set(); this.replacementAlgorithms = []; this.cancellationToken = token; this.generatedFiles = new Map(); this.log = opts.log ?? (() => {}); this.warn = opts.warn ? wrapWarn(sourceText, this, opts.warn) : () => {}; this._figureCounts = { table: 0, figure: 0, }; this._xrefs = []; this._ntRefs = []; this._ntStringRefs = []; this._prodRefs = []; this._textNodes = {}; this._effectWorklist = new Map(); this._effectfulAOs = new Map(); this._emuMetasToRender = new Set(); this._emuMetasToRemove = new Set(); this.refsByClause = Object.create(null); this.processMetadata(); Object.assign(this.opts, opts); if (this.opts.multipage) { if (this.opts.jsOut || this.opts.cssOut) { throw new Error('Cannot use --multipage with --js-out or --css-out'); } if (this.opts.outfile == null) { this.opts.outfile = ''; } if (this.opts.assets !== 'none') { this.opts.jsOut = path.join(this.opts.outfile, 'ecmarkup.js'); this.opts.cssOut = path.join(this.opts.outfile, 'ecmarkup.css'); } } if (typeof this.opts.status === 'undefined') { this.opts.status = 'proposal'; } if (typeof this.opts.toc === 'undefined') { this.opts.toc = true; } if (typeof this.opts.copyright === 'undefined') { this.opts.copyright = true; } if (!this.opts.date) { this.opts.date = new Date(); } if (this.opts.stage != undefined) { this.opts.stage = String(this.opts.stage); } if (!this.opts.location) { this.opts.location = '<no location>'; } this.namespace = this.opts.location; this.biblio = new Biblio(this.opts.location); } public fetch(file: string) { return this._fetch(file, this.cancellationToken); } public async build() { /* The Ecmarkup build process proceeds as follows: 1. Load biblios, making xrefs and auto-linking from external specs work 2. Load imports by recursively inlining the import files' content into the emu-import element 3. Generate boilerplate text 4. Do a walk of the DOM visting elements and text nodes. Text nodes are replaced by text and HTML nodes depending on content. Elements are built by delegating to builders. Builders work by modifying the DOM ahead of them so the new elements they make are visited during the walk. Elements added behind the current iteration must be handled specially (eg. see static exit method of clause). Xref, nt, and prodref's are collected for linking in the next step. 5. Linking. After the DOM walk we have a complete picture of all the symbols in the document so we proceed to link the various xrefs to the proper place. 6. Adding charset, highlighting code, etc. 7. Add CSS & JS dependencies. */ this.log('Loading biblios...'); await this.loadBiblios(); this.log('Loading imports...'); await this.loadImports(); this.log('Building boilerplate...'); this.buildBoilerplate(); const context: Context = { spec: this, node: this.doc.body, importStack: [], clauseStack: [], tagStack: [], clauseNumberer: ClauseNumbers(this), inNoAutolink: false, inAlg: false, inNoEmd: false, followingEmd: null, currentId: null, }; const document = this.doc; if (this.opts.lintSpec) { this.log('Linting...'); const source = this.sourceText; if (source === undefined) { throw new Error('Cannot lint when source text is not available'); } await lint(this.warn, source, this, document); } this.log('Walking document, building various elements...'); const walker = document.createTreeWalker(document.body, 1 | 4 /* elements and text nodes */); await walk(walker, context); const sdoJs = this.generateSDOMap(); this.setReplacementAlgorithmOffsets(); this.autolink(); if (this.opts.lintSpec) { this.log('Checking types...'); this.typecheck(); } this.log('Propagating effect annotations...'); this.propagateEffects(); this.log('Linking xrefs...'); this._xrefs.forEach(xref => xref.build()); this.log('Linking non-terminal references...'); this._ntRefs.forEach(nt => nt.build()); this._emuMetasToRender.forEach(node => { Meta.render(this, node); }); this._emuMetasToRemove.forEach(node => { node.replaceWith(...node.childNodes); }); // TODO: make these look good // this.log('Adding clause labels...'); // this.labelClauses(); if (this.opts.lintSpec) { this._ntStringRefs.forEach(({ name, loc, node, namespace }) => { if (this.biblio.byProductionName(name, namespace) == null) { this.warn({ type: 'contents', ruleId: 'undefined-nonterminal', message: `could not find a definition for nonterminal ${name}`, node, nodeRelativeLine: loc.line, nodeRelativeColumn: loc.column, }); } }); } this.log('Linking production references...'); this._prodRefs.forEach(prod => prod.build()); this.log('Building reference graph...'); this.buildReferenceGraph(); this.highlightCode(); this.setCharset(); const wrapper = this.buildSpecWrapper(); let commonEles: HTMLElement[] = []; let tocJs = ''; if (this.opts.toc) { this.log('Building table of contents...'); if (this.opts.oldToc) { new Toc(this).build(); } else { ({ js: tocJs, eles: commonEles } = makeMenu(this)); } } this.log('Building shortcuts help dialog...'); commonEles.push(this.buildShortcutsHelp()); for (const ele of commonEles) { this.doc.body.insertBefore(ele, this.doc.body.firstChild); } const jsContents = (await concatJs(sdoJs, tocJs)) + `\n;let usesMultipage = ${!!this.opts.multipage}`; const jsSha = sha(jsContents); if (this.opts.multipage) { await this.buildMultipage(wrapper, commonEles, jsSha); } await this.buildAssets(jsContents, jsSha); const file = this.opts.multipage ? path.join(this.opts.outfile!, 'index.html') : this.opts.outfile ?? null; this.generatedFiles.set(file, this.toHTML()); return this; } private labelClauses() { const label = (clause: Clause) => { if (clause.header != null) { if ( clause.signature?.return?.kind === 'completion' && clause.signature.return.completionType !== 'normal' ) { // style="border: 1px #B50000; background-color: #FFE6E6; padding: .2rem;border-radius: 5px;/*! color: white; */font-size: small;vertical-align: middle;/*! line-height: 1em; */border-style: dotted;color: #B50000;cursor: default;user-select: none;" // TODO: make this a different color clause.header.innerHTML += `<span class="clause-tag abrupt-tag" title="this can return an abrupt completion">abrupt</span>`; } // TODO: make this look like the [UC] annotation // TODO: hide this if [UC] is not enabled (maybe) // the querySelector is gross; you are welcome to replace it with a better analysis which actually keeps track of stuff if (clause.node.querySelector('.e-user-code')) { clause.header.innerHTML += `<span class="clause-tag user-code-tag" title="this can invoke user code">user code</span>`; } } for (const sub of clause.subclauses) { label(sub); } }; for (const sub of this.subclauses) { label(sub); } } // right now this just checks that AOs which do/don't return completion records are invoked appropriately // someday, more! private typecheck() { const isCall = (x: Xref) => x.isInvocation && x.clause != null && x.aoid != null; const isUnused = (t: Type) => t.kind === 'unused' || (t.kind === 'completion' && (t.completionType === 'abrupt' || t.typeOfValueIfNormal?.kind === 'unused')); const AOs = this.biblio .localEntries() .filter(e => e.type === 'op' && e.signature?.return != null) as AlgorithmBiblioEntry[]; const onlyPerformed: Map<string, null | 'only performed' | 'top'> = new Map( AOs.filter(e => !isUnused(e.signature!.return!)).map(a => [a.aoid, null]) ); const alwaysAssertedToBeNormal: Map<string, null | 'always asserted normal' | 'top'> = new Map( AOs.filter(e => e.signature!.return!.kind === 'completion').map(a => [a.aoid, null]) ); for (const xref of this._xrefs) { if (!isCall(xref)) { continue; } const biblioEntry = this.biblio.byAoid(xref.aoid); if (biblioEntry == null) { this.warn({ type: 'node', node: xref.node, ruleId: 'xref-biblio', message: `could not find biblio entry for xref ${JSON.stringify(xref.aoid)}`, }); continue; } const signature = biblioEntry.signature; if (signature == null) { continue; } const { return: returnType } = signature; if (returnType == null) { continue; } // this is really gross // i am sorry // the better approach is to make the xref-linkage logic happen on the level of the ecmarkdown tree // so that we still have this information at that point // rather than having to reconstruct it, approximately // ... someday! const warn = (message: string) => { const path = []; let pointer: HTMLElement | null = xref.node; let alg: HTMLElement | null = null; while (pointer != null) { if (pointer.tagName === 'LI') { // @ts-ignore path.unshift([].indexOf.call(pointer.parentElement!.children, pointer)); } if (pointer.tagName === 'EMU-ALG') { alg = pointer; break; } pointer = pointer.parentElement; } if (alg?.hasAttribute('example')) { return; } if (alg == null || !{}.hasOwnProperty.call(alg, 'ecmarkdownTree')) { const ruleId = 'completion-invocation'; let pointer: Element | null = xref.node; while (this.locate(pointer) == null) { pointer = pointer.parentElement; if (pointer == null) { break; } } if (pointer == null) { this.warn({ type: 'global', ruleId, message: message + ` but I wasn't able to find a source location to give you, sorry!`, }); } else { this.warn({ type: 'node', node: pointer, ruleId, message, }); } } else { // @ts-ignore const tree = alg.ecmarkdownTree as ReturnType<typeof parseAlgorithm>; let stepPointer: OrderedListItemNode | UnorderedListItemNode = { sublist: tree.contents, } as OrderedListItemNode; for (const step of path) { stepPointer = stepPointer.sublist!.contents[step]; } this.warn({ type: 'contents', node: alg, ruleId: 'invocation-return-type', message, nodeRelativeLine: stepPointer.location.start.line, nodeRelativeColumn: stepPointer.location.start.column, }); } }; const consumedAsCompletion = isConsumedAsCompletion(xref); // checks elsewhere ensure that well-formed documents never have a union of completion and non-completion, so checking the first child suffices // TODO: this is for 'a break completion or a throw completion', which is kind of a silly union; maybe address that in some other way? const isCompletion = returnType.kind === 'completion' || (returnType.kind === 'union' && returnType.types[0].kind === 'completion'); if (['Completion', 'ThrowCompletion', 'NormalCompletion'].includes(xref.aoid)) { if (consumedAsCompletion) { warn( `${xref.aoid} clearly creates a Completion Record; it does not need to be marked as such, and it would not be useful to immediately unwrap its result` ); } } else if (isCompletion && !consumedAsCompletion) { warn(`${xref.aoid} returns a Completion Record, but is not consumed as if it does`); } else if (!isCompletion && consumedAsCompletion) { warn(`${xref.aoid} does not return a Completion Record, but is consumed as if it does`); } if (returnType.kind === 'unused' && !isCalledAsPerform(xref, false)) { warn( `${xref.aoid} does not return a meaningful value and should only be invoked as \`Perform ${xref.aoid}(...).\`` ); } if (onlyPerformed.has(xref.aoid) && onlyPerformed.get(xref.aoid) !== 'top') { const old = onlyPerformed.get(xref.aoid); const performed = isCalledAsPerform(xref, true); if (!performed) { onlyPerformed.set(xref.aoid, 'top'); } else if (old === null) { onlyPerformed.set(xref.aoid, 'only performed'); } } if ( alwaysAssertedToBeNormal.has(xref.aoid) && alwaysAssertedToBeNormal.get(xref.aoid) !== 'top' ) { const old = alwaysAssertedToBeNormal.get(xref.aoid); const asserted = isAssertedToBeNormal(xref); if (!asserted) { alwaysAssertedToBeNormal.set(xref.aoid, 'top'); } else if (old === null) { alwaysAssertedToBeNormal.set(xref.aoid, 'always asserted normal'); } } } for (const [aoid, state] of onlyPerformed) { if (state !== 'only performed') { continue; } const message = `${aoid} is only ever invoked with Perform, so it should return ~unused~ or a Completion Record which, if normal, contains ~unused~`; const ruleId = 'perform-not-unused'; const biblioEntry = this.biblio.byAoid(aoid)!; if (biblioEntry._node) { this.spec.warn({ type: 'node', ruleId, message, node: biblioEntry._node, }); } else { this.spec.warn({ type: 'global', ruleId, message, }); } } for (const [aoid, state] of alwaysAssertedToBeNormal) { if (state !== 'always asserted normal') { continue; } if (aoid === 'AsyncGeneratorAwaitReturn') { // TODO remove this when https://github.com/tc39/ecma262/issues/2412 is fixed continue; } const message = `every call site of ${aoid} asserts the return value is a normal completion; it should be refactored to not return a completion record at all`; const ruleId = 'always-asserted-normal'; const biblioEntry = this.biblio.byAoid(aoid)!; if (biblioEntry._node) { this.spec.warn({ type: 'node', ruleId, message, node: biblioEntry._node, }); } else { this.spec.warn({ type: 'global', ruleId, message, }); } } } private toHTML() { const htmlEle = this.doc.documentElement; return '<!doctype html>\n' + (htmlEle.hasAttributes() ? htmlEle.outerHTML : htmlEle.innerHTML); } public locate( node: Element | Node ): ({ file?: string; source: string } & ElementLocation) | undefined { let pointer: Element | Node | null = node; while (pointer != null) { if (isEmuImportElement(pointer)) { break; } pointer = pointer.parentElement; } const dom = pointer == null ? this.dom : pointer.dom; if (!dom) { return; } // the jsdom types are wrong const loc = dom.nodeLocation(node) as unknown as ElementLocation; if (loc) { // we can't just spread `loc` because not all properties are own/enumerable const out: ReturnType<Spec['locate']> = { source: this.sourceText, startTag: loc.startTag, endTag: loc.endTag, startOffset: loc.startOffset, endOffset: loc.endOffset, attrs: loc.attrs, startLine: loc.startLine, startCol: loc.startCol, endLine: loc.endLine, endCol: loc.endCol, }; if (pointer != null) { out.file = pointer.importPath!; out.source = pointer.source!; } return out; } } private buildReferenceGraph() { const refToClause = this.refsByClause; const setParent = (node: Element) => { let pointer: Node | null = node; while (pointer && !['EMU-CLAUSE', 'EMU-INTRO', 'EMU-ANNEX'].includes(pointer.nodeName)) { pointer = pointer.parentNode; } // @ts-ignore if (pointer == null || pointer.id == null) { // @ts-ignore pointer = { id: 'sec-intro' }; } // @ts-ignore if (refToClause[pointer.id] == null) { // @ts-ignore refToClause[pointer.id] = []; } // @ts-ignore refToClause[pointer.id].push(node.id); }; let counter = 0; this._xrefs.forEach(xref => { let entry = xref.entry; if (!entry || entry.namespace === 'external') return; if (!entry.id && entry.refId) { entry = this.spec.biblio.byId(entry.refId); } if (!xref.id) { const id = `_ref_${counter++}`; xref.node.setAttribute('id', id); xref.id = id; } setParent(xref.node); entry.referencingIds.push(xref.id); }); this._ntRefs.forEach(prod => { const entry = prod.entry; if (!entry || entry.namespace === 'external') return; // if this is the defining nt of an emu-production, don't create a ref if (prod.node.parentNode!.nodeName === 'EMU-PRODUCTION') return; const id = `_ref_${counter++}`; prod.node.setAttribute('id', id); setParent(prod.node); entry.referencingIds.push(id); }); } private checkValidSectionId(ele: Element) { if (!ele.id.startsWith('sec-')) { this.warn({ type: 'node', ruleId: 'top-level-section-id', message: 'When using --multipage, top-level sections must have ids beginning with `sec-`', node: ele, }); return false; } if (!/^[A-Za-z0-9-_]+$/.test(ele.id)) { this.warn({ type: 'node', ruleId: 'top-level-section-id', message: 'When using --multipage, top-level sections must have ids matching /^[A-Za-z0-9-_]+$/', node: ele, }); return false; } if (ele.id.toLowerCase() === 'sec-index') { this.warn({ type: 'node', ruleId: 'top-level-section-id', message: 'When using --multipage, top-level sections must not be named "index"', node: ele, }); return false; } return true; } private propagateEffects() { for (const [effectName, worklist] of this._effectWorklist) { this.propagateEffect(effectName, worklist); } } private propagateEffect(effectName: string, worklist: WorklistItem[]) { const usersOfAoid: Map<string, Set<Clause>> = new Map(); for (const xref of this._xrefs) { if (xref.clause == null || xref.aoid == null) continue; if (!xref.shouldPropagateEffect(effectName)) continue; if (xref.hasAddedEffect(effectName)) { maybeAddClauseToEffectWorklist(effectName, xref.clause, worklist); } const usedAoid = xref.aoid; if (!usersOfAoid.has(usedAoid)) { usersOfAoid.set(usedAoid, new Set()); } usersOfAoid.get(usedAoid)!.add(xref.clause); } while (worklist.length !== 0) { const clause = worklist.shift()!; const aoid = clause.aoid; if (aoid == null || !usersOfAoid.has(aoid)) { continue; } this._effectfulAOs.set(aoid, clause.effects); for (const userClause of usersOfAoid.get(aoid)!) { maybeAddClauseToEffectWorklist(effectName, userClause, worklist); } } } public getEffectsByAoid(aoid: string): string[] | null { if (this._effectfulAOs.has(aoid)) { return this._effectfulAOs.get(aoid)!; } return null; } private async buildMultipage(wrapper: Element, commonEles: Element[], jsSha: string) { let stillIntro = true; const introEles = []; const sections: { name: string; eles: Element[] }[] = []; const containedIdToSection: Map<string, string> = new Map(); const sectionToContainedIds: Map<string, string[]> = new Map(); const clauseTypes = ['EMU-ANNEX', 'EMU-CLAUSE']; // @ts-ignore for (const child of wrapper.children) { if (stillIntro) { if (clauseTypes.includes(child.nodeName)) { throw new Error('cannot make multipage build without intro'); } else if (child.nodeName === 'EMU-INTRO') { stillIntro = false; if (child.id == null) { this.warn({ type: 'node', ruleId: 'top-level-section-id', message: 'When using --multipage, top-level sections must have ids', node: child, }); continue; } if (child.id !== 'sec-intro') { this.warn({ type: 'node', ruleId: 'top-level-section-id', message: 'When using --multipage, the introduction must have id "sec-intro"', node: child, }); continue; } const name = 'index'; introEles.push(child); sections.push({ name, eles: introEles }); const contained: string[] = []; sectionToContainedIds.set(name, contained); for (const item of introEles) { if (item.id) { contained.push(item.id); containedIdToSection.set(item.id, name); } } // @ts-ignore for (const item of [...introEles].flatMap(e => [...e.querySelectorAll('[id]')])) { contained.push(item.id); containedIdToSection.set(item.id, name); } } else { introEles.push(child); } } else { if (!clauseTypes.includes(child.nodeName)) { throw new Error('non-clause children are not yet implemented: ' + child.nodeName); } if (child.id == null) { this.warn({ type: 'node', ruleId: 'top-level-section-id', message: 'When using --multipage, top-level sections must have ids', node: child, }); continue; } if (!this.checkValidSectionId(child)) { continue; } const name = child.id.substring(4); const contained: string[] = []; sectionToContainedIds.set(name, contained); contained.push(child.id); containedIdToSection.set(child.id, name); for (const item of child.querySelectorAll('[id]')) { contained.push(item.id); containedIdToSection.set(item.id, name); } sections.push({ name, eles: [child] }); } } let htmlEle = ''; if (this.doc.documentElement.hasAttributes()) { const clonedHtmlEle = this.doc.documentElement.cloneNode(false) as HTMLElement; clonedHtmlEle.innerHTML = ''; const src = clonedHtmlEle.outerHTML; htmlEle = src.substring(0, src.length - '<head></head><body></body></html>'.length); } const head = this.doc.head.cloneNode(true) as HTMLHeadElement; this.addStyle(head, 'ecmarkup.css'); // omit `../` because we rewrite `<link>` elements below this.addStyle( head, `https://cdnjs.cloudflare.com/ajax/libs/highlight.js/${ (hljs as any).versionString }/styles/base16/solarized-light.min.css` ); const script = this.doc.createElement('script'); script.src = '../ecmarkup.js?cache=' + jsSha; script.setAttribute('defer', ''); head.appendChild(script); const containedMap = JSON.stringify(Object.fromEntries(sectionToContainedIds)).replace( /[\\`$]/g, '\\$&' ); const multipageJsContents = `'use strict'; let multipageMap = JSON.parse(\`${containedMap}\`); ${await utils.readFile(path.join(__dirname, '../js/multipage.js'))} `; if (this.opts.assets !== 'none') { this.generatedFiles.set( path.join(this.opts.outfile!, 'multipage/multipage.js'), multipageJsContents ); } const multipageScript = this.doc.createElement('script'); multipageScript.src = 'multipage.js?cache=' + sha(multipageJsContents); multipageScript.setAttribute('defer', ''); head.insertBefore(multipageScript, head.querySelector('script')); for (const { name, eles } of sections) { this.log(`Generating section ${name}...`); const headClone = head.cloneNode(true) as HTMLHeadElement; const commonClone = commonEles.map(e => e.cloneNode(true)); const clones = eles.map(e => e.cloneNode(true)); const allClones = [headClone, ...commonClone, ...clones]; // @ts-ignore const links = allClones.flatMap(e => [...e.querySelectorAll('a,link')]); for (const link of links) { if (linkIsAbsolute(link)) { continue; } if (linkIsInternal(link)) { let p = link.hash.substring(1); if (!containedIdToSection.has(p)) { try { p = decodeURIComponent(p); } catch { // pass } if (!containedIdToSection.has(p)) { this.warn({ type: 'node', ruleId: 'multipage-link-target', message: 'could not find appropriate section for ' + link.hash, node: link, }); continue; } } const targetSec = containedIdToSection.get(p)!; link.href = (targetSec === 'index' ? './' : targetSec + '.html') + link.hash; } else if (linkIsPathRelative(link)) { link.href = '../' + pathFromRelativeLink(link); } } // @ts-ignore for (const img of allClones.flatMap(e => [...e.querySelectorAll('img')])) { if (!/^(http:|https:|:|\/)/.test(img.src)) { img.src = '../' + img.src; } } // prettier-ignore // @ts-ignore for (const object of allClones.flatMap(e => [...e.querySelectorAll('object[data]')])) { if (!/^(http:|https:|:|\/)/.test(object.data)) { object.data = '../' + object.data; } } if (eles[0].hasAttribute('id')) { const canonical = this.doc.createElement('link'); canonical.setAttribute('rel', 'canonical'); canonical.setAttribute('href', `../#${eles[0].id}`); headClone.appendChild(canonical); } // @ts-ignore const commonHTML = commonClone.map(e => e.outerHTML).join('\n'); // @ts-ignore const clonesHTML = clones.map(e => e.outerHTML).join('\n'); const content = `<!doctype html>${htmlEle}\n${headClone.outerHTML}\n<body>${commonHTML}<div id='spec-container'>${clonesHTML}</div></body>`; this.generatedFiles.set(path.join(this.opts.outfile!, `multipage/${name}.html`), content); } } private async buildAssets(jsContents: string, jsSha: string) { const cssContents = await utils.readFile(path.join(__dirname, '../css/elements.css')); if (this.opts.jsOut) { this.generatedFiles.set(this.opts.jsOut, jsContents); } if (this.opts.cssOut) { this.generatedFiles.set(this.opts.cssOut, cssContents); } if (this.opts.assets === 'none') return; const outDir = this.opts.outfile ? this.opts.multipage ? this.opts.outfile : path.dirname(this.opts.outfile) : process.cwd(); if (this.opts.jsOut) { let skipJs = false; const scripts = this.doc.querySelectorAll('script'); for (let i = 0; i < scripts.length; i++) { const script = scripts[i]; const src = script.getAttribute('src'); if (src && path.normalize(path.join(outDir, src)) === path.normalize(this.opts.jsOut)) { this.log(`Found existing js link to ${src}, skipping inlining...`); skipJs = true; } } if (!skipJs) { const script = this.doc.createElement('script'); script.src = path.relative(outDir, this.opts.jsOut) + '?cache=' + jsSha; script.setAttribute('defer', ''); this.doc.head.appendChild(script); } } else { this.log('Inlining JavaScript assets...'); const script = this.doc.createElement('script'); script.textContent = jsContents; this.doc.head.appendChild(script); } if (this.opts.cssOut) { let skipCss = false; const links = this.doc.querySelectorAll('link[rel=stylesheet]'); for (let i = 0; i < links.length; i++) { const link = links[i]; const href = link.getAttribute('href'); if (href && path.normalize(path.join(outDir, href)) === path.normalize(this.opts.cssOut)) { this.log(`Found existing css link to ${href}, skipping inlining...`); skipCss = true; } } if (!skipCss) { this.addStyle(this.doc.head, path.relative(outDir, this.opts.cssOut)); } } else { this.log('Inlining CSS assets...'); const style = this.doc.createElement('style'); style.textContent = cssContents; this.doc.head.appendChild(style); } this.addStyle( this.doc.head, `https://cdnjs.cloudflare.com/ajax/libs/highlight.js/${ (hljs as any).versionString }/styles/base16/solarized-light.min.css` ); } private addStyle(head: HTMLHeadElement, href: string) { const style = this.doc.createElement('link'); style.setAttribute('rel', 'stylesheet'); style.setAttribute('href', href); // insert early so that the document's own stylesheets can override const firstLink = head.querySelector('link[rel=stylesheet], style'); if (firstLink != null) { head.insertBefore(style, firstLink); } else { head.appendChild(style); } } private buildSpecWrapper() { const elements = this.doc.body.childNodes; const wrapper = this.doc.createElement('div'); wrapper.id = 'spec-container'; while (elements.length > 0) { wrapper.appendChild(elements[0]); } this.doc.body.appendChild(wrapper); return wrapper; } private buildShortcutsHelp() { const shortcutsHelp = this.doc.createElement('div'); shortcutsHelp.setAttribute('id', 'shortcuts-help'); shortcutsHelp.innerHTML = ` <ul> <li><span>Toggle shortcuts help</span><code>?</code></li> <li><span>Toggle "can call user code" annotations</span><code>u</code></li> ${this.opts.multipage ? `<li><span>Navigate to/from multipage</span><code>m</code></li>` : ''} <li><span>Jump to search box</span><code>/</code></li> </ul>`; return shortcutsHelp; } private processMetadata() { const block = this.doc.querySelector('pre.metadata'); if (!block || !block.parentNode) { return; } let data: any; try { data = yaml.safeLoad(block.textContent!); } catch (e: any) { if (typeof e?.mark.line === 'number' && typeof e?.mark.column === 'number') { this.warn({ type: 'contents', ruleId: 'invalid-metadata', message: `metadata block failed to parse: ${e.reason}`, node: block, nodeRelativeLine: e.mark.line + 1, nodeRelativeColumn: e.mark.column + 1, }); } else { this.warn({ type: 'node', ruleId: 'invalid-metadata', message: 'metadata block failed to parse', node: block, }); } return; } finally { block.parentNode.removeChild(block); } Object.assign(this.opts, data); } private async loadBiblios() { this.cancellationToken.throwIfCancellationRequested(); const biblioPaths = []; for (const biblioEle of this.doc.querySelectorAll('emu-biblio')) { const href = biblioEle.getAttribute('href'); if (href == null) { this.spec.warn({ type: 'node', node: biblioEle, ruleId: 'biblio-href', message: 'emu-biblio elements must have an href attribute', }); } else { biblioPaths.push(href); } } const biblioContents = await Promise.all( biblioPaths.map(p => this.fetch(path.join(this.rootDir, p))) ); const biblios = biblioContents.flatMap(c => JSON.parse(c) as ExportedBiblio | ExportedBiblio[]); for (const biblio of biblios.concat(this.opts.extraBiblios ?? [])) { if (biblio?.entries == null) { let message = Object.keys(biblio ?? {}).some(k => k.startsWith('http')) ? 'This is an old-style biblio.' : 'Biblio does not appear to be in the correct format, are you using an old-style biblio?'; message += ' You will need to update it to work with versions of ecmarkup >= 12.0.0.'; throw new Error(message); } this.biblio.addExternalBiblio(biblio); for (const entry of biblio.entries) { if (entry.type === 'op' && entry.effects?.length > 0) { this._effectfulAOs.set(entry.aoid, entry.effects); for (const effect of entry.effects) { if (!this._effectWorklist.has(effect)) { this._effectWorklist.set(effect, []); } this._effectWorklist.get(effect)!.push(entry); } } } } } private async loadImports() { await loadImports(this, this.spec.doc.body, this.rootDir); } public exportBiblio(): ExportedBiblio | null { if (!this.opts.location) { this.warn({ type: 'global', ruleId: 'no-location', message: "no spec location specified; biblio not generated. try setting the location in the document's metadata block", }); return null; } return this.biblio.export(); } private highlightCode() { this.log('Highlighting syntax...'); const codes = this.doc.querySelectorAll('pre code'); for (let i = 0; i < codes.length; i++) { const classAttr = codes[i].getAttribute('class'); if (!classAttr) continue; const language = classAttr.replace(/lang(uage)?-/, ''); let input = codes[i].textContent!; // remove leading and trailing blank lines input = input.replace(/^(\s*[\r\n])+|([\r\n]\s*)+$/g, ''); // remove base inden based on indent of first non-blank line const baseIndent = input.match(/^\s*/) || ''; const baseIndentRe = new RegExp('^' + baseIndent, 'gm'); input = input.replace(baseIndentRe, ''); // @ts-expect-error the type definitions for highlight.js are broken const result = hljs.highlight(input, { language }); codes[i].innerHTML = result.value; codes[i].setAttribute('class', classAttr + ' hljs'); } } private buildBoilerplate() { this.cancellationToken.throwIfCancellationRequested(); const status = this.opts.status!; const version = this.opts.version; const title = this.opts.title; const shortname = this.opts.shortname; const location = this.opts.location; const stage = this.opts.stage; if (this.opts.copyright) { if (status !== 'draft' && status !== 'standard' && !this.opts.contributors) { this.warn({ type: 'global', ruleId: 'no-contributors', message: 'contributors not specified, skipping copyright boilerplate. specify contributors in your frontmatter metadata', }); } else { this.buildCopyrightBoilerplate(); } } // no title boilerplate generated if title not specified if (!title) return; // title if (title && !this._updateBySelector('title', title)) { const titleElem = this.doc.createElement('title'); titleElem.innerHTML = title; this.doc.head.appendChild(titleElem); const h1 = this.doc.createElement('h1'); h1.setAttribute('class', 'title'); h1.innerHTML = title; this.doc.body.insertBefore(h1, this.doc.body.firstChild); } // version string, ala 6th Edition July 2016 or Draft 10 / September 26, 2015 let versionText = ''; let omitShortname = false; if (version) { versionText += version + ' / '; } else if (status === 'proposal' && stage) { versionText += 'Stage ' + stage + ' Draft / '; } else if (shortname && status === 'draft') { versionText += 'Draft ' + shortname + ' / '; omitShortname = true; } else { return; } const defaultDateFormat = status === 'standard' ? STANDARD_DATE_FORMAT : DRAFT_DATE_FORMAT; const date = new Intl.DateTimeFormat('en-US', defaultDateFormat).format(this.opts.date); versionText += date; if (!this._updateBySelector('h1.version', versionText)) { const h1 = this.doc.createElement('h1'); h1.setAttribute('class', 'version'); h1.innerHTML = versionText; this.doc.body.insertBefore(h1, this.doc.body.firstChild); } // shortname and status, ala 'Draft ECMA-262 if (shortname && !omitShortname) { // for proposals, link shortname to location const shortnameLinkHtml = status === 'proposal' && location ? `<a href="${location}">${shortname}</a>` : shortname; const shortnameHtml = status.charAt(0).toUpperCase() + status.slice(1) + ' ' + shortnameLinkHtml; if (!this._updateBySelector('h1.shortname', shortnameHtml)) { const h1 = this.doc.createElement('h1'); h1.setAttribute('class', 'shortname'); h1.innerHTML = shortnameHtml; this.doc.body.insertBefore(h1, this.doc.body.firstChild); } } } private buildCopyrightBoilerplate() { let addressFile: string | undefined; let copyrightFile: string | undefined; let licenseFile: string | undefined; if (this.opts.boilerplate) { if (this.opts.boilerplate.address) { addressFile = path.join(process.cwd(), this.opts.boilerplate.address); } if (this.opts.boilerplate.copyright) { copyrightFile = path.join(process.cwd(), this.opts.boilerplate.copyright); } if (this.opts.boilerplate.license) { licenseFile = path.join(process.cwd(), this.opts.boilerplate.license); } } // Get content from files let address = getBoilerplate(addressFile || 'address'); let copyright = getBoilerplate(copyrightFile || `${this.opts.status}-copyright`); const license = getBoilerplate(licenseFile || 'software-license'); if (this.opts.status === 'proposal') { address = ''; } // Operate on content copyright = copyright.replace(/!YEAR!/g, '' + this.opts.date!.getFullYear()); if (this.opts.contributors) { copyright = copyright.replace(/!CONTRIBUTORS!/g, this.opts.contributors); } let copyrightClause = this.doc.querySelector('.copyright-and-software-license'); if (!copyrightClause) { let last: HTMLElement | undefined; utils.domWalkBackward(this.doc.body, node => { if (last) return false; if (node.nodeName === 'EMU-CLAUSE' || node.nodeName === 'EMU-ANNEX') { last = node as HTMLElement; return false; } }); copyrightClause = this.doc.createElement('emu-annex'); copyrightClause.setAttribute('id', 'sec-copyright-and-software-license'); if (last && last.parentNode) { last.parentNode.insertBefore(copyrightClause, last.nextSibling); } else { this.doc.body.appendChild(copyrightClause); } } copyrightClause.innerHTML = ` <h1>Copyright &amp; Software License</h1> ${address} <h2>Copyright Notice</h2> ${copyright.replace('!YEAR!', '' + this.opts.date!.getFullYear())} <h2>Software License</h2> ${license} `; } private generateSDOMap() { const sdoMap = Object.create(null); this.log('Building SDO map...'); const mainGrammar: Set<Element> = new Set( this.doc.querySelectorAll('emu-grammar[type=definition]:not([example])') ); // we can't just do `:not(emu-annex emu-grammar)` because that selector is too complicated for this version of jsdom for (const annexEle of this.doc.querySelectorAll('emu-annex emu-grammar[type=definition]')) { mainGrammar.delete(annexEle); } const mainProductions: Map<string, { rhs: RightHandSide | OneOfList; rhsEle: Element }[]> = new Map(); for (const grammarEle of mainGrammar) { if (!('grammarSource' in grammarEle)) { // this should only happen if it failed to parse/emit, which we'll have already warned for continue; } for (const [name, { rhses }] of this.getProductions(grammarEle as AugmentedGrammarEle)) { if (mainProductions.has(name)) { mainProductions.set(name, mainProductions.get(name)!.concat(rhses)); } else { mainProductions.set(name, rhses); } } } const sdos = this.doc.querySelectorAll( 'emu-clause[type=sdo],emu-clause[type="syntax-directed operation"]' ); outer: for (const sdo of sdos) { let header: Element | undefined; for (const child of sdo.children) { if (child.tagName === 'SPAN' && child.childNodes.length === 0) { // an `oldid` marker, presumably continue; } if (child.tagName === 'H1') { header = child; break; } this.warn({ type: 'node', node: child, ruleId: 'sdo-name', message: 'expected H1 as first child of syntax-directed operation', }); continue outer; } if (!header) { continue; } const clause = header.firstElementChild!.textContent!; const nameMatch = header.textContent ?.slice(clause.length + 1) .match(/^(?:(?:Static|Runtime) Semantics: )?\s*(\w+)\b/); if (nameMatch == null) { this.warn({ type: 'contents', node: header, ruleId: 'sdo-name', message: 'could not parse name of syntax-directed operation', nodeRelativeLine: 1, nodeRelativeColumn: 1, }); continue; } const sdoName = nameMatch[1]; for (const grammarEle of sdo.children) { if (grammarEle.tagName !== 'EMU-GRAMMAR') { continue; } if (!('grammarSource' in grammarEle)) { // this should only happen if it failed to parse/emit, which we'll have already warned for continue; } // prettier-ignore for (const [name, { production, rhses }] of this.getProductions(grammarEle as AugmentedGrammarEle)) { if (!mainProductions.has(name)) { if (this.biblio.byProductionName(name) != null) { // in an ideal world we'd keep the full grammar in the biblio so we could check for a matching RHS, not just a matching LHS // but, we're not in that world // https://github.com/tc39/ecmarkup/issues/431 continue; } const { line, column } = getLocationInGrammarFile( (grammarEle as AugmentedGrammarEle).grammarSource, production.pos ); this.warn({ type: 'contents', node: grammarEle, nodeRelativeLine: line, nodeRelativeColumn: column, ruleId: 'grammar-shape', message: `could not find definition corresponding to production ${name}`, }); continue; } const mainRhses = mainProductions.get(name)!; for (const { rhs, rhsEle } of rhses) { const matches = mainRhses.filter(p => rhsMatches(rhs, p.rhs)); if (matches.length === 0) { const { line, column } = getLocationInGrammarFile( (grammarEle as AugmentedGrammarEle).grammarSource, rhs.pos ); this.warn({ type: 'contents', node: grammarEle, nodeRelativeLine: line, nodeRelativeColumn: column, ruleId: 'grammar-shape', message: `could not find definition for rhs ${JSON.stringify(rhsEle.textContent)}`, }); continue; } if (matches.length > 1) { const { line, column } = getLocationInGrammarFile( (grammarEle as AugmentedGrammarEle).grammarSource, rhs.pos ); this.warn({ type: 'contents', node: grammarEle, nodeRelativeLine: line, nodeRelativeColumn: column, ruleId: 'grammar-shape', message: `found multiple definitions for rhs ${JSON.stringify(rhsEle.textContent)}`, }); continue; } const match = matches[0].rhsEle; if (match.id === '') { match.id = 'prod-' + sha(`${name} : ${match.textContent}`); } const mainId = match.id; if (rhsEle.id === '') { rhsEle.id = 'prod-' + sha(`[${sdoName}] ${name} ${rhsEle.textContent}`); } if (!{}.hasOwnProperty.call(sdoMap, mainId)) { sdoMap[mainId] = Object.create(null); } const sdosForThisId = sdoMap[mainId]; if (!{}.hasOwnProperty.call(sdosForThisId, sdoName)) { sdosForThisId[sdoName] = { clause, ids: [] }; } else if (sdosForThisId[sdoName].clause !== clause) { this.warn({ type: 'node', node: grammarEle, ruleId: 'grammar-shape', message: `SDO ${sdoName} found in multiple clauses`, }); } sdosForThisId[sdoName].ids.push(rhsEle.id); } } } } const json = JSON.stringify(sdoMap); return `let sdoMap = JSON.parse(\`${json.replace(/[\\`$]/g, '\\$&')}\`);`; } private getProductions(grammarEle: AugmentedGrammarEle) { // unfortunately we need both the element and the grammarkdown node // there is no immediate association between them // so we are going to reconstruct the association by hand const productions: Map< string, { production: GMDProduction; rhses: { rhs: RightHandSide | OneOfList; rhsEle: Element }[] } > = new Map(); const productionEles: Map<string, Array<Element>> = new Map(); for (const productionEle of grammarEle.querySelectorAll('emu-production')) { if (!productionEle.hasAttribute('name')) { // I don't think this is possible, but we can at least be graceful about it this.warn({ type: 'node', // All of these elements are synthetic, and hence lack locations, so we point error messages to the containing emu-grammar node: grammarEle, ruleId: 'grammar-shape', message: 'expected emu-production node to have name', }); continue; } const name = productionEle.getAttribute('name')!; const rhses = [...productionEle.querySelectorAll('emu-rhs')]; if (productionEles.has(name)) { productionEles.set(name, productionEles.get(name)!.concat(rhses)); } else { productionEles.set(name, rhses); } } const sourceFile: SourceFile = grammarEle.grammarSource; for (const [name, { production, rhses }] of getProductions([sourceFile])) { if (!productionEles.has(name)) { this.warn({ type: 'node', node: grammarEle, ruleId: 'rhs-consistency', message: `failed to locate element for production ${name}. This is is a bug in ecmarkup; please report it.`, }); continue; } const rhsEles = productionEles.get(name)!; if (rhsEles.length !== rhses.length) { this.warn({ type: 'node', node: grammarEle, ruleId: 'rhs-consistency', message: `inconsistent RHS lengths for production ${name}. This is is a bug in ecmarkup; please report it.`, }); continue; } productions.set(name, { production, rhses: rhses.map((rhs, i) => ({ rhs, rhsEle: rhsEles[i] })), }); } return productions; } private setReplacementAlgorithmOffsets() { this.log('Finding offsets for replacement algorithm steps...'); const pending: Map<string, Element[]> = new Map(); const setReplacementAlgorithmStart = (element: Element, stepNumbers: number[]) => { const rootList = element.firstElementChild! as HTMLOListElement; rootList.start = stepNumbers[stepNumbers.length - 1]; if (stepNumbers.length > 1) { // Note the off-by-one here: a length of 1 indicates we are replacing a top-level step, which means we do not need to adjust the styling. if (stepNumbers.length === 2) { rootList.classList.add('nested-once'); } else if (stepNumbers.length === 3) { rootList.classList.add('nested-twice'); } else if (stepNumbers.length === 4) { rootList.classList.add('nested-thrice'); } else if (stepNumbers.length === 5) { rootList.classList.add('nested-four-times'); } else { // At the sixth level and deeper (so once we have nested five times) we use a consistent line numbering style, so no further cases are necessary rootList.classList.add('nested-lots'); } } // Fix up the biblio entries for any labeled steps in the algorithm for (const entry of this.replacementAlgorithmToContainedLabeledStepEntries.get(element)!) { entry.stepNumbers = [...stepNumbers, ...entry.stepNumbers.slice(1)]; this.labeledStepsToBeRectified.delete(entry.id); // Now that we've figured out where the step is, we can deal with algorithms replacing it if (pending.has(entry.id)) { const todo = pending.get(entry.id)!; pending.delete(entry.id); for (const replacementAlgorithm of todo) { setReplacementAlgorithmStart(replacementAlgorithm, entry.stepNumbers); } } } }; for (const { element, target } of this.replacementAlgorithms) { if (this.labeledStepsToBeRectified.has(target)) { if (!pending.has(target)) { pending.set(target, []); } pending.get(target)!.push(element); } else { // When the target is not itself within a replacement, or is within a replacement which we have already rectified, we can just use its step number directly const targetEntry = this.biblio.byId(target); if (targetEntry == null) { this.warn({ type: 'attr-value', attr: 'replaces-step', ruleId: 'invalid-replacement', message: `could not find step ${JSON.stringify(target)}`, node: element, }); } else if (targetEntry.type !== 'step') { this.warn({ type: 'attr-value', attr: 'replaces-step', ruleId: 'invalid-replacement', message: `expected algorithm to replace a step, not a ${targetEntry.type}`, node: element, }); } else { setReplacementAlgorithmStart(element, targetEntry.stepNumbers); } } } if (pending.size > 0) { // todo consider line/column missing cases this.warn({ type: 'global', ruleId: 'invalid-replacement', message: 'could not unambiguously determine replacement algorithm offsets - do you have a cycle in your replacement algorithms?', }); } } public autolink() { this.log('Autolinking terms and abstract ops...'); const namespaces = Object.keys(this._textNodes); for (let i = 0; i < namespaces.length; i++) { const namespace = namespaces[i]; const { replacer, autolinkmap } = replacerForNamespace(namespace, this.biblio); const nodes = this._textNodes[namespace]; for (let j = 0; j < nodes.length; j++) { const { node, clause, inAlg, currentId } = nodes[j]; autolink(node, replacer, autolinkmap, clause, currentId, inAlg); } } } public setCharset() { let current = this.spec.doc.querySelector('meta[charset]'); if (!current) { current = this.spec.doc.createElement('meta'); this.spec.doc.head.insertBefore(current, this.spec.doc.head.firstChild); } current.setAttribute('charset', 'utf-8'); } private _updateBySelector(selector: string, contents: string) { const elem = this.doc.querySelector(selector); if (elem && elem.textContent!.trim().length > 0) { return true; } if (elem) { elem.innerHTML = contents; return true; } return false; } } function getBoilerplate(file: string) { let boilerplateFile: string = file; try { if (fs.lstatSync(file).isFile()) { boilerplateFile = file; } } catch (error) { boilerplateFile = path.join(__dirname, '../boilerplate', `${file}.html`); } return fs.readFileSync(boilerplateFile, 'utf8'); } async function loadImports(spec: Spec, rootElement: HTMLElement, rootPath: string) { const imports = rootElement.querySelectorAll('EMU-IMPORT'); for (let i = 0; i < imports.length; i++) { const node = imports[i]; const imp = await Import.build(spec, node as EmuImportElement, rootPath); await loadImports(spec, node as HTMLElement, imp.relativeRoot); } } async function walk(walker: TreeWalker, context: Context) { const previousInNoAutolink = context.inNoAutolink; let previousInNoEmd = context.inNoEmd; const { spec } = context; context.node = walker.currentNode as HTMLElement; context.tagStack.push(context.node); if (context.node === context.followingEmd) { context.followingEmd = null; context.inNoEmd = false; // inNoEmd is true because we're walking past the output of emd, rather than by being within a NO_EMD context // so reset previousInNoEmd so we exit it properly previousInNoEmd = false; } if (context.node.nodeType === 3) { // walked to a text node if (context.node.textContent!.trim().length === 0) return; // skip empty nodes; nothing to do! const clause = context.clauseStack[context.clauseStack.length - 1] || context.spec; const namespace = clause ? clause.namespace : context.spec.namespace; if (!context.inNoEmd) { // new nodes as a result of emd processing should be skipped context.inNoEmd = true; let node = context.node as Node | null; while (node && !node.nextSibling) { node = node.parentNode; } if (node) { // inNoEmd will be set to false when we walk to this node context.followingEmd = node.nextSibling; } // else, there's no more nodes to process and inNoEmd does not need to be tracked utils.emdTextNode(context.spec, context.node as unknown as Text, namespace); } if (!context.inNoAutolink) { // stuff the text nodes into an array for auto-linking with later // (since we can't autolink at this point without knowing the biblio). context.spec._textNodes[namespace] = context.spec._textNodes[namespace] || []; context.spec._textNodes[namespace].push({ node: context.node, clause, inAlg: context.inAlg, currentId: context.currentId, }); } return; } // context.node is an HTMLElement (node type 1) // handle oldids const oldids = context.node.getAttribute('oldids'); if (oldids) { if (!context.node.childNodes) { throw new Error('oldids found on unsupported element: ' + context.node.nodeName); } oldids .split(/,/g) .map(s => s.trim()) .forEach(oid => { const s = spec.doc.createElement('span'); s.setAttribute('id', oid); context.node.insertBefore(s, context.node.childNodes[0]); }); } const parentId = context.currentId; if (context.node.hasAttribute('id')) { context.currentId = context.node.getAttribute('id'); } if (NO_CLAUSE_AUTOLINK.has(context.node.nodeName)) { context.inNoAutolink = true; } else if (YES_CLAUSE_AUTOLINK.has(context.node.nodeName)) { context.inNoAutolink = false; } if (NO_EMD.has(context.node.nodeName)) { context.inNoEmd = true; } else if (YES_EMD.has(context.node.nodeName)) { context.inNoEmd = false; } const visitor = visitorMap[context.node.nodeName]; if (visitor) { await visitor.enter(context); } const firstChild = walker.firstChild(); if (firstChild) { while (true) { await walk(walker, context); const next = walker.nextSibling(); if (!next) break; } walker.parentNode(); context.node = walker.currentNode as HTMLElement; } if (visitor) visitor.exit(context); context.inNoAutolink = previousInNoAutolink; context.inNoEmd = previousInNoEmd; context.currentId = parentId; context.tagStack.pop(); } const jsDependencies = ['sdoMap.js', 'menu.js', 'listNumbers.js']; async function concatJs(...extras: string[]) { let dependencies = await Promise.all( jsDependencies.map(dependency => utils.readFile(path.join(__dirname, '../js/' + dependency))) ); dependencies = dependencies.concat(extras); return dependencies.join('\n'); } function sha(str: string) { return crypto .createHash('sha256') .update(str) .digest('base64') .slice(0, 8) .replace(/\+/g, '-') .replace(/\//g, '_'); } // jsdom does not handle the `.hostname` (etc) parts correctly, so we have to look at the href directly // it also (some?) relative links as links to about:blank, for the purposes of testing the href function linkIsAbsolute(link: HTMLAnchorElement | HTMLLinkElement) { return !link.href.startsWith('about:blank') && /^[a-z]+:/.test(link.href); } function linkIsInternal(link: HTMLAnchorElement | HTMLLinkElement) { return link.href.startsWith('#') || link.href.startsWith('about:blank#'); } function linkIsPathRelative(link: HTMLAnchorElement | HTMLLinkElement) { return !link.href.startsWith('/') && !link.href.startsWith('about:blank/'); } function pathFromRelativeLink(link: HTMLAnchorElement | HTMLLinkElement) { return link.href.startsWith('about:blank') ? link.href.substring(11) : link.href; } function isFirstChild(node: Node) { const p = node.parentElement!; return ( p.childNodes[0] === node || (p.childNodes[0].textContent === '' && p.childNodes[1] === node) ); } // TODO factor some of this stuff out function isCalledAsPerform(xref: Xref, allowQuestion: boolean) { let node = xref.node; if (node.parentElement?.tagName === 'EMU-META' && isFirstChild(node)) { node = node.parentElement; } const previousSibling = node.previousSibling; if (previousSibling?.nodeType !== 3 /* TEXT_NODE */) { return false; } return (allowQuestion ? /\bperform ([?!]\s)?$/i : /\bperform $/i).test( previousSibling.textContent! ); } function isAssertedToBeNormal(xref: Xref) { let node = xref.node; if (node.parentElement?.tagName === 'EMU-META' && isFirstChild(node)) { node = node.parentElement; } const previousSibling = node.previousSibling; if (previousSibling?.nodeType !== 3 /* TEXT_NODE */) { return false; } return /\s!\s$/.test(previousSibling.textContent!); } function isConsumedAsCompletion(xref: Xref) { let node = xref.node; if (node.parentElement?.tagName === 'EMU-META' && isFirstChild(node)) { node = node.parentElement; } const previousSibling = node.previousSibling; if (previousSibling?.nodeType !== 3 /* TEXT_NODE */) { return false; } if (/[!?]\s$/.test(previousSibling.textContent!)) { return true; } if (previousSibling.textContent! === '(') { // check for Completion( const previousPrevious = previousSibling.previousSibling; if (previousPrevious?.textContent === 'Completion') { return true; } } return false; }
the_stack
import {Class, AnyTiming, Timing} from "@swim/util"; import {MemberFastenerClass, Property} from "@swim/component"; import type {GeoBox} from "@swim/geo"; import type {Trait} from "@swim/model"; import {ViewRef} from "@swim/view"; import {HtmlView} from "@swim/dom"; import {CanvasView} from "@swim/graphics"; import {Controller, TraitViewRef, TraitViewControllerSet} from "@swim/controller"; import type {GeoPerspective} from "../geo/GeoPerspective"; import type {GeoViewport} from "../geo/GeoViewport"; import type {GeoView} from "../geo/GeoView"; import type {GeoTrait} from "../geo/GeoTrait"; import {GeoController} from "../geo/GeoController"; import {MapView} from "./MapView"; import {MapTrait} from "./MapTrait"; import type {MapControllerObserver} from "./MapControllerObserver"; /** @public */ export interface MapControllerLayerExt { attachLayerTrait(layerTrait: GeoTrait, layerController: GeoController): void; detachLayerTrait(layerTrait: GeoTrait, layerController: GeoController): void; attachLayerView(layerView: GeoView, layerController: GeoController): void; detachLayerView(layerView: GeoView, layerController: GeoController): void; } /** @public */ export abstract class MapController extends Controller { override readonly observerType?: Class<MapControllerObserver>; protected abstract createMapView(containerView: HtmlView): MapView; protected setGeoPerspective(geoPerspective: GeoPerspective | null): void { if (geoPerspective !== null) { const mapView = this.map.view; if (mapView !== null) { mapView.moveTo(geoPerspective); } } } @TraitViewRef<MapController, MapTrait, MapView>({ traitType: MapTrait, observesTrait: true, willAttachTrait(mapTrait: MapTrait): void { this.owner.callObservers("controllerWillAttachMapTrait", mapTrait, this.owner); }, didAttachTrait(mapTrait: MapTrait): void { const mapView = this.view; if (mapView !== null) { this.owner.setGeoPerspective(mapTrait.geoPerspective.value); } const layerTraits = mapTrait.layers.traits; for (const traitId in layerTraits) { const layerTrait = layerTraits[traitId]!; this.owner.layers.addTraitController(layerTrait); } }, willDetachTrait(mapTrait: MapTrait): void { const layerTraits = mapTrait.layers.traits; for (const traitId in layerTraits) { const layerTrait = layerTraits[traitId]!; this.owner.layers.deleteTraitController(layerTrait); } }, didDetachTrait(mapTrait: MapTrait): void { this.owner.callObservers("controllerDidDetachMapTrait", mapTrait, this.owner); }, traitDidSetGeoPerspective(newGeoPerspective: GeoPerspective | null, oldGeoPerspective: GeoPerspective | null): void { this.owner.setGeoPerspective(newGeoPerspective); }, traitWillAttachLayer(layerTrait: GeoTrait, targetTrait: Trait): void { this.owner.layers.addTraitController(layerTrait, targetTrait); }, traitDidDetachLayer(layerTrait: GeoTrait): void { this.owner.layers.deleteTraitController(layerTrait); }, viewType: MapView, observesView: true, willAttachView(mapView: MapView): void { this.owner.callObservers("controllerWillAttachMapView", mapView, this.owner); }, didAttachView(mapView: MapView): void { this.owner.canvas.setView(mapView.canvas.view); this.owner.container.setView(mapView.container.view); const mapTrait = this.trait; if (mapTrait !== null) { this.owner.setGeoPerspective(mapTrait.geoPerspective.value); } const layerControllers = this.owner.layers.controllers; for (const controllerId in layerControllers) { const layerController = layerControllers[controllerId]!; const layerView = layerController.geo.view; if (layerView !== null && layerView.parent === null) { layerController.geo.insertView(mapView); } } }, willDetachView(mapView: MapView): void { this.owner.canvas.setView(null); this.owner.container.setView(null); }, didDetachView(mapView: MapView): void { this.owner.callObservers("controllerDidDetachMapView", mapView, this.owner); }, viewWillSetGeoViewport(newGeoViewport: GeoViewport, oldGeoViewport: GeoViewport): void { this.owner.callObservers("controllerWillSetGeoViewport", newGeoViewport, oldGeoViewport, this.owner); }, viewDidSetGeoViewport(newGeoViewport: GeoViewport, oldGeoViewport: GeoViewport): void { this.owner.callObservers("controllerDidSetGeoViewport", newGeoViewport, oldGeoViewport, this.owner); }, viewWillAttachMapCanvas(mapCanvasView: CanvasView): void { this.owner.canvas.setView(mapCanvasView); }, viewDidDetachMapCanvas(mapCanvasView: CanvasView): void { this.owner.canvas.setView(null); }, viewWillAttachMapContainer(mapContainerView: HtmlView): void { this.owner.container.setView(mapContainerView); }, viewDidDetachMapContainer(mapContainerView: HtmlView): void { this.owner.container.setView(null); }, }) readonly map!: TraitViewRef<this, MapTrait, MapView>; static readonly map: MemberFastenerClass<MapController, "map">; @ViewRef<MapController, CanvasView>({ type: CanvasView, willAttachView(mapCanvasView: CanvasView): void { this.owner.callObservers("controllerWillAttachMapCanvasView", mapCanvasView, this.owner); }, didDetachView(mapCanvasView: CanvasView): void { this.owner.callObservers("controllerDidDetachMapCanvasView", mapCanvasView, this.owner); }, }) readonly canvas!: ViewRef<this, CanvasView>; static readonly canvas: MemberFastenerClass<MapController, "canvas">; @ViewRef<MapController, HtmlView>({ type: HtmlView, willAttachView(mapContainerView: HtmlView): void { this.owner.callObservers("controllerWillAttachMapContainerView", mapContainerView, this.owner); }, didAttachView(containerView: HtmlView): void { const mapView = this.owner.createMapView(containerView); mapView.container.setView(containerView); this.owner.map.setView(mapView); }, didDetachView(mapContainerView: HtmlView): void { this.owner.callObservers("controllerDidDetachMapContainerView", mapContainerView, this.owner); }, }) readonly container!: ViewRef<this, HtmlView>; static readonly container: MemberFastenerClass<MapController, "container">; @Property({type: Timing, value: true}) readonly geoTiming!: Property<this, Timing | boolean | undefined, AnyTiming>; @TraitViewControllerSet<MapController, GeoTrait, GeoView, GeoController, MapControllerLayerExt>({ implements: true, type: GeoController, binds: true, observes: true, get parentView(): MapView | null { return this.owner.map.view; }, getTraitViewRef(layerController: GeoController): TraitViewRef<unknown, GeoTrait, GeoView> { return layerController.geo; }, willAttachController(layerController: GeoController): void { this.owner.callObservers("controllerWillAttachLayer", layerController, this.owner); }, didAttachController(layerController: GeoController): void { const layerTrait = layerController.geo.trait; if (layerTrait !== null) { this.attachLayerTrait(layerTrait, layerController); } const layerView = layerController.geo.view; if (layerView !== null) { this.attachLayerView(layerView, layerController); } }, willDetachController(layerController: GeoController): void { const layerView = layerController.geo.view; if (layerView !== null) { this.detachLayerView(layerView, layerController); } const layerTrait = layerController.geo.trait; if (layerTrait !== null) { this.detachLayerTrait(layerTrait, layerController); } }, didDetachController(layerController: GeoController): void { this.owner.callObservers("controllerDidDetachLayer", layerController, this.owner); }, controllerWillAttachGeoTrait(layerTrait: GeoTrait, layerController: GeoController): void { this.owner.callObservers("controllerWillAttachLayerTrait", layerTrait, layerController, this.owner); this.attachLayerTrait(layerTrait, layerController); }, controllerDidDetachGeoTrait(layerTrait: GeoTrait, layerController: GeoController): void { this.detachLayerTrait(layerTrait, layerController); this.owner.callObservers("controllerDidDetachLayerTrait", layerTrait, layerController, this.owner); }, attachLayerTrait(layerTrait: GeoTrait, layerController: GeoController): void { // hook }, detachLayerTrait(layerTrait: GeoTrait, layerController: GeoController): void { // hook }, controllerWillAttachGeoView(layerView: GeoView, layerController: GeoController): void { this.owner.callObservers("controllerWillAttachLayerView", layerView, layerController, this.owner); this.attachLayerView(layerView, layerController); }, controllerDidDetachGeoView(layerView: GeoView, layerController: GeoController): void { this.detachLayerView(layerView, layerController); this.owner.callObservers("controllerDidDetachLayerView", layerView, layerController, this.owner); }, attachLayerView(layerView: GeoView, layerController: GeoController): void { // hook }, detachLayerView(layerView: GeoView, layerController: GeoController): void { layerView.remove(); }, controllerWillSetGeoBounds(newGeoBounds: GeoBox, oldGeoBounds: GeoBox, layerController: GeoController): void { this.owner.callObservers("controllerWillSetLayerGeoBounds", newGeoBounds, oldGeoBounds, layerController, this.owner); }, controllerDidSetGeoBounds(newGeoBounds: GeoBox, oldGeoBounds: GeoBox, layerController: GeoController): void { this.owner.callObservers("controllerDidSetLayerGeoBounds", newGeoBounds, oldGeoBounds, layerController, this.owner); }, createController(layerTrait?: GeoTrait): GeoController { if (layerTrait !== void 0) { return GeoController.fromTrait(layerTrait); } else { return TraitViewControllerSet.prototype.createController.call(this); } }, }) readonly layers!: TraitViewControllerSet<this, GeoTrait, GeoView, GeoController> & MapControllerLayerExt; static readonly layers: MemberFastenerClass<MapController, "layers">; }
the_stack
import { Community } from '../community/community.model'; import { CommunityUserNotification, NotificationType, } from '../community/user-notification/user-notification.model'; import { currency } from '../filters/currency'; import { FiresideCommunity } from '../fireside/community/community.model'; import { Fireside } from '../fireside/fireside.model'; import { FiresidePostCommunity } from '../fireside/post/community/community.model'; import { FiresidePost } from '../fireside/post/post-model'; import { FiresideStreamNotification } from '../fireside/stream-notification/stream-notification.model'; import { ForumTopic } from '../forum/topic/topic.model'; import { Game } from '../game/game.model'; import { GameTrophy } from '../game/trophy/trophy.model'; import { Mention } from '../mention/mention.model'; import { OrderItem } from '../order/item/item.model'; import { Sellable } from '../sellable/sellable.model'; import { SiteTrophy } from '../site/trophy/trophy.model'; import { Translate } from '../translate/translate.service'; import { UserGameTrophy } from '../user/trophy/game-trophy.model'; import { UserSiteTrophy } from '../user/trophy/site-trophy.model'; import { User } from '../user/user.model'; import { Notification } from './notification-model'; export class NotificationText { private static getSubjectTranslationValue(notification: Notification) { if (notification.is_user_based) { if (notification.from_model instanceof User) { return ( notification.from_model.display_name + ' (@' + notification.from_model.username + ')' ); } else { return Translate.$gettext('Someone'); } } else if (notification.is_game_based && notification.to_model instanceof Game) { return notification.to_model.title; } else if ( notification.is_community_based && notification.from_model instanceof Community ) { return notification.from_model.name; } return ''; } private static getTranslationValues(notification: Notification) { const subject = this.getSubjectTranslationValue(notification); let output = { subject } as any; if (notification.to_model instanceof Game || notification.to_model instanceof ForumTopic) { output.object = notification.to_model.title; } else if (notification.to_model instanceof Community) { output.object = notification.to_model.name; } else if (notification.to_model instanceof FiresidePost) { output.object = notification.to_model.getShortLead(); } else if (notification.to_model instanceof User) { if ( notification.from_model instanceof User && notification.from_model.id === notification.to_model.id ) { output.object = Translate.$gettext('them'); } else { output.object = notification.to_model.display_name + ' (@' + notification.to_model.username + ')'; } } return output; } /** * Gets notification display text. * * @param plaintext When `true` returns the text without any modifications done to accomodate for HTML rendering. */ public static getText(notification: Notification, plaintext: boolean): string | undefined { // Super hack time! function _process(text: string) { if (plaintext) { return text .replace(/<em>/g, '') .replace(/<\/em>/g, '') .replace(/<b>/g, '') .replace(/<\/b>/g, ''); } return text; } switch (notification.type) { case Notification.TYPE_POST_ADD: { let gameTitle = ''; let postTitle = ''; if (notification.to_model instanceof Game) { gameTitle = notification.to_model.title + ' - '; } if (notification.action_model instanceof FiresidePost) { postTitle = notification.action_model.getShortLead(); } return gameTitle + postTitle; } case Notification.TYPE_POST_FEATURED_IN_COMMUNITY: { const postCommunity = notification.action_model as FiresidePostCommunity; return _process( Translate.$gettextInterpolate( `Your post in the <em>%{ community }</em> community has been featured!`, { community: postCommunity.community.name, }, !plaintext ) ); } case Notification.TYPE_FIRESIDE_FEATURED_IN_COMMUNITY: { return _process( Translate.$gettextInterpolate( `Your Fireside in the <em>%{ community }</em> community has been featured!`, { community: (notification.action_model as FiresideCommunity).community .name, }, !plaintext ) ); } case Notification.TYPE_COMMUNITY_USER_NOTIFICATION: { const userNotification = notification.action_model as CommunityUserNotification; switch (userNotification.type) { case NotificationType.POSTS_MOVE: return _process( Translate.$gettextInterpolate( `Your post in the <em>%{ community }</em> community has been <b>moved</b> to a different channel.`, { community: userNotification.community.name, }, !plaintext ) ); case NotificationType.POSTS_EJECT: return _process( Translate.$gettextInterpolate( `Your post has been <b>ejected</b> from the <em>%{ community }</em> community.`, { community: userNotification.community.name, }, !plaintext ) ); case NotificationType.FIRESIDES_EJECT: return _process( Translate.$gettextInterpolate( `Your Fireside has been <b>ejected</b> from the <em>%{ community }</em> community.`, { community: userNotification.community.name, }, !plaintext ) ); } } break; case Notification.TYPE_GAME_TROPHY_ACHIEVED: { if ( notification.action_model instanceof UserGameTrophy && notification.action_model.trophy instanceof GameTrophy && notification.action_model.game instanceof Game ) { return _process( Translate.$gettextInterpolate( `You achieved <em>%{ trophyTitle }</em> on <b>%{ gameTitle }</b>!`, { trophyTitle: notification.action_model.trophy.title, gameTitle: notification.action_model.game.title, }, !plaintext ) ); } break; } case Notification.TYPE_SITE_TROPHY_ACHIEVED: { if ( notification.action_model instanceof UserSiteTrophy && notification.action_model.trophy instanceof SiteTrophy ) { return _process( Translate.$gettextInterpolate( `You achieved the Game Jolt Trophy <em>%{ trophyTitle }</em>!`, { trophyTitle: notification.action_model.trophy.title, }, !plaintext ) ); } break; } case Notification.TYPE_COMMENT_ADD_OBJECT_OWNER: { if (notification.to_model instanceof User) { return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> shouted at you!`, this.getTranslationValues(notification), !plaintext ) ); } else { return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> commented on <b>%{ object }</b>.`, this.getTranslationValues(notification), !plaintext ) ); } } case Notification.TYPE_COMMENT_ADD: { if (notification.to_model instanceof User) { return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> replied to your shout to <b>%{ object }</b>.`, this.getTranslationValues(notification), !plaintext ) ); } else { return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> replied to your comment on <b>%{ object }</b>.`, this.getTranslationValues(notification), !plaintext ) ); } } case Notification.TYPE_FORUM_POST_ADD: { return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> posted a new forum post to <b>%{ object }</b>.`, this.getTranslationValues(notification), !plaintext ) ); } case Notification.TYPE_FRIENDSHIP_REQUEST: { return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> sent you a friend request.`, this.getTranslationValues(notification), !plaintext ) ); } case Notification.TYPE_FRIENDSHIP_ACCEPT: { return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> accepted your friend request.`, this.getTranslationValues(notification), !plaintext ) ); } case Notification.TYPE_GAME_RATING_ADD: { return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> liked <b>%{ object }</b>.`, this.getTranslationValues(notification), !plaintext ) ); } case Notification.TYPE_GAME_FOLLOW: { return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> followed <b>%{ object }</b>.`, this.getTranslationValues(notification), !plaintext ) ); } case Notification.TYPE_SELLABLE_SELL: { const sellable = notification.to_model as Sellable; const orderItem = notification.action_model as OrderItem; const translationValues = { object: sellable.title, amount: currency(orderItem.amount), subject: this.getSubjectTranslationValue(notification), }; return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> bought a package in <b>%{ object }</b> for %{ amount }.`, translationValues, !plaintext ) ); } case Notification.TYPE_USER_FOLLOW: { return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> followed you.`, this.getTranslationValues(notification), !plaintext ) ); } case Notification.TYPE_COLLABORATOR_INVITE: { switch (notification.to_resource) { case 'Game': return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> invited you to collaborate on the game <b>%{ object }</b>.`, this.getTranslationValues(notification), !plaintext ) ); case 'Community': return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> invited you to collaborate on the <b>%{ object }</b> community.`, this.getTranslationValues(notification), !plaintext ) ); } break; } case Notification.TYPE_MENTION: { const mention = notification.action_model as Mention; switch (mention.resource) { case 'Comment': { if (notification.to_model instanceof Game) { return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> mentioned you in a comment on the game <b>%{ object }</b>.`, { object: notification.to_model.title, subject: this.getSubjectTranslationValue(notification), }, !plaintext ) ); } else if (notification.to_model instanceof FiresidePost) { return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> mentioned you in a comment on the post <b>%{ object }</b>.`, { object: notification.to_model.getShortLead(), subject: this.getSubjectTranslationValue(notification), }, !plaintext ) ); } else if (notification.to_model instanceof User) { return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> mentioned you in a shout to @<b>%{ object }</b>.`, { object: notification.to_model.username, subject: this.getSubjectTranslationValue(notification), }, !plaintext ) ); } break; } case 'Game': { return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> mentioned you in the game <b>%{ object }</b>.`, { object: (notification.to_model as Game).title, subject: this.getSubjectTranslationValue(notification), }, !plaintext ) ); } case 'User': { return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> mentioned you in their user bio.`, this.getTranslationValues(notification), !plaintext ) ); } case 'Fireside_Post': { return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> mentioned you in the post <b>%{ object }</b>.`, { object: (notification.to_model as FiresidePost).getShortLead(), subject: this.getSubjectTranslationValue(notification), }, !plaintext ) ); } case 'Forum_Post': { return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> mentioned you in a forum post to <b>%{ object }</b>.`, { object: (notification.to_model as ForumTopic).title, subject: this.getSubjectTranslationValue(notification), }, !plaintext ) ); } default: { console.warn( 'Encountered not-implemented resource type for mention notification', mention.resource ); return undefined; } } break; } case Notification.TYPE_FIRESIDE_START: { if (notification.action_model instanceof Fireside) { return _process( Translate.$gettextInterpolate( `<em>%{ subject }</em> started up a new Fireside.`, this.getTranslationValues(notification), !plaintext ) ); } break; } case Notification.TYPE_FIRESIDE_STREAM_NOTIFICATION: { const users = (notification.action_model as FiresideStreamNotification).users; if (users.length === 0) { return undefined; } const userInterpolates: { [name: string]: string } = {}; let i = 1; for (const user of users) { userInterpolates[`user${i}`] = `@${user.username}`; i++; } switch (users.length) { case 1: return _process( Translate.$gettextInterpolate( `<em>%{ user1 }</em> is streaming in a Fireside.`, userInterpolates, !plaintext ) ); case 2: return _process( Translate.$gettextInterpolate( `<em>%{ user1 }</em> and <em>%{ user2 }</em> are streaming in a Fireside.`, userInterpolates, !plaintext ) ); default: return _process( Translate.$gettextInterpolate( `<em>%{ user1 }</em>, <em>%{ user2 }</em> and <em>%{ more }</em> more are streaming in a Fireside.`, { ...userInterpolates, more: users.length - 2, }, !plaintext ) ); } } } // When the notification type has no implementation, we log and don't show it (return undefined). console.warn('Encountered not-implemented notification type', notification.type); return undefined; } }
the_stack
import {extend} from '../../util'; import * as o from '../x86/operand'; import * as t from '../x86/table'; import {S, rel, rel8, rel16, rel32, imm, imm8, imm16, imm32, imm64, immu, immu8, immu16, immu32, immu64, M, r, r8, r16, r32, r64, mm, st, xmm, xmmm, xmm_xmmm, xmm_xmm_xmmm, ymm, ymmm, ymm_ymmm, ymm_ymm_ymmm, zmm, zmmm, zmm_zmmm, zmm_zmm_zmmm, bnd, cr, dr, sreg, m, m8, m16, m32, m64, m128, m256, m512, rm8, rm16, rm32, rm64} from '../x86/atoms'; import {EXT, INS} from "../x86/consts"; import {cr0_7, dr0_7, ext_avx, ext_avx2, ext_mmx, ext_sse, ext_sse2, rvm} from "./atoms"; declare const require; function lazy(part: string, mnemonic: string) { return require('./table/' + part).default[mnemonic]; } export const defaults = { ...t.defaults, rex: false, ds: S.D, }; function tpl_not(o = 0xF6, or = 2, lock = true): t.ITableDefinitionX86[] { return [{o: o + 1, or: or, lock: lock}, // F6 /2 NOT r/m8 M Valid Valid Reverse each bit of r/m8. // REX + F6 /2 NOT r/m8* M Valid N.E. Reverse each bit of r/m8. {o: o, ops: [rm8]}, // F7 /2 NOT r/m16 M Valid Valid Reverse each bit of r/m16. {ops: [rm16]}, // F7 /2 NOT r/m32 M Valid Valid Reverse each bit of r/m32. {ops: [rm32]}, // REX.W + F7 /2 NOT r/m64 M Valid N.E. Reverse each bit of r/m64. {ops: [rm64]}, ]; } function tpl_bt(o_r = 0x0FA3, or_imm = 4, o_imm = 0x0FBA) { return [{en: 'mr'}, // 0F A3 /r BT r/m16, r16 MR Valid Valid Store selected bit in CF flag. {o: o_r, ops: [rm16, r16]}, // 0F A3 /r BT r/m32, r32 MR Valid Valid Store selected bit in CF flag. {o: o_r, ops: [rm32, r32]}, // REX.W + 0F A3 /r BT r/m64, r64 MR Valid N.E. Store selected bit in CF flag. {o: o_r, ops: [rm64, r64]}, // 0F BA /4 ib BT r/m16, imm8 MI Valid Valid Store selected bit in CF flag. {o: o_imm, or: or_imm, ops: [rm16, imm8]}, // 0F BA /4 ib BT r/m32, imm8 MI Valid Valid Store selected bit in CF flag. {o: o_imm, or: or_imm, ops: [rm32, imm8]}, // REX.W + 0F BA /4 ib BT r/m64, imm8 MI Valid N.E. Store selected bit in CF flag. {o: o_imm, or: or_imm, ops: [rm64, imm8]}, ]; } function tpl_bsf(op = 0x0FBC) { return [{o: op}, // 0F BC /r BSF r16, r/m16 RM Valid Valid Bit scan forward on r/m16. {ops: [r16, rm16]}, // 0F BC /r BSF r32, r/m32 RM Valid Valid Bit scan forward on r/m32. {ops: [r32, rm32]}, // REX.W + 0F BC /r BSF r64, r/m64 RM Valid N.E. Bit scan forward on r/m64. {ops: [r64, rm64]}, ]; } function tpl_ja(op = 0x77, op2 = 0x0F87) { return [{}, // 77 cb JA rel8 D Valid Valid Jump short if above (CF=0 and ZF=0). {o: op, ops: [rel8]}, // 0F 87 cd JA rel32 D Valid Valid Jump near if above (CF=0 and ZF=0). {o: op2, ops: [rel32]}, ]; } function tpl_cmovc(op = 0x0F42) { return [{o: op}, // 0F 42 /r CMOVC r16, r/m16 RM Valid Valid Move if carry (CF=1). {ops: [r16, rm16]}, // 0F 42 /r CMOVC r32, r/m32 RM Valid Valid Move if carry (CF=1). {ops: [r32, rm32]}, // REX.W + 0F 42 /r CMOVC r64, r/m64 RM Valid N.E. Move if carry (CF=1). {ops: [r64, rm64]}, ]; } function tpl_xadd(op = 0, lock = true) { return [{o: op + 1, en: 'mr', lock: lock}, // 0F C0 /r XADD r/m8, r8 MR Valid Valid Exchange r8 and r/m8; load sum into r/m8. // REX + 0F C0 /r XADD r/m8*, r8* MR Valid N.E. Exchange r8 and r/m8; load sum into r/m8. {o: op, ops: [rm8, r8]}, // 0F C1 /r XADD r/m16, r16 MR Valid Valid Exchange r16 and r/m16; load sum into r/m16. {ops: [rm16, r16]}, // 0F C1 /r XADD r/m32, r32 MR Valid Valid Exchange r32 and r/m32; load sum into r/m32. {ops: [rm32, r32]}, // REX.W + 0F C1 /r XADD r/m64, r64 MR Valid N.E. Exchange r64 and r/m64; load sum into r/m64. {ops: [rm64, r64]}, ]; } function tpl_movs(op = 0xA4) { return [{o: op + 1}, // A4 MOVS m8, m8 NP Valid Valid {o: op, s: S.B}, // A5 MOVS m16, m16 NP Valid Valid {s: S.W}, // A5 MOVS m32, m32 NP Valid Valid {s: S.D}, // REX.W + A5 MOVS m64, m64 NP Valid N.E. Move qword from address (R|E)SI to (R|E)DI. {s: S.Q}, ]; } function tpl_lss(op = 0x0FB2) { return [{o: op}, // 0F B2 /r LSS r16,m16:16 RM Valid Valid Load SS:r16 with far pointer from memory. {ops: [rm16, m]}, // 0F B2 /r LSS r32,m16:32 RM Valid Valid Load SS:r32 with far pointer from memory. {ops: [rm32, m]}, // REX + 0F B2 /r LSS r64,m16:64 RM Valid N.E. Load SS:r64 with far pointer from memory. {ops: [rm64, m]}, ]; } function tpl_blsi(op = 0xF3, or = 3) { return [{o: op, or: or, en: 'vm', ext: [EXT.BMI1]}, {vex: 'NDD.LZ.0F38.W0', ops: [r32, rm32]}, {vex: 'NDD.LZ.0F38.W1', ops: [r64, rm64], mod: M.X64}, ]; } function tpl_bndcl(op = 0xF30F1A) { return [{o: op, ext: [EXT.MPX]}, {ops: [bnd, rm32], mod: M.X32, s: S.D}, {ops: [bnd, rm64], mod: M.X64, s: S.Q}, ]; } // TODO: // TODO: CALL - ptr16:16 vs m16:16 // TODO: test `mib` operands, that require SIB and have no SCALE and INDEX // TODO: JMP - memory and pointer legacy references. var _dec = tpl_not(0xFE, 1); _dec.push({o: 0x48, r: true, ops: [r16], mod: M.COMP | M.LEG}); _dec.push({o: 0x48, r: true, ops: [r32], mod: M.COMP | M.LEG}); var _inc = tpl_not(0xFE, 0); _inc.push({o: 0x40, r: true, ops: [r16], mod: M.COMP | M.LEG}); _inc.push({o: 0x40, r: true, ops: [r32], mod: M.COMP | M.LEG}); export const table = {...t.table, // # A-letter aaa: require('./mnemonics/aaa').default, aad: require('./mnemonics/aad').default, aam: [{mod: M.OLD}, {o: 0xD40A}, {o: 0xD4, ops: [imm8]}, ], aas: [{o: 0x3F, mod: M.OLD}], addpd: [{o: 0x660F58, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vaddpd: [{o: 0x58, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.66.0F.WIG', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.256.66.0F.WIG', ops: [ymm, ymm, [ymm, m]]}, ], // 0F 58 /r ADDPS xmm1, xmm2/m128 V/V SSE addps: [{o: 0x0F58, ops: xmm_xmmm, ext: ext_sse}], get vaddps() {return lazy('avx', 'vaddps')}, kandw: [{}, // VEX.L1.0F.W0 41 /r KANDW k1, k2, k3 V/V AVX512F {o: 0x41, vex: 'L1.0F.W0', ops: [], ext: [EXT.AVX512F]}, ], addsd: [{o: 0xF20F58, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vaddsd: [{o: 0x58, vex: 'NDS.LIG.F2.0F.WIG', en: 'rvm', ops: [xmm, xmm, [xmm, m]], ext: [EXT.AVX]}], addss: [{o: 0xF30F58, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vaddss: [{o: 0x58, vex: 'NDS.LIG.F3.0F.WIG', en: 'rvm', ops: [xmm, xmm, [xmm, m]], ext: [EXT.AVX]}], addsubpd: [{o: 0x660FD0, ops: [xmm, [xmm, m]], ext: [EXT.SSE3]}], vaddsubpd: [{o: 0xD0, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.66.0F.WIG', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.256.66.0F.WIG', ops: [ymm, ymm, [ymm, m]]}, ], addsubps: [{o: 0xF20FD0, ops: [xmm, [xmm, m]], ext: [EXT.SSE3]}], vaddsubps: [{o: 0xD0, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.F2.0F.WIG', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.256.F2.0F.WIG', ops: [ymm, ymm, [ymm, m]]}, ], aesdec: [{o: 0x0F38DE, pfx: [0x66], ops: [xmm, [xmm, m]], ext: [EXT.AES]}], vaesdec: [{o: 0xDE, vex: 'NDS.128.66.0F38.WIG', en: 'rvm', ops: [xmm, xmm, [xmm, m]], ext: [EXT.AES, EXT.AVX]}], aesdeclast: [{o: 0x0F38DF, pfx: [0x66], ops: [xmm, [xmm, m]], ext: [EXT.AES]}], vaesdeclast: [{o: 0xDF, vex: 'NDS.128.66.0F38.WIG', en: 'rvm', ops: [xmm, xmm, [xmm, m]], ext: [EXT.AES, EXT.AVX]}], aesenc: [{o: 0x0F38DC, pfx: [0x66], ops: [xmm, [xmm, m]], ext: [EXT.AES]}], vaesenc: [{o: 0xDC, vex: 'NDS.128.66.0F38.WIG', en: 'rvm', ops: [xmm, xmm, [xmm, m]], ext: [EXT.AES, EXT.AVX]}], aesenclast: [{o: 0x0F38DD, pfx: [0x66], ops: [xmm, [xmm, m]], ext: [EXT.AES]}], vaesenclast: [{o: 0xDD, vex: 'NDS.128.66.0F38.WIG', en: 'rvm', ops: [xmm, xmm, [xmm, m]], ext: [EXT.AES, EXT.AVX]}], aesimc: [{o: 0x0F38DB, pfx: [0x66], ops: [xmm, [xmm, m]], ext: [EXT.AES]}], vaesimc: [{o: 0xDB, vex: '128.66.0F38.WIG', ops: [xmm, [xmm, m]], ext: [EXT.AES, EXT.AVX]}], aeskeygenassist: [{o: 0x0F3ADF, pfx: [0x66], ops: [xmm, [xmm, m], imm8], ext: [EXT.AES]}], vaeskeygenassist: [{o: 0xDF, vex: '128.66.0F3A.WIG', ops: [xmm, [xmm, m], imm8], ext: [EXT.AES, EXT.AVX]}], andn: [{o: 0xF2, en: 'rvm', ext: [EXT.BMI1]}, {vex: 'NDS.LZ.0F38.W0', ops: [r32, r32, rm32]}, {vex: 'NDS.LZ.0F38.W1', ops: [r64, r64, rm64], mod: M.X64}, ], andpd: [{o: 0x660F54, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vandpd: [{o: 0x54, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.66.0F.WIG', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.256.66.0F.WIG', ops: [ymm, ymm, [ymm, m]]}, ], andps: [{o: 0x0F54, ops: [xmm, [xmm, m]], ext: [EXT.SSE]}], vandps: [{o: 0x54, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.0F.WIG', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.256.0F.WIG', ops: [ymm, ymm, [ymm, m]]}, ], andnpd: [{o: 0x660F55, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vandnpd: [{o: 0x55, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.66.0F.WIG', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.256.66.0F.WIG', ops: [ymm, ymm, [ymm, m]]}, ], andnps: [{o: 0x0F55, ops: [xmm, [xmm, m]], ext: [EXT.SSE]}], vandnps: [{o: 0x55, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.0F.WIG', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.256.0F.WIG', ops: [ymm, ymm, [ymm, m]]}, ], arpl: [{o: 0x63, ops: [rm16, r16], mod: M.OLD}], // # B-letter blendpd: [{o: 0x0F3A0F, pfx: [0x66], ops: [xmm, [xmm, m], imm8], ext: [EXT.SSE4_1]}], vblendpd: [{o: 0x0D, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.66.0F3A.WIG', ops: [xmm, xmm, [xmm, m], imm8]}, {vex: 'NDS.256.66.0F3A.WIG', ops: [ymm, ymm, [ymm, m], imm8]}, ], bextr: [{o: 0xF7, en: 'rmv', ext: [EXT.BMI1]}, {vex: 'NDS.LZ.0F38.W0', ops: [r32, rm32, r32]}, {vex: 'NDS.LZ.0F38.W1', ops: [r64, rm64, r64], mod: M.X64}, ], blendps: [{o: 0x0F3A0C, pfx: [0x66], ops: [xmm, [xmm, m], imm8], ext: [EXT.SSE4_1]}], vblendps: [{o: 0x0C, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.66.0F3A.WIG', ops: [xmm, xmm, [xmm, m], imm8]}, {vex: 'NDS.256.66.0F3A.WIG', ops: [ymm, ymm, [ymm, m], imm8]}, ], blendvpd: [{o: 0x0F3815, pfx: [0x66], ops: [xmm, [xmm, m]], ext: [EXT.SSE4_1]}], vblendvpd: [{o: 0x4B, en: 'rvmr', ext: [EXT.AVX]}, {vex: 'NDS.128.66.0F3A.W0', ops: [xmm, xmm, [xmm, m], xmm]}, {vex: 'NDS.256.66.0F3A.W0', ops: [ymm, ymm, [ymm, m], ymm]}, ], blendvps: [{o: 0x0F3814, pfx: [0x66], ops: [xmm, [xmm, m]], ext: [EXT.SSE4_1]}], vblendvps: [{o: 0x4A, en: 'rvmr', ext: [EXT.AVX]}, {vex: 'NDS.128.66.0F3A.W0', ops: [xmm, xmm, [xmm, m], xmm]}, {vex: 'NDS.256.66.0F3A.W0', ops: [ymm, ymm, [ymm, m], ymm]}, ], blsi: tpl_blsi(), blsmsk: tpl_blsi(0xF3, 2), blsr: tpl_blsi(0xF3, 1), bndcl: tpl_bndcl(), bndcu: tpl_bndcl(0xF20F1A), bndcn: tpl_bndcl(0xF20F1B), bndmk: tpl_bndcl(0xF30F1B), bndldx: [{o: 0x0F1A, ops: [bnd, m], ext: [EXT.MPX]}], bndmov: [{pfx: [0x66, 0x0F], ext: [EXT.MPX]}, {o: 0x1A, ops: [bnd, [bnd, m]], dbit: true}, {o: 0x1B, ops: [[bnd, m], bnd], en: 'mr', dbit: true}, ], bndstx: [{o: 0x0F1B, ops: [m, bnd], en: 'mr', ext: [EXT.MPX]}], bound: [{o: 0x62, mod: M.OLD}, {ops: [r16, m]}, {ops: [r32, m]}, ], bzhi: [{o: 0xF5, en: 'rmv', ext: [EXT.BMI2]}, {vex: 'NDS.LZ.0F38.W0', ops: [r32, rm32, r32]}, {vex: 'NDS.LZ.0F38.W1', ops: [r64, rm64, r64], mod: M.X64}, ], // # C-letter clflush: [{o: 0x0FAE, or: 7, ops: [m]}], clflushopt: [{o: 0x660FAE, or: 7, ops: [m]}], clts: [{o: 0x0F06}], cmppd: [{o: 0x660FC2, ops: [xmm, [xmm, m], imm8], ext: [EXT.SSE2]}], vcmppd: [{o: 0xC2, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.66.0F.WIG', ops: [xmm, xmm, [xmm, m], imm8]}, {vex: 'NDS.256.66.0F.WIG', ops: [ymm, ymm, [ymm, m], imm8]}, ], cmpps: [{o: 0x0FC2, ops: [xmm, [xmm, m], imm8], ext: [EXT.SSE]}], vcmpps: [{o: 0xC2, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.0F.WIG C2', ops: [xmm, xmm, [xmm, m], imm8]}, {vex: 'NDS.256.0F.WIG C2', ops: [ymm, ymm, [ymm, m], imm8]}, ], cmpsd: [{o: 0xF20FC2, ops: [xmm, [xmm, m], imm8], ext: [EXT.SSE2]}], vcmpsd: [{o: 0xC2, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.LIG.F2.0F.WIG', ops: [xmm, xmm, [xmm, m], imm8]}, ], cmpss: [{o: 0xF30FC2, ops: [xmm, [xmm, m], imm8], ext: [EXT.SSE]}], vcmpss: [{o: 0xC2, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.LIG.F3.0F.WIG', ops: [xmm, xmm, [xmm, m], imm8]}, ], comisd: [{o: 0x660F2F, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vcomisd: [{o: 0x2F, vex: 'LIG.66.0F.WIG', ops: [xmm, [xmm, m]], ext: [EXT.AVX]}], comiss: [{o: 0x0F2F, ops: [xmm, [xmm, m]], ext: [EXT.SSE]}], vcomiss: [{o: 0x2F, vex: 'LIG.0F.WIG', ops: [xmm, [xmm, m]], ext: [EXT.AVX]}], cvtdq2pd: [{o: 0xF30FE6, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vcvtdq2pd: [{o: 0xE6, ext: [EXT.AVX]}, {vex: '128.F3.0F.WIG', ops: [xmm, [xmm, m]]}, {vex: '256.F3.0F.WIG', ops: [ymm, [ymm, m]]}, ], cvtdq2ps: [{o: 0x0F5B, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vcvtdq2ps: [{o: 0x5B, ext: [EXT.AVX]}, {vex: '128.0F.WIG', ops: [xmm, [xmm, m]]}, {vex: '256.0F.WIG', ops: [ymm, [ymm, m]]}, ], cvtpd2dq: [{o: 0xF20FE6, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vcvtpd2dq: [{o: 0xE6, ext: [EXT.AVX]}, {vex: '128.F2.0F.WIG', ops: [xmm, [xmm, m]]}, {vex: '256.F2.0F.WIG', ops: [ymm, [ymm, m]]}, ], cvtpd2pi: [{o: 0x660F2D, ops: [xmm, [xmm, m]]}], cvtpd2ps: [{o: 0x660F5A, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vcvtpd2ps: [{o: 0x5A, ext: [EXT.AVX]}, {vex: '128.66.0F.WIG', ops: [xmm, [xmm, m]]}, {vex: '256.66.0F.WIG', ops: [ymm, [ymm, m]]}, ], cvtpi2pd: [{o: 0x660F2A, ops: [xmm, [xmm, m]]}], cvtpi2ps: [{o: 0x0F2A, ops: [xmm, [xmm, m]]}], cvtps2dq: [{o: 0x660F5B, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vcvtps2dq: [{o: 0x5B, ext: [EXT.AVX]}, {vex: '128.66.0F.WIG', ops: [xmm, [xmm, m]]}, {vex: '256.66.0F.WIG', ops: [ymm, [ymm, m]]}, ], cvtps2pd: [{o: 0x0F5A, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vcvtps2pd: [{o: 0x5A, ext: [EXT.AVX]}, {vex: '128.0F.WIG', ops: [xmm, [xmm, m]]}, {vex: '256.0F.WIG', ops: [ymm, [ymm, m]]}, ], cvtps2pi: [{o: 0x0F2D, ops: [xmm, [xmm, m]]}], cvtsd2si: [{o: 0xF20F2D, ops: [r32, [xmm, m]], s: S.D, ext: [EXT.SSE2]}], vcvtsd2si: [{o: 0x2D, ext: [EXT.AVX]}, {o: 0x0F2D, pfx: [0xF2], ops: [r64, [xmm, m]], s: S.Q, ext: [EXT.SSE2], mod: M.X64}, {vex: 'LIG.F2.0F.W0', ops: [r32, [xmm, m]], s: S.D}, {vex: 'LIG.F2.0F.W1', ops: [r64, [xmm, m]], s: S.Q, mod: M.X64}, ], cvtsd2ss: [{o: 0xF20F5A, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vcvtsd2ss: [{o: 0x5A, vex: 'NDS.LIG.F2.0F.WIG', ops: [xmm, xmm, [xmm, m]], en: 'rvm', ext: [EXT.AVX]}], cvtsi2sd: [{o: 0x0F2A, pfx: [0xF2], ext: [EXT.SSE2]}, {ops: [xmm, rm32], s: S.D}, {ops: [xmm, rm64], s: S.Q}, ], vcvtsi2sd: [{o: 0x2A, ext: [EXT.AVX], en: 'rvm'}, {vex: 'NDS.LIG.F2.0F.W0', ops: [xmm, xmm, rm32], s: S.D}, {vex: 'NDS.LIG.F2.0F.W1', ops: [xmm, xmm, rm64], s: S.Q}, ], cvtsi2ss: [{o: 0x0F2A, pfx: [0xF3], ext: [EXT.SSE]}, {ops: [xmm, rm32], s: S.D}, {ops: [xmm, rm64], s: S.Q}, ], vcvtsi2ss: [{o: 0x2A, ext: [EXT.AVX], en: 'rvm'}, {vex: 'NDS.LIG.F3.0F.W0', ops: [xmm, xmm, rm32], s: S.D}, {vex: 'NDS.LIG.F3.0F.W1', ops: [xmm, xmm, rm64], s: S.Q}, ], cvtss2sd: [{o: 0xF30F5A, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vcvtss2sd: [{o: 0x5A, vex: 'NDS.LIG.F3.0F.WIG', ops: [xmm, xmm, [xmm, m]], en: 'rvm', ext: [EXT.AVX]}], cvtss2si: [{o: 0x0F2D, pfx: [0xF3], ext: [EXT.SSE]}, {ops: [r32, [xmm, m]], s: S.D}, {ops: [r64, [xmm, m]], s: S.Q, mod: M.X64}, ], vcvtss2si: [{o: 0x2D, ext: [EXT.AVX]}, {vex: 'LIG.F3.0F.W0', ops: [r32, [xmm, m]], s: S.D}, {vex: 'LIG.F3.0F.W1', ops: [r64, [xmm, m]], s: S.Q, mod: M.X64}, ], cvttpd2dq: [{o: 0x660FE6, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vcvttpd2dq: [{o: 0xE6, ext: [EXT.AVX]}, {vex: '128.66.0F.WIG', ops: [xmm, [xmm, m]]}, {vex: '256.66.0F.WIG', ops: [ymm, [ymm, m]]}, ], cvttpd2pi: [{o: 0x660F2C, ops: [xmm, [xmm, m]]}], cvttps2dq: [{o: 0xF30F5B, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vcvttps2dq: [{o: 0x5B, ext: [EXT.AVX]}, {vex: '128.F3.0F.WIG', ops: [xmm, [xmm, m]]}, {vex: '256.F3.0F.WIG', ops: [ymm, [ymm, m]]}, ], cvttps2pi: [{o: 0x0F2C, ops: [xmm, [xmm, m]]}], cvttsd2si: [{o: 0x0F2C, pfx: [0xF2], ext: [EXT.SSE2]}, {ops: [r32, [xmm, m]], s: S.D}, {ops: [r64, [xmm, m]], s: S.Q, mod: M.X64}, ], vcvttsd2si: [{o: 0x2C, ext: [EXT.AVX]}, {vex: 'LIG.F2.0F.W0', ops: [r32, [xmm, m]], s: S.D}, {vex: 'LIG.F2.0F.W1', ops: [r64, [xmm, m]], s: S.Q, mod: M.X64}, ], cvttss2si: [{o: 0x0F2C, pfx: [0xF3], ext: [EXT.SSE]}, {ops: [r32, [xmm, m]], s: S.D}, {ops: [r64, [xmm, m]], s: S.Q, mod: M.X64}, ], vcvttss2si: [{o: 0x2C, ext: [EXT.AVX]}, {vex: 'LIG.F3.0F.W0', ops: [r32, [xmm, m]], s: S.D}, {vex: 'LIG.F3.0F.W1', ops: [r64, [xmm, m]], s: S.Q, mod: M.X64}, ], // # D-letter daa: [{o: 0x27, mod: M.OLD}], das: [{o: 0x2F, mod: M.OLD}], divpd: [{o: 0x660F5E, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vdivpd: [{o: 0x5E, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.66.0F.WIG', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.256.66.0F.WIG', ops: [ymm, ymm, [ymm, m]]}, ], divps: [{o: 0x0F5E, ops: [xmm, [xmm, m]], ext: [EXT.SSE]}], vdivps: [{o: 0x5E, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.0F.WIG', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.256.0F.WIG', ops: [ymm, ymm, [ymm, m]]}, ], divsd: [{o: 0xF20F5E, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vdivsd: [{o: 0x5E, en: 'rvm', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.LIG.F2.0F.WIG', ext: [EXT.AVX]}, {evex: 'NDS.LIG.F2.0F.W1', ext: [EXT.AVX512F]}, ], divss: [{o: 0xF30F5E, ops: [xmm, [xmm, m]], ext: [EXT.SSE]}], vdivss: [{o: 0x5E, en: 'rvm', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.LIG.F3.0F.WIG', ext: [EXT.AVX]}, ], dppd: [{o: 0x0F3A41, pfx: [0x66], ops: [xmm, [xmm, m], imm8], ext: [EXT.SSE4_1]}], vdppd: [{o: 0x41, vex: 'NDS.128.66.0F3A.WIG', ops: [xmm, xmm, [xmm, m], imm8], ext: [EXT.AVX]}], dpps: [{o: 0x0F3A40, pfx: [0x66], ops: [xmm, [xmm, m], imm8], ext: [EXT.SSE4_1]}], vdpps: [{o: 0x40, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.66.0F3A.WIG', ops: [xmm, xmm, [xmm, m], imm8]}, {vex: 'NDS.256.66.0F3A.WIG', ops: [ymm, ymm, [ymm, m], imm8]}, ], // # E-letter emms: [{o: 0x0F77}], extractps: [{o: 0x0F3A17, pfx: [0x66], en: 'mr', ops: [r32, xmm, imm8], s: S.D, ext: [EXT.SSE4_1]}], vextractps: [{o: 0x17, en: 'mr', vex: '128.66.0F3A.WIG', ops: [rm32, xmm, imm8], s: S.Q, ext: [EXT.AVX]}], // # F-letter f2xm1: [{o: 0xD9F0}], fabs: [{o: 0xD9E1}], fadd: [{}, {o: 0xD8, or: 0, ops: [m], s: S.D}, {o: 0xDC, or: 0, ops: [m], s: S.Q}, {o: 0xD8, ops: [o.st(0), st]}, {o: 0xDC, ops: [st, o.st(0)]}, ], faddp: [{}, {o: 0xDE, ops: [st, o.st(0)]}, {o: 0xDEC1}, ], fiadd: [{or: 0}, {o: 0xDA, ops: [m], s: S.D}, {o: 0xDE, ops: [m], s: S.W}, ], fbld: [{o: 0xDF, or: 4, ops: [m]}], fbstp: [{o: 0xDF, or: 6, ops: [m]}], fchs: [{o: 0xD9E0}], fclex: [{o: 0x9BDBE2}], fnclex: [{o: 0xDBE2}], fcmovb: [{o: 0xDA, or: 0, ops: [st]}], fcmove: [{o: 0xDA, or: 1, ops: [st]}], fcmovbe: [{o: 0xDA, or: 2, ops: [st]}], fcmovu: [{o: 0xDA, or: 3, ops: [st]}], fcmovnb: [{o: 0xDB, or: 0, ops: [st]}], fcmovne: [{o: 0xDB, or: 1, ops: [st]}], fcmovnbe: [{o: 0xDB, or: 2, ops: [st]}], fcmovnu: [{o: 0xDB, or: 3, ops: [st]}], fcom: [{or: 2}, {o: 0xD8, ops: [m], s: S.D}, {o: 0xDC, ops: [m], s: S.Q}, {o: 0xD8, ops: [st]}, {o: 0xD8D1}, ], fcomp: [{or: 3}, {o: 0xD8, ops: [m], s: S.D}, {o: 0xDC, ops: [m], s: S.Q}, {o: 0xD8, ops: [st]}, {o: 0xD8D9}, ], fcompp: [{o: 0xDED9}], fcomi: [{o: 0xDB, or: 6, ops: [st]}], fcomip: [{o: 0xDF, or: 6, ops: [st]}], fucomi: [{o: 0xDB, or: 5, ops: [st]}], fucomip:[{o: 0xDF, or: 5, ops: [st]}], fcos: [{o: 0xD9FF}], fdecstp: [{o: 0xD9F6}], fdiv: [{}, {o: 0xD8, or: 6, ops: [m], s: S.D}, {o: 0xDC, or: 6, ops: [m], s: S.Q}, {o: 0xD8, i: 0xF0, ops: [o.st(0), st]}, {o: 0xDC, i: 0xF8, ops: [st, o.st(0)]}, ], fdivp: [{}, {o: 0xDE, i: 0xF8, ops: [st, o.st(0)]}, {o: 0xDEF9}, ], fidiv: [{or: 6}, {o: 0xDA, ops: [m], s: S.D}, {o: 0xDE, ops: [m], s: S.W}, ], fdivr: [{}, {o: 0xD8, or: 7, ops: [m], s: S.D}, {o: 0xDC, or: 7, ops: [m], s: S.Q}, {o: 0xD8, i: 0xF8, ops: [o.st(0), st]}, {o: 0xDC, i: 0xF0, ops: [st, o.st(0)]}, ], fdivrp: [{o: 0xDE}, {i: 0xF0, ops: [st, o.st(0)]}, {i: 0xF1}, ], fidivr: [{or: 7}, {o: 0xDA, ops: [m], s: S.D}, {o: 0xDE, ops: [m], s: S.W}, ], ffree: [{o: 0xDD, i: 0xC0, ops: [st]}], ficom: [{or: 2}, {o: 0xDE, ops: [m], s: S.W}, {o: 0xDA, ops: [m], s: S.D}, ], ficomp: [{or: 3}, {o: 0xDE, ops: [m], s: S.W}, {o: 0xDA, ops: [m], s: S.D}, ], fild: [{}, {o: 0xDF, or: 0, ops: [m], s: S.W}, {o: 0xDB, or: 0, ops: [m], s: S.D}, {o: 0xDF, or: 5, ops: [m], s: S.Q}, ], fincstp: [{o: 0xD9F7}], finit: [{o: 0x9BDBE3}], fninit: [{o: 0xDBE3}], fist: [{or: 2, ops: [m]}, {o: 0xDF, s: S.W}, {o: 0xDB, s: S.D}, ], fistp: [{ops: [m]}, {o: 0xDF, or: 3, s: S.W}, {o: 0xDB, or: 3, s: S.D}, {o: 0xDF, or: 7, s: S.Q}, ], fisttp: [{or: 1, ops: [m]}, {o: 0xDF, s: S.W}, {o: 0xDB, s: S.D}, {o: 0xDD, s: S.Q}, ], fld: [{}, {o: 0xD9, or: 0, ops: [m], s: S.D}, {o: 0xDD, or: 0, ops: [m], s: S.Q}, {o: 0xDB, or: 5, ops: [m], s: S.T}, {o: 0xD9, i: 0xC0, ops: [st]}, ], fld1: [{o: 0xD9E8}], fldl2t: [{o: 0xD9E9}], fldl2e: [{o: 0xD9EA}], fldpi: [{o: 0xD9EB}], fldlg2: [{o: 0xD9EC}], fldln2: [{o: 0xD9ED}], fldz: [{o: 0xD9EE}], fldcw: [{o: 0xD9, or: 5, ops: [m], s: S.W}], fldenv: [{o: 0xD9, or: 4, ops: [m]}], // TODO: Size? What is `m14/28byte` fmul: [{}, {o: 0xD8, or: 1, ops: [m], s: S.D}, {o: 0xDC, or: 1, ops: [m], s: S.Q}, {o: 0xD8, i: 0xC8, ops: [o.st(0), st]}, {o: 0xDC, i: 0xC8, ops: [st, o.st(0)]}, ], fmulp: [{}, {o: 0xDE, i: 0xC8, ops: [st, o.st(0)]}, {o: 0xDEC9}, ], fimul: [{or: 1}, {o: 0xDA, ops: [m], s: S.D}, {o: 0xDE, ops: [m], s: S.Q}, ], fnop: [{o: 0xD9D0}], fpatan: [{o: 0xD9F3}], fprem: [{o: 0xD9F8}], fprem1: [{o: 0xD9F5}], fptan: [{o: 0xD9F2}], frndint:[{o: 0xD9FC}], frstor: [{o: 0xDD, or: 4, ops: [m]}], // TODO: m94/108byte ? fsave: [{o: 0x9BDD, or: 6, ops: [m]}], fnsave: [{o: 0xDD, or: 6, ops: [m]}], fscale: [{o: 0xD9FD}], fsin: [{o: 0xD9FE}], fsincos: [{o: 0xD9FB}], fsqrt: [{o: 0xD9FA}], fst: [{}, {o: 0xD9, or: 2, ops: [m], s: S.D}, {o: 0xDD, or: 2, ops: [m], s: S.Q}, {o: 0xDD, i: 0xD0, ops: [st]}, ], fstp: [{}, {o: 0xD9, or: 3, ops: [m], s: S.D}, {o: 0xDD, or: 3, ops: [m], s: S.Q}, {o: 0xDB, or: 7, ops: [m], s: S.T}, {o: 0xDD, i: 0xD8, ops: [st]}, ], fstcw: [{o: 0x9BD9, or: 7, ops: [m], s: S.W}], fnstcw: [{o: 0xD9, or: 7, ops: [m], s: S.W}], fstenv: [{o: 0x9BD9, or: 6, ops: [m]}], fnstenv: [{o: 0xD9, or: 6, ops: [m]}], fstsw: [{}, {o: 0x9BDD, or: 7, ops: [m], s: S.W}, {o: 0x9BDFE0, mr: false, ops: [o.ax]}, ], fnstsw: [{}, {o: 0xDD, or: 7, ops: [m], s: S.W}, {o: 0xDFE0, mr: false, ops: [o.ax]}, ], fsub: [{}, {o: 0xD8, or: 4, ops: [m], s: S.D}, {o: 0xDC, or: 4, ops: [m], s: S.Q}, {o: 0xD8, i: 0xE0, ops: [o.st(0), st]}, {o: 0xDC, i: 0xE8, ops: [st, o.st(0)]}, ], fsubp: [{}, {o: 0xDE, i: 0xE8, ops: [st, o.st(0)]}, {o: 0xDEE9}, ], fisub: [{or: 4}, {o: 0xDA, ops: [m], s: S.D}, {o: 0xDE, ops: [m], s: S.W}, ], fsubr: [{}, {o: 0xD8, or: 5, ops: [m], s: S.D}, {o: 0xDC, or: 5, ops: [m], s: S.Q}, {o: 0xD8, i: 0xE8, ops: [o.st(0), st]}, {o: 0xDC, i: 0xE0, ops: [st, o.st(0)]}, ], fsubrp: [{}, {o: 0xDE, i: 0xE0, ops: [st, o.st(0)]}, {o: 0xDEE1}, ], fisubr: [{or: 5}, {o: 0xDA, ops: [m], s: S.D}, {o: 0xDE, ops: [m], s: S.W}, ], ftst: [{o: 0xD9E4}], fucom: [{o: 0xDD, i: 0xE0, ops: [st]}], fucomp: [{o: 0xDD, i: 0xE8, ops: [st]}], fucompp: [{o: 0xDAE9}], fxam: [{o: 0xD9E5}], fxch: [{o: 0xD9, i: 0xC8, ops: [st]}], fxrstor: [{o: 0x0FAE, or: 1, ops: [m], s: 512}], fxrstor64: [{o: 0x0FAE, or: 1, ops: [m], s: 512, mod: M.X64}], fxsave: [{o: 0x0FAE, or: 0, ops: [m], s: 512}], fxsave64: [{o: 0x0FAE, or: 0, ops: [m], s: 512, mod: M.X64}], fxtract: [{o: 0xD9F4}], fyl2x: [{o: 0xD9F1}], fyl2xp1: [{o: 0xD9F9}], // # H-letter haddpd: [{o: 0x660F7C, ops: [xmm, [xmm, m]], ext: [EXT.SSE3]}], vhaddpd: [{o: 0x7C, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.66.0F.WIG', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.256.66.0F.WIG', ops: [ymm, ymm, [ymm, m]]}, ], haddps: [{o: 0xF20F7C, ops: [xmm, [xmm, m]], ext: [EXT.SSE3]}], vhaddps: [{o: 0x7C, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.F2.0F.WIG', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.256.F2.0F.WIG', ops: [ymm, ymm, [ymm, m]]}, ], hlt: [{o: 0xF4}], hsubpd: [{o: 0x660F7D, ops: [xmm, [xmm, m]], ext: [EXT.SSE3]}], vhsubpd: [{o: 0x7D, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.66.0F.WIG', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.256.66.0F.WIG', ops: [ymm, ymm, [ymm, m]]}, ], hsubps: [{o: 0xF20F7D, ops: [xmm, [xmm, m]], ext: [EXT.SSE3]}], vhsubps: [{o: 0x7D, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.F2.0F.WIG', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.256.F2.0F.WIG', ops: [ymm, ymm, [ymm, m]]}, ], // # I-letter insertps: [{o: 0x0F3A21, pfx: [0x66], ops: [xmm, [xmm, m], imm8], ext: [EXT.SSE4_1]}], vinsertps: [{o: 0x21, vex: 'NDS.128.66.0F3A.WIG', en: 'rvm', ops: [xmm, xmm, [xmm, m], imm8], ext: [EXT.AVX]}], invd: [{o: 0x0F08}], invlpg: [{o: 0x0F01, or: 7, ops: [m]}], invpcid: [{o: 0x3882, pfx: [0x66, 0x0F], ext: [EXT.INVPCID]}, {ops: [r32, m], mod: M.X32}, {ops: [r64, m], mod: M.X64}, ], // # J-letter // # L-letter lahf: [{o: 0x9F, mod: M.COMP | M.LEG}], lar: [{o: 0x0F02}, {ops: [r16, rm16]}, {ops: [r, rm32]}, ], lddqu: [{o: 0xF20FF0, ops: [xmm, m], ext: [EXT.SSE3]}], vlddqu: [{o: 0xF0, ext: [EXT.AVX]}, {vex: '128.F2.0F.WIG', ops: [xmm, m]}, {vex: '256.F2.0F.WIG', ops: [ymm, m]}, ], ldmxcsr: [{o: 0x0FAE, or: 2, ops: [m], s: S.D, ext: ext_sse}], vldmxcsr: [{o: 0xAE, or: 2, vex: 'VEX.LZ.0F.WIG', ops: [m], ext: ext_avx}], lfence: [{o: 0x0FAEE8}], lgdt: [{o: 0x0F01, or: 2}, // TODO: Fix memory sizes. {ops: [m]}, ], lidt: [{o: 0x0F01, or: 3}, {ops: [m]}, ], lldt: [{o: 0x0F00, or: 2, ops: [rm16]}], lmsw: [{o: 0x0F01, or: 6, ops: [rm16]}], lock: [{o: 0xF0}], lsl: [{o: 0x0F03}, {ops: [r16, rm16]}, {ops: [r32, rm32]}, {ops: [r64, rm32], s: S.Q}, ], ltr: [{o: 0x0F00, or: 3, ops: [rm16]}], lzcnt: [{o: 0x0FBD, pfx: [0xF3], ext: [EXT.LZCNT]}, {ops: [r16, rm16]}, {ops: [r32, rm32]}, {ops: [r64, rm64]}, ], // # M-letter maskmovdqu: [{o: 0x660FF7, ops: [xmm, xmm], ext: [EXT.SSE2]}], vmaskmovdqu: [{o: 0xF7, vex: '128.66.0F.WIG', ops: [xmm, xmm], ext: [EXT.AVX]}], maskmovq: [{o: 0x0FF7, ops: [mm, mm]}], maxpd: [{o: 0x660F5F, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vmaxpd: [{o: 0x5F, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.66.0F.WIG', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.256.66.0F.WIG', ops: [ymm, ymm, [ymm, m]]}, ], maxps: [{o: 0x0F5F, ops: [xmm, [xmm, m]], ext: [EXT.SSE]}], vmaxps: [{o: 0x5F, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.0F.WIG', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.256.0F.WIG', ops: [ymm, ymm, [ymm, m]]}, ], maxsd: [{o: 0xF20F5F, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vmaxsd: [{o: 0x5F, vex: 'NDS.LIG.F2.0F.WIG', en: 'rvm', ops: [xmm, xmm, [xmm, m]], ext: [EXT.AVX]}], maxss: [{o: 0xF30F5F, ops: [xmm, [xmm, m]], ext: [EXT.SSE]}], vmaxss: [{o: 0x5F, vex: 'NDS.LIG.F3.0F.WIG', en: 'rvm', ops: [xmm, xmm, [xmm, m]], ext: [EXT.AVX]}], mfence: [{o: 0x0FAEF0}], minpd: [{o: 0x660F5D, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vminpd: [{o: 0x5D, ext: [EXT.AVX]}, {vex: 'NDS.128.66.0F.WIG', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.256.66.0F.WIG', ops: [ymm, ymm, [ymm, m]]}, ], minps: [{o: 0x0F5D, ops: [xmm, [xmm, m]], ext: [EXT.SSE]}], vminps: [{o: 0x5D, ext: [EXT.AVX]}, {vex: 'NDS.128.0F.WIG', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.256.0F.WIG', ops: [ymm, ymm, [ymm, m]]}, ], minsd: [{o: 0xF20F5D, ops: [xmm, [xmm, m]], ext: [EXT.SSE2]}], vminsd: [{o: 0x5D, vex: 'NDS.LIG.F2.0F.WIG', en: 'rvm', ops: [xmm, xmm, [xmm, m]], ext: [EXT.AVX]}], minss: [{o: 0xF30F5D, ops: [xmm, [xmm, m]], ext: [EXT.SSE]}], vminss: [{o: 0x5D, vex: 'NDS.LIG.F3.0F.WIG', en: 'rvm', ops: [xmm, xmm, [xmm, m]], ext: [EXT.AVX]}], monitor: [{o: 0x0F01C8}], movapd: [{pfx: [0x66, 0x0F], ext: [EXT.SSE2]}, {o: 0x28, ops: [xmm, [xmm, m]], dbit: true}, {o: 0x29, ops: [[xmm, m], xmm], dbit: true, en: 'mr'}, ], vmovapd: [{ext: [EXT.AVX]}, {o: 0x28, vex: '128.66.0F.WIG', ops: [xmm, [xmm, m]], dbit: true}, {o: 0x29, vex: '128.66.0F.WIG', ops: [[xmm, m], xmm], dbit: true, en: 'mr'}, {o: 0x28, vex: '256.66.0F.WIG', ops: [ymm, [ymm, m]], dbit: true}, {o: 0x29, vex: '256.66.0F.WIG', ops: [[ymm, m], ymm], dbit: true, en: 'mr'}, ], movaps: [{pfx: [0x0F], ext: [EXT.SSE]}, {o: 0x28, ops: [xmm, [xmm, m]], dbit: true}, {o: 0x29, ops: [[xmm, m], xmm], dbit: true, en: 'mr'}, ], vmovaps: [{ext: [EXT.AVX]}, {o: 0x28, vex: '128.0F.WIG', ops: [xmm, [xmm, m]], dbit: true}, {o: 0x29, vex: '128.0F.WIG', ops: [[xmm, m], xmm], dbit: true, en: 'mr'}, {o: 0x28, vex: '256.0F.WIG', ops: [ymm, [ymm, m]], dbit: true}, {o: 0x29, vex: '256.0F.WIG', ops: [[ymm, m], ymm], dbit: true, en: 'mr'}, ], movd: [{}, // 0F 6E /r MOVD mm, r/m32 RM V/V MMX Move doubleword from r/m32 to mm. {o: 0x0F6E, ops: [mm, rm32], s: S.D, ext: [EXT.MMX]}, // 0F 7E /r MOVD r/m32, mm MR V/V MMX Move doubleword from mm to r/m32. {o: 0x0F7E, ops: [rm32, mm], s: S.D, ext: [EXT.MMX]}, // 66 0F 6E /r MOVD xmm, r/m32 RM V/V SSE2 Move doubleword from r/m32 to xmm. {o: 0x0F6E, pfx: [0x66], ops: [xmm, rm32], s: S.D, ext: [EXT.SSE2]}, // 66 0F 7E /r MOVD r/m32, xmm MR V/V SSE2 Move doubleword from xmm register to r/m32. {o: 0x0F7E, pfx: [0x66], ops: [rm32, xmm], s: S.D, ext: [EXT.SSE2]}, ], vmovd: [{ext: [EXT.AVX]}, // VEX.128.66.0F.W0 6E / VMOVD xmm1, r32/m32 RM V/V AVX Move doubleword from r/m32 to xmm1. {o: 0x6E, vex: '128.66.0F.W0', ops: [xmm, rm32], s: S.D}, // VEX.128.66.0F.W0 7E /r VMOVD r32/m32, xmm1 MR V/V AVX Move doubleword from xmm1 register to r/m32. {o: 0x7E, vex: '128.66.0F.W0', ops: [rm32, xmm], s: S.D}, ], movq: [{mod: M.X64}, // REX.W + 0F 6E /r MOVQ mm, r/m64 RM V/N.E. MMX Move quadword from r/m64 to mm. {o: 0x0F6E, ops: [mm, rm64], s: S.Q, ext: [EXT.MMX]}, // REX.W + 0F 7E /r MOVQ r/m64, mm MR V/N.E. MMX Move quadword from mm to r/m64. {o: 0x0F7E, ops: [rm64, mm], s: S.Q, ext: [EXT.MMX]}, // 66 REX.W 0F 6E /r MOVQ xmm, r/m64 RM V/N.E. SSE2 Move quadword from r/m64 to xmm. {o: 0x0F6E, pfx: [0x66], ops: [xmm, rm64], s: S.Q, ext: [EXT.SSE2]}, // 66 REX.W 0F 7E /r MOVQ r/m64, xmm MR V/N.E. SSE2 Move quadword from xmm register to r/m64. {o: 0x0F7E, pfx: [0x66], ops: [rm64, xmm], s: S.Q, ext: [EXT.SSE2]}, // MOVQ—Move Quadword // 0F 6F /r MOVQ mm, mm/m64 RM V/V MMX Move quadword from mm/m64 to mm. {o: 0x0F6F, ops: [mm, [mm, m64]], s: S.Q, ext: ext_mmx}, // 0F 7F /r MOVQ mm/m64, mm MR V/V MMX Move quadword from mm to mm/m64. {o: 0x0F7F, ops: [[mm, m64], mm], s: S.Q, en: 'mr', ext: ext_mmx}, // F3 0F 7E /r MOVQ xmm1, xmm2/m64 RM V/V SSE2 Move quadword from xmm2/mem64 to xmm1. {o: 0xF30F7E, ops: [xmm, [xmm, m64]], s: S.Q, ext: ext_sse2}, // 66 0F D6 /r MOVQ xmm2/m64, xmm1 MR V/V SSE2 Move quadword from xmm1 to xmm2/mem64. {o: 0x660FD6, ops: [[xmm, m64], xmm], s: S.Q, en: 'mr', ext: ext_sse2}, ], vmovq: [{mod: M.X64, ext: [EXT.AVX]}, // VEX.128.66.0F.W1 6E /r VMOVQ xmm1, r64/m64 RM V/N.E. AVX Move quadword from r/m64 to xmm1. {o: 0x6E, vex: '128.66.0F.W1', ops: [xmm, rm64], s: S.Q}, // VEX.128.66.0F.W1 7E /r VMOVQ r64/m64, xmm1 MR V/N.E. AVX Move quadword from xmm1 register to r/m64. {o: 0x7E, vex: '128.66.0F.W1', ops: [rm64, xmm], s: S.Q, en: 'mr'}, // VEX.128.F3.0F.WIG 7E /r VMOVQ xmm1, xmm2 RM V/V AVX Move quadword from xmm2 to xmm1. {o: 0x7E, vex: '128.F3.0F.WIG', ops: [xmm, xmm]}, // VEX.128.F3.0F.WIG 7E /r VMOVQ xmm1, m64 RM V/V AVX Load quadword from m64 to xmm1. {o: 0x7E, vex: '128.F3.0F.WIG', ops: [xmm, m64], s: S.Q}, // VEX.128.66.0F.WIG D6 /r VMOVQ xmm1/m64, xmm2 MR V/V AVX Move quadword from {o: 0xD6, vex: '128.66.0F.WIG', ops: [[xmm, m64], xmm], s: S.Q, en: 'mr'}, ], movddup: [{o: 0xF20F12, ops: [xmm, [xmm, m]], ext: [EXT.SSE3]}], vmovddup: [{o: 0x12, ext: [EXT.AVX]}, {vex: '128.F2.0F.WIG', ops: [xmm, [xmm, m]]}, {vex: '256.F2.0F.WIG', ops: [ymm, [ymm, m]]}, ], movdqa: [{pfx: [0x66, 0x0F], ext: [EXT.SSE2]}, {o: 0x6F, ops: [xmm, [xmm, m]]}, {o: 0x7F, ops: [[xmm, m], xmm], en: 'mr'}, ], vmovdqa: [{ext: [EXT.AVX]}, {o: 0x6F, vex: '128.66.0F.WIG', ops: [xmm, [xmm, m]]}, {o: 0x7F, vex: '128.66.0F.WIG', ops: [[xmm, m], xmm], en: 'mr'}, {o: 0x6F, vex: '256.66.0F.WIG', ops: [ymm, [ymm, m]]}, {o: 0x7F, vex: '256.66.0F.WIG', ops: [[ymm, m], ymm], en: 'mr'}, ], movdqu: [{pfx: [0xF3, 0x0F], ext: [EXT.SSE2]}, {o: 0x6F, ops: [xmm, [xmm, m]]}, {o: 0x7F, ops: [[xmm, m], xmm], en: 'mr'}, ], vmovdqu: [{ext: [EXT.AVX]}, {o: 0x6F, vex: '128.F3.0F.WIG', ops: [xmm, [xmm, m]]}, {o: 0x7F, vex: '128.F3.0F.WIG', ops: [[xmm, m], xmm], en: 'mr'}, {o: 0x6F, vex: '256.F3.0F.WIG', ops: [ymm, [ymm, m]]}, {o: 0x7F, vex: '256.F3.0F.WIG', ops: [[ymm, m], ymm], en: 'mr'}, ], movdq2q: [{o: 0xF20FD6, ops: [mm, xmm]}], movhlps: [{o: 0x0F12, ops: [xmm, xmm], ext: [EXT.SSE]}], vmovhlps: [{o: 0x12, vex: 'NDS.128.0F.WIG', en: 'rvm', ops: [xmm, xmm, xmm], ext: [EXT.AVX]}], movhpd: [{pfx: [0x66, 0x0F], ext: [EXT.SSE2]}, {o: 0x16, ops: [xmm, m64], dbit: true}, {o: 0x17, ops: [m64, xmm], dbit: true, en: 'mr'}, ], vmovhpd: [{ext: [EXT.AVX]}, {o: 0x16, vex: 'NDS.128.66.0F.WIG', ops: [xmm, xmm, m64], en: 'rvm'}, {o: 0x17, vex: '128.66.0F.WIG', ops: [m64, xmm], en: 'mr'}, ], movhps: [{pfx: [0x0F], ext: [EXT.SSE]}, {o: 0x16, ops: [xmm, m64], dbit: true}, {o: 0x17, ops: [m64, xmm], dbit: true, en: 'mr'}, ], vmovhps: [{ext: [EXT.AVX]}, {o: 0x16, vex: 'NDS.128.0F.WIG', ops: [xmm, xmm, m64], en: 'rvm'}, {o: 0x17, vex: '128.0F.WIG', ops: [m64, xmm], en: 'mr'}, ], movlhps: [{o: 0x0F16, ops: [xmm, xmm], ext: [EXT.SSE]}], vmovlhps: [{o: 0x16, vex: 'NDS.128.0F.WIG', en: 'rvm', ops: [xmm, xmm, xmm], ext: [EXT.AVX]}], movlpd: [{pfx: [0x66, 0x0F], ext: [EXT.SSE2]}, {o: 0x12, ops: [xmm, m64], dbit: true}, {o: 0x13, ops: [m64, xmm], dbit: true, en: 'mr'}, ], vmovlpd: [{ext: [EXT.AVX]}, {o: 0x12, vex: 'NDS.128.66.0F.WIG', ops: [xmm, xmm, m64], en: 'rvm'}, {o: 0x13, vex: '128.66.0F.WIG', ops: [m64, xmm], en: 'mr'}, ], movlps: [{pfx: [0x0F], ext: [EXT.SSE]}, {o: 0x12, ops: [xmm, m64], dbit: true}, {o: 0x13, ops: [m64, xmm], dbit: true, en: 'mr'}, ], vmovlps: [{ext: [EXT.AVX]}, {o: 0x12, vex: 'NDS.128.0F.WIG', ops: [xmm, xmm, m64], en: 'rvm'}, {o: 0x13, vex: '128.0F.WIG', ops: [m64, xmm], en: 'mr'}, ], movmskpd: [{o: 0x660F50, ops: [r, xmm], ext: [EXT.SSE2]}], vmovmskpd: [{o: 0x50, ext: [EXT.AVX]}, {vex: '128.66.0F.WIG', ops: [r, xmm]}, {vex: '256.66.0F.WIG', ops: [r, ymm]}, ], movmskps: [{o: 0x0F50, ops: [r, xmm], ext: [EXT.SSE]}], vmovmskps: [{o: 0x50, ext: [EXT.AVX]}, {vex: '128.0F.WIG', ops: [r, xmm]}, {vex: '256.0F.WIG', ops: [r, ymm]}, ], movntdqa: [{o: 0x382A, pfx: [0x66, 0x0F], ops: [xmm, m], ext: [EXT.SSE4_1]}], vmovntdqa: [{o: 0x2A}, {vex: '128.66.0F38.WIG', ops: [xmm, m], ext: [EXT.AVX]}, {vex: '256.66.0F38.WIG', ops: [ymm, m], ext: [EXT.AVX2]}, ], movntdq: [{o: 0xE7, pfx: [0x66, 0x0F], en: 'mr', ops: [m128, xmm], ext: [EXT.SSE2]}], vmovntdq: [{o: 0xE7, ext: [EXT.AVX]}, {vex: '128.66.0F.WIG', en: 'mr', ops: [m, xmm]}, {vex: '256.66.0F.WIG', en: 'mr', ops: [m, ymm]}, ], movnti: [{o: 0x0FC3, en: 'mr'}, {ops: [m32, r32]}, {ops: [m64, r64]}, ], movntpd: [{o: 0x2B, pfx: [0x66, 0x0F], en: 'mr', ops: [m128, xmm], ext: [EXT.SSE2]}], vmovntpd: [{o: 0x2B, ext: [EXT.AVX]}, {vex: '128.66.0F.WIG', en: 'mr', ops: [m, xmm]}, {vex: '256.66.0F.WIG', en: 'mr', ops: [m, ymm]}, ], movntps: [{o: 0x2B, pfx: [0x0F], en: 'mr', ops: [m, xmm], ext: [EXT.SSE]}], vmovntps: [{o: 0x2B, en: 'mr', ext: [EXT.AVX]}, {vex: '128.0F.WIG', ops: [m, xmm]}, {vex: '256.0F.WIG', ops: [m, ymm]}, ], movntq: [{o: 0x0FE7, ops: [m64, mm], en: 'mr'}], movq2dq: [{o: 0xF30FD6, ops: [xmm, mm]}], movsd: [{pfx: [0xF2, 0x0F], ext: [EXT.SSE2]}, {o: 0x10, ops: [xmm, [xmm, m64]], dbit: true}, {o: 0x11, ops: [[xmm, m64], xmm], dbit: true, en: 'mr'}, ], vmovsd: [{ext: [EXT.AVX]}, {o: 0x10, vex: 'NDS.LIG.F2.0F.WIG', ops: [xmm, xmm, xmm], en: 'rvm'}, {o: 0x10, vex: 'LIG.F2.0F.WIG', ops: [xmm, m64], en: 'rm'}, {o: 0x11, vex: 'NDS.LIG.F2.0F.WIG', ops: [xmm, xmm, xmm], en: 'mvr'}, {o: 0x11, vex: 'LIG.F2.0F.WIG', ops: [m64, xmm], en: 'mr'}, ], movshdup: [{o: 0xF30F16, ops: [xmm, [xmm, m]], ext: [EXT.SSE3]}], vmovshdup: [{o: 0x16, ext: [EXT.AVX]}, {vex: '128.F3.0F.WIG', ops: [xmm, [xmm, m]]}, {vex: '256.F3.0F.WIG', ops: [ymm, [ymm, m]]}, ], movsldup: [{o: 0xF30F12, ops: [xmm, [xmm, m]], ext: [EXT.SSE3]}], vmovsldup: [{o: 0x12, ext: [EXT.AVX]}, {vex: '128.F3.0F.WIG', ops: [xmm, [xmm, m]]}, {vex: '256.F3.0F.WIG', ops: [ymm, [ymm, m]]}, ], movss: [{ext: [EXT.SSE]}, {o: 0xF30F10, ops: [xmm, [xmm, m]]}, {o: 0xF30F11, ops: [[xmm, m], xmm], en: 'mr'}, ], vmovss: [{ext: [EXT.AVX]}, {o: 0x10, vex: 'NDS.LIG.F3.0F.WIG', ops: [xmm, xmm, xmm], en: 'rvm'}, {o: 0x10, vex: 'LIG.F3.0F.WIG', ops: [xmm, m]}, {o: 0x11, vex: 'NDS.LIG.F3.0F.WIG', ops: [xmm, xmm, xmm], en: 'mvr'}, {o: 0x11, vex: 'LIG.F3.0F.WIG', ops: [m, xmm], en: 'mr'}, ], movupd: [{ext: [EXT.SSE2]}, {o: 0x660F10, ops: [xmm, [xmm, m]]}, {o: 0x660F11, ops: [[xmm, m], xmm], en: 'mr'}, ], vmovupd: [{ext: [EXT.AVX]}, {o: 0x10, vex: '128.66.0F.WIG', ops: [xmm, [xmm, m]]}, {o: 0x10, vex: '256.66.0F.WIG', ops: [ymm, [ymm, m]]}, {o: 0x11, vex: '128.66.0F.WIG', ops: [xmm, [xmm, m]], en: 'mr'}, {o: 0x11, vex: '256.66.0F.WIG', ops: [ymm, [ymm, m]], en: 'mr'}, ], movups: [{ext: [EXT.SSE]}, {o: 0x0F10, ops: [xmm, [xmm, m]]}, {o: 0x0F11, ops: [[xmm, m], xmm], en: 'mr'}, ], vmovups: [{ext: [EXT.AVX]}, {o: 0x10, vex: '128.0F.WIG', ops: [xmm, [xmm, m]]}, {o: 0x10, vex: '256.0F.WIG', ops: [ymm, [ymm, m]]}, {o: 0x11, vex: '128.0F.WIG', ops: [xmm, [xmm, m]], en: 'mr'}, {o: 0x11, vex: '256.0F.WIG', ops: [ymm, [ymm, m]], en: 'mr'}, ], mpsadbw: [{o: 0x42, pfx: [0x66, 0x0F, 0x3A], ops: [xmm, [xmm, m], imm8], ext: [EXT.SSE4_1]}], vmpsadbw: [{o: 0x42, en: 'rvm'}, {ops: [xmm, xmm, [xmm, m], imm8], ext: [EXT.AVX]}, {ops: [ymm, ymm, [ymm, m], imm8], ext: [EXT.AVX2]}, ], mulps: [{o: 0x59, pfx: [0x0F], ops: [xmm, [xmm, m]], ext: [EXT.SSE]}], vmulps: [{o: 0x59, ext: [EXT.AVX]}, {vex: 'NDS.128.0F.WIG', ops: [xmm, xmm, [xmm, m]]}, {vex: 'NDS.256.0F.WIG', ops: [ymm, ymm, [ymm, m]]}, ], mulsd: [{o: 0x59, pfx: [0xF2, 0x0F], ops: xmm_xmmm, ext: [EXT.SSE2]}], vmulsd: [{o: 0x59, vex: 'NDS.LIG.F2.0F.WIG', ops: xmm_xmm_xmmm, en: 'rvm', ext: [EXT.AVX]}], mulss: [{o: 0x59, pfx: [0xF3, 0x0F], ops: xmm_xmmm, ext: [EXT.SSE]}], vmulss: [{o: 0x59, vex: 'NDS.LIG.F3.0F.WIG', ops: xmm_xmm_xmmm, en: 'rvm', ext: [EXT.AVX]}], mulx: [{o: 0xF6, en: 'rvm', ext: [EXT.BMI2]}, {vex: 'NDD.LZ.F2.0F38.W0', ops: [r32, r32, rm32]}, {vex: 'NDD.LZ.F2.0F38.W1', ops: [r64, r64, rm64]}, ], mwait: [{o: 0x0F01C9}], // # O-letter orpd: [{o: 0x56, pfx: [0x66, 0x0F], ops: xmm_xmmm, ext: [EXT.SSE2]}], vorpd: [{o: 0x56, ext: [EXT.AVX]}, {vex: 'NDS.128.66.0F.WIG', ops: xmm_xmm_xmmm}, {vex: 'NDS.256.66.0F.WIG', ops: ymm_ymm_ymmm}, ], orps: [{o: 0x56, pfx: [0x0F], ops: xmm_xmmm, ext: [EXT.SSE]}], vorps: [{o: 0x56, en: 'rvm', ext: [EXT.AVX]}, {vex: 'NDS.128.0F.WIG', ops: xmm_xmm_xmmm}, {vex: 'NDS.256.0F.WIG', ops: ymm_ymm_ymmm}, ], // # P-letter pabsb: [{o: 0x1C, ext: [EXT.SSSE3]}, {pfx: [0x0F, 0x38], ops: [mm, [mm, m]]}, {pfx: [0x66, 0x0F, 0x38], ops: xmm_xmmm}, ], vpabsb: [{o: 0x1C}, {vex: '128.66.0F38.WIG', ops: xmm_xmmm, ext: [EXT.AVX]}, {vex: '256.66.0F38.WIG', ops: ymm_ymmm, ext: [EXT.AVX2]}, ], pabsw: [{o: 0x1D, ext: [EXT.SSSE3]}, {pfx: [0x0F, 0x38], ops: [mm, [mm, m]]}, {pfx: [0x66, 0x0F, 0x38], ops: xmm_xmmm}, ], vpabsw: [{o: 0x1D}, {vex: '128.66.0F38.WIG', ops: xmm_xmmm, ext: ext_avx}, {vex: '256.66.0F38.WIG', ops: ymm_ymmm, ext: ext_avx2}, ], pabsd: [{o: 0x1E, ext: [EXT.SSSE3]}, {pfx: [0x0F, 0x38], ops: [mm, [mm, m]]}, {pfx: [0x66, 0x0F, 0x38], ops: xmm_xmmm}, ], vpabsd: [{o: 0x1E}, {vex: '128.66.0F38.WIG', ops: xmm_xmmm, ext: ext_avx}, {vex: '256.66.0F38.WIG', ops: ymm_ymmm, ext: ext_avx2}, ], packsswb: [{o: 0x63}, {pfx: [0x0F], ops: [mm, [mm, m]], ext: ext_mmx}, {pfx: [0x66, 0x0F], ops: xmm_xmmm, ext: ext_sse2}, ], vpacksswb: [{o: 0x63}, {vex: 'NDS.128.66.0F.WIG', ops: xmm_xmm_xmmm, ext: ext_avx}, {vex: 'NDS.256.66.0F.WIG', ops: ymm_ymm_ymmm, ext: ext_avx2}, ], packssdw: [{o: 0x6B, en: rvm}, {pfx: [0x0F], ops: [mm, [mm, m]], ext: ext_mmx}, {pfx: [0x66, 0x0F], ops: xmm_xmmm, ext: ext_sse2}, ], vpackssdw: [{o: 0x6B, en: rvm}, {vex: 'NDS.128.66.0F.WIG', ops: xmm_xmm_xmmm, ext: ext_avx}, {vex: 'NDS.256.66.0F.WIG', ops: ymm_ymm_ymmm, ext: ext_avx2}, ], packusdw: [{o: 0x2B, pfx: [0x66, 0x0F, 0x38], ops: xmm_xmmm, ext: [EXT.SSE4_1]}], vpackusdw: [{o: 0x2B, en: rvm}, {vex: 'NDS.128.66.0F38.WIG', ops: xmm_xmm_xmmm, ext: ext_avx}, {vex: 'NDS.256.66.0F38.WIG', ops: ymm_ymm_ymmm, ext: ext_avx2}, ], pause: [{o: 0xF390}], // ## Data Transfer // MOV Move data between general-purpose registers mov:[{}, // 88 /r MOV r/m8,r8 MR Valid Valid Move r8 to r/m8. // REX + 88 /r MOV r/m8***,r8*** MR Valid N.E. Move r8 to r/m8. {o: 0x88, ops: [rm8, r8], en: 'mr', dbit: true}, // 8A /r MOV r8,r/m8 RM Valid Valid Move r/m8 to r8. // REX + 8A /r MOV r8***,r/m8*** RM Valid N.E. Move r/m8 to r8. {o: 0x8A, ops: [r8, rm8], dbit: true}, // 89 /r MOV r/m16,r16 MR Valid Valid Move r16 to r/m16. {o: 0x89, ops: [rm16, r16], en: 'mr', dbit: true}, // 8B /r MOV r16,r/m16 RM Valid Valid Move r/m16 to r16. {o: 0x8B, ops: [r16, rm16], dbit: true}, // 89 /r MOV r/m32,r32 MR Valid Valid Move r32 to r/m32. {o: 0x89, ops: [rm32, r32], en: 'mr', dbit: true}, // 8B /r MOV r32,r/m32 RM Valid Valid Move r/m32 to r32. {o: 0x8B, ops: [r32, rm32], dbit: true}, // REX.W + 89 /r MOV r/m64,r64 MR Valid N.E. Move r64 to r/m64. {o: 0x89, ops: [rm64, r64], en: 'mr', dbit: true}, // REX.W + 8B /r MOV r64,r/m64 RM Valid N.E. Move r/m64 to r64. {o: 0x8B, ops: [r64, rm64], dbit: true}, // 8C /r MOV r/m16,Sreg** MR Valid Valid Move segment register to r/m16. {o: 0x8C, ops: [rm16, sreg], s: S.W}, // 8E /r MOV Sreg,r/m16** RM Valid Valid Move r/m16 to segment register. {o: 0x8E, ops: [sreg, rm16], s: S.W}, // REX.W + 8C /r MOV r/m64,Sreg** MR Valid Valid Move zero extended 16-bit segment register to r/m64. {o: 0x8C, ops: [rm64, sreg], s: S.W}, // REX.W + 8E /r MOV Sreg,r/m64** RM Valid Valid Move lower 16 bits of r/m64 to segment register. {o: 0x8E, ops: [sreg, rm64], s: S.W}, // B0+ rb ib MOV r8, imm8 OI Valid Valid Move imm8 to r8. // REX + B0+ rb ib MOV r8***, imm8 OI Valid N.E. Move imm8 to r8. {o: 0xB0, r: true, ops: [r8, imm8]}, // B8+ rw iw MOV r16, imm16 OI Valid Valid Move imm16 to r16. {o: 0xB8, r: true, ops: [r16, imm16]}, // B8+ rd id MOV r32, imm32 OI Valid Valid Move imm32 to r32. {o: 0xB8, r: true, ops: [r32, imm32]}, // REX.W + B8+ rd io MOV r64, imm64 OI Valid N.E. Move imm64 to r64. {o: 0xB8, r: true, ops: [r64, imm64]}, // C6 /0 ib MOV r/m8, imm8 MI Valid Valid Move imm8 to r/m8. // REX + C6 /0 ib MOV r/m8***, imm8 MI Valid N.E. Move imm8 to r/m8. {o: 0xC6, or: 0, ops: [rm8, imm8]}, // C7 /0 iw MOV r/m16, imm16 MI Valid Valid Move imm16 to r/m16. {o: 0xC7, or: 0, ops: [rm16, imm16]}, // C7 /0 id MOV r/m32, imm32 MI Valid Valid Move imm32 to r/m32. {o: 0xC7, or: 0, ops: [rm32, imm32]}, // REX.W + C7 /0 io MOV r/m64, imm32 MI Valid N.E. Move imm32 sign extended to 64-bits to r/m64. {o: 0xC7, or: 0, ops: [rm64, imm32]}, // MOV—Move to/from Control Registers {o: 0x0F20, ops: [r32, cr0_7], dbit: true, s: S.D, mod: M.COMP | M.LEG}, {o: 0x0F20, ops: [r64, cr0_7], dbit: true, s: S.Q, mod: M.X64}, {o: 0x0F20, or: 0, ops: [r64, o.cr(8)], s: S.Q, mod: M.X64}, {o: 0x0F22, ops: [cr0_7, r32], dbit: true, s: S.D, mod: M.COMP | M.LEG}, {o: 0x0F22, ops: [cr0_7, r64], dbit: true, s: S.Q, mod: M.X64}, {o: 0x0F22, or: 0, ops: [o.cr(8), r64], s: S.Q, mod: M.X64}, // MOV—Move to/from Debug Registers {o: 0x0F21, ops: [r32, dr0_7], dbit: true, s: S.D, mod: M.COMP | M.LEG}, {o: 0x0F23, ops: [dr0_7, r32], dbit: true, s: S.D, mod: M.COMP | M.LEG}, {o: 0x0F21, ops: [r64, dr0_7], dbit: true, s: S.Q, mod: M.X64}, {o: 0x0F23, ops: [dr0_7, r64], dbit: true, s: S.Q, mod: M.X64}, ], movabs: [{}, // A0 MOV AL,moffs8* FD Valid Valid Move byte at (seg:offset) to AL. // REX.W + A0 MOV AL,moffs8* FD Valid N.E. Move byte at (offset) to AL. {o: 0xA0, ops: [o.al, imm8]}, // A1 MOV AX,moffs16* FD Valid Valid Move word at (seg:offset) to AX. {o: 0xA1, ops: [o.ax, imm16]}, // A1 MOV EAX,moffs32* FD Valid Valid Move doubleword at (seg:offset) to EAX. {o: 0xA1, ops: [o.eax, imm32]}, // REX.W + A1 MOV RAX,moffs64* FD Valid N.E. Move quadword at (offset) to RAX. {o: 0xA1, ops: [o.rax, imm64]}, // A2 MOV moffs8,AL TD Valid Valid Move AL to (seg:offset). // REX.W + A2 MOV moffs8***,AL TD Valid N.E. Move AL to (offset). {o: 0xA2, ops: [imm8, o.al]}, // A3 MOV moffs16*,AX TD Valid Valid Move AX to (seg:offset). {o: 0xA3, ops: [imm16, o.ax]}, // A3 MOV moffs32*,EAX TD Valid Valid Move EAX to (seg:offset). {o: 0xA3, ops: [imm32, o.eax]}, // REX.W + A3 MOV moffs64*,RAX TD Valid N.E. Move RAX to (offset). {o: 0xA3, ops: [imm64, o.rax]}, ], // CMOVE/CMOVZ Conditional move if equal/Conditional move if zero cmove: tpl_cmovc(0x0F44), cmovz: ['cmove'], // CMOVNE/CMOVNZ Conditional move if not equal/Conditional move if not zero cmovne: tpl_cmovc(0x0F45), cmovnz: ['cmovne'], // CMOVA/CMOVNBE Conditional move if above/Conditional move if not below or equal cmova: tpl_cmovc(0x0F47), cmovnbe: ['cmova'], // CMOVAE/CMOVNB Conditional move if above or equal/Conditional move if not below cmovae: tpl_cmovc(0x0F43), cmovnb: ['cmovae'], // CMOVB/CMOVNAE Conditional move if below/Conditional move if not above or equal cmovb: tpl_cmovc(0x0F42), cmovnae: ['cmovb'], // CMOVBE/CMOVNA Conditional move if below or equal/Conditional move if not above cmovbe: tpl_cmovc(0x0F46), cmovna: ['cmovbe'], // CMOVG/CMOVNLE Conditional move if greater/Conditional move if not less or equal cmovg: tpl_cmovc(0x0F4F), cmovnle: ['cmovg'], // CMOVGE/CMOVNL Conditional move if greater or equal/Conditional move if not less cmovge: tpl_cmovc(0x0F4D), cmovnl: ['cmovge'], // CMOVL/CMOVNGE Conditional move if less/Conditional move if not greater or equal cmovl: tpl_cmovc(0x0F4C), cmovnge: ['cmovl'], // CMOVLE/CMOVNG Conditional move if less or equal/Conditional move if not greater cmovle: tpl_cmovc(0x0F4E), cmovng: ['cmovle'], // CMOVC Conditional move if carry cmovc: tpl_cmovc(), // CMOVNC Conditional move if not carry cmovnc: tpl_cmovc(0x0F43), // CMOVO Conditional move if overflow cmovo: tpl_cmovc(0x0F40), // CMOVNO Conditional move if not overflow cmovno: tpl_cmovc(0x0F41), // CMOVS Conditional move if sign (negative) cmovs: tpl_cmovc(0x0F48), // CMOVNS Conditional move if not sign (non-negative) cmovns: tpl_cmovc(0x0F4B), // CMOVP/CMOVPE Conditional move if parity/Conditional move if parity even cmovp: tpl_cmovc(0x0F4A), cmovpe: ['cmovp'], // CMOVNP/CMOVPO Conditional move if not parity/Conditional move if parity odd cmovnp: tpl_cmovc(0x0F4B), cmovpo: ['cmovnp'], // XCHG Exchange xchg: [{}, // 90+rw XCHG AX, r16 O Valid Valid Exchange r16 with AX. {o: 0x90, r: true, ops: [o.ax, r16]}, // 90+rw XCHG r16, AX O Valid Valid Exchange AX with r16. {o: 0x90, r: true, ops: [r16, o.ax]}, // 90+rd XCHG EAX, r32 O Valid Valid Exchange r32 with EAX. {o: 0x90, r: true, ops: [o.eax, r32]}, // REX.W + 90+rd XCHG RAX, r64 O Valid N.E. Exchange r64 with RAX. {o: 0x90, r: true, ops: [o.rax, r64]}, // 90+rd XCHG r32, EAX O Valid Valid Exchange EAX with r32. {o: 0x90, r: true, ops: [r32, o.eax]}, // REX.W + 90+rd XCHG r64, RAX O Valid N.E. Exchange RAX with r64. {o: 0x90, r: true, ops: [r64, o.rax]}, // 86 /r XCHG r/m8, r8 MR Valid Valid Exchange r8 (byte register) with byte from r/m8. // REX + 86 /r XCHG r/m8*, r8* MR Valid N.E. Exchange r8 (byte register) with byte from r/m8. // 86 /r XCHG r8, r/m8 RM Valid Valid Exchange byte from r/m8 with r8 (byte register). // REX + 86 /r XCHG r8*, r/m8* RM Valid N.E. Exchange byte from r/m8 with r8 (byte register). {o: 0x86, ops: [rm8, rm8]}, // 87 /r XCHG r/m16, r16 MR Valid Valid Exchange r16 with word from r/m16. // 87 /r XCHG r16, r/m16 RM Valid Valid Exchange word from r/m16 with r16. {o: 0x87, ops: [rm16, rm16]}, // 87 /r XCHG r/m32, r32 MR Valid Valid Exchange r32 with doubleword from r/m32. // 87 /r XCHG r32, r/m32 RM Valid Valid Exchange doubleword from r/m32 with r32. {o: 0x87, ops: [rm32, rm32]}, // REX.W + 87 /r XCHG r/m64, r64 MR Valid N.E. Exchange r64 with quadword from r/m64. // REX.W + 87 /r XCHG r64, r/m64 RM Valid N.E. Exchange quadword from r/m64 with r64. {o: 0x87, ops: [rm64, rm64]}, ], // BSWAP Byte swap bswap: [{o: 0x0FC8, r: true}, // 0F C8+rd BSWAP r32 O Valid* Valid Reverses the byte order of a 32-bit register. {ops: [r32]}, // REX.W + 0F C8+rd BSWAP r64 O Valid N.E. Reverses the byte order of a 64-bit register. {ops: [r64]}, ], // XADD Exchange and add xadd: tpl_xadd(0x0FC0), // CMPXCHG Compare and exchange cmpxchg: tpl_xadd(0x0FB0), // CMPXCHG8B Compare and exchange 8 bytes cmpxchg8b: [{o: 0x0FC7, or: 1, ops: [m], s: S.Q}], cmpxchg16b: [{o: 0x0FC7, or: 1, ops: [m], s: S.O}], // PUSH Push onto stack push: [{ds: S.Q}, // FF /6 PUSH r/m16 M Valid Valid Push r/m16. {o: 0xFF, or: 6, ops: [rm16]}, // FF /6 PUSH r/m64 M Valid N.E. Push r/m64. {o: 0xFF, or: 6, ops: [rm64]}, // 50+rw PUSH r16 O Valid Valid Push r16. {o: 0x50, r: true, ops: [r16]}, // 50+rd PUSH r64 O Valid N.E. Push r64. {o: 0x50, r: true, ops: [r64]}, // 6A ib PUSH imm8 I Valid Valid Push imm8. {o: 0x6A, ops: [imm8]}, // 68 iw PUSH imm16 I Valid Valid Push imm16. {o: 0x68, ops: [imm16]}, // 68 id PUSH imm32 I Valid Valid Push imm32. {o: 0x68, ops: [imm32]}, // 0F A0 PUSH FS NP Valid Valid Push FS. {o: 0x0FA0, ops: [o.fs]}, // 0F A8 PUSH GS NP Valid Valid Push GS. {o: 0x0FA8, ops: [o.gs]}, ], // POP Pop off of stack pop: [{ds: S.Q}, // 8F /0 POP r/m16 M Valid Valid {o: 0x8F, or: 0, ops: [rm16]}, // 8F /0 POP r/m64 M Valid N.E. {o: 0x8F, or: 0, ops: [rm64]}, // 58+ rw POP r16 O Valid Valid {o: 0x58, r: true, ops: [r16]}, // 58+ rd POP r64 O Valid N.E. {o: 0x58, r: true, ops: [r64]}, // 0F A1 POP FS NP Valid Valid 16-bits {o: 0x0FA1, ops: [o.fs], s: S.W}, // 0F A1 POP FS NP Valid N.E. 64-bits {o: 0x0FA1, ops: [o.fs], s: S.Q}, // 0F A9 POP GS NP Valid Valid 16-bits {o: 0x0FA9, ops: [o.gs], s: S.W}, // 0F A9 POP GS NP Valid N.E. 64-bits {o: 0x0FA9, ops: [o.gs], s: S.W}, ], // CWD/CDQ/CQO Convert word to doubleword/Convert doubleword to quadword // 99 CWD NP Valid Valid DX:AX ← sign-extend of AX. cwd: [{o: 0x99, s: S.W}], // 99 CDQ NP Valid Valid EDX:EAX ← sign-extend of EAX. cdq: [{o: 0x99, s: S.D}], // REX.W + 99 CQO NP Valid N.E. RDX:RAX← sign-extend of RAX. cqo: [{o: 0x99, s: S.Q}], // CBW/CWDE/CDQE Convert byte to word/Convert word to doubleword in EAX register // 98 CBW NP Valid Valid AX ← sign-extend of AL. cbw: [{o: 0x98, s: S.W}], // 98 CWDE NP Valid Valid EAX ← sign-extend of AX. cwde: [{o: 0x98, s: S.D}], // REX.W + 98 CDQE NP Valid N.E. RAX ← sign-extend of EAX. cdqe: [{o: 0x98, s: S.Q}], // MOVSX Move and sign extend movsx: [{}, // 0F BE /r MOVSX r16, r/m8 RM Valid Valid Move byte to word with sign-extension. {o: 0x0FBE, ops: [r16, rm8], s: S.W}, // 0F BE /r MOVSX r32, r/m8 RM Valid Valid Move byte to doubleword with signextension. {o: 0x0FBE, ops: [r32, rm8], s: S.D}, // REX + 0F BE /r MOVSX r64, r/m8* RM Valid N.E. Move byte to quadword with sign-extension. {o: 0x0FBE, ops: [r64, rm8], s: S.Q}, // 0F BF /r MOVSX r32, r/m16 RM Valid Valid Move word to doubleword, with signextension. {o: 0x0FBF, ops: [r32, rm16], s: S.D}, // REX.W + 0F BF /r MOVSX r64, r/m16 RM Valid N.E. Move word to quadword with sign-extension. {o: 0x0FBF, ops: [r64, rm16], s: S.Q}, ], // REX.W** + 63 /r MOVSXD r64, r/m32 RM Valid N.E. Move doubleword to quadword with signextension. movsxd: [{o: 0x63, ops: [r64, rm32], s: S.Q}], // MOVZX Move and zero extend movzx: [{}, // 0F B6 /r MOVZX r16, r/m8 RM Valid Valid Move byte to word with zero-extension. {o: 0x0FB6, ops: [r16, rm8], s: S.W}, // 0F B6 /r MOVZX r32, r/m8 RM Valid Valid Move byte to doubleword, zero-extension. {o: 0x0FB6, ops: [r32, rm8], s: S.D}, // REX.W + 0F B6 /r MOVZX r64, r/m8* RM Valid N.E. Move byte to quadword, zero-extension. {o: 0x0FB6, ops: [r64, rm8], s: S.Q}, // 0F B7 /r MOVZX r32, r/m16 RM Valid Valid Move word to doubleword, zero-extension. {o: 0x0FB7, ops: [r32, rm16], s: S.D}, // REX.W + 0F B7 /r MOVZX r64, r/m16 RM Valid N.E. Move word to quadword, zero-extension. {o: 0x0FB7, ops: [r64, rm16], s: S.Q}, ], // ## Binary Arithmetic // ADCX Unsigned integer add with carry adcx: [{o: 0x0F38F6, pfx: [0x66], ext: [EXT.ADX]}, {ops: [r32, rm32]}, {ops: [r64, rm64], mod: M.X64}, ], // ADOX Unsigned integer add with overflow adox: [{o: 0x0F38F6, pfx: [0xF3], ext: [EXT.ADX]}, {ops: [r32, rm32]}, {ops: [r64, rm64], mod: M.X64}, ], // ADD Integer add get add() {return lazy('common', 'add')}, // ADC Add with carry get adc() {return lazy('common', 'adc')}, // SUB Subtract get sub() {return lazy('common', 'sub')}, // SBB Subtract with borrow get sbb() {return lazy('common', 'sbb')}, // IMUL Signed multiply imul: [{}, // F6 /5 IMUL r/m8* M Valid Valid AX← AL ∗ r/m byte. {o: 0xF6, or: 5, ops: [rm8]}, // F7 /5 IMUL r/m16 M Valid Valid DX:AX ← AX ∗ r/m word. {o: 0xF7, or: 5, ops: [rm16]}, // F7 /5 IMUL r/m32 M Valid Valid EDX:EAX ← EAX ∗ r/m32. {o: 0xF7, or: 5, ops: [rm32]}, // REX.W + F7 /5 IMUL r/m64 M Valid N.E. RDX:RAX ← RAX ∗ r/m64. {o: 0xF7, or: 5, ops: [rm64]}, // 0F AF /r IMUL r16, r/m16 RM Valid Valid word register ← word register ∗ r/m16. {o: 0x0FAF, ops: [r16, rm16]}, // 0F AF /r IMUL r32, r/m32 RM Valid Valid doubleword register ← doubleword register ∗ r/m32. {o: 0x0FAF, ops: [r32, rm32]}, // REX.W + 0F AF /r IMUL r64, r/m64 RM Valid N.E. Quadword register ← Quadword register ∗ r/m64. {o: 0x0FAF, ops: [r64, rm64]}, // 6B /r ib IMUL r16, r/m16, imm8 RMI Valid Valid word register ← r/m16 ∗ sign-extended immediate byte. {o: 0x6B, ops: [r16, rm16, imm8]}, // 6B /r ib IMUL r32, r/m32, imm8 RMI Valid Valid doubleword register ← r/m32 ∗ signextended immediate byte. {o: 0x6B, ops: [r32, rm32, imm8]}, // REX.W + 6B /r ib IMUL r64, r/m64, imm8 RMI Valid N.E. Quadword register ← r/m64 ∗ sign-extended immediate byte. {o: 0x6B, ops: [r64, rm64, imm8]}, // 69 /r iw IMUL r16, r/m16, imm16 RMI Valid Valid word register ← r/m16 ∗ immediate word. {o: 0x69, ops: [r16, rm16, imm16]}, // 69 /r id IMUL r32, r/m32, imm32 RMI Valid Valid doubleword register ← r/m32 ∗ immediate doubleword. {o: 0x69, ops: [r32, rm32, imm32]}, // REX.W + 69 /r id IMUL r64, r/m64, imm32 RMI Valid N.E. Quadword register {o: 0x69, ops: [r64, rm64, imm32]}, ], // MUL Unsigned multiply mul: tpl_not(0xF6, 4, false), // IDIV Signed divide idiv: tpl_not(0xF6, 7, false), // DIV Unsigned divide div: tpl_not(0xF6, 6, false), // INC Increment inc: _inc, // DEC Decrement dec: _dec, // NEG Negate neg: tpl_not(0xF6, 3), // CMP Compare get cmp() {return lazy('common', 'cmp')}, // ## Logical // AND Perform bitwise logical AND get and() {return lazy('common', 'and')}, // OR Perform bitwise logical OR get or() {return lazy('common', 'or')}, // XOR Perform bitwise logical exclusive OR get xor() {return lazy('common', 'xor')}, // NOT Perform bitwise logical NOT not: tpl_not(), // ## Shift and Rotate // SAR Shift arithmetic right get sar() {return lazy('sar', 'sar')}, // SHR Shift logical right get shr() {return lazy('sar', 'shr')}, // SAL/SHL Shift arithmetic left/Shift logical left get shl() {return lazy('sar', 'shl')}, sal: ['shl'], // SHRD Shift right double get shrd() {return lazy('shrd', 'shrd')}, // SHLD Shift left double get shld() {return lazy('shrd', 'shld')}, // ROR Rotate right get ror() {return lazy('sar', 'ror')}, // ROL Rotate left get rol() {return lazy('sar', 'rol')}, // RCR Rotate through carry right get rcr() {return lazy('sar', 'rcr')}, // RCL Rotate through carry left get rcl() {return lazy('sar', 'rcl')}, // ## Bit and Byte // BT Bit test bt: tpl_bt(), // BTS Bit test and set bts: tpl_bt(0x0FAB, 4), // BTR Bit test and reset btr: tpl_bt(0x0FB3, 6), // BTC Bit test and complement btc: tpl_bt(0x0FBB, 7), // BSF Bit scan forward bsf: tpl_bsf(), // BSR Bit scan reverse bsr: tpl_bsf(0x0FBD), // SETE/SETZ Set byte if equal/Set byte if zero sete: [{o: 0x0F94, ops: [rm8]}], setz: ['sete'], // SETNE/SETNZ Set byte if not equal/Set byte if not zero setne: [{o: 0x0F95, ops: [rm8]}], setnz: ['setne'], // SETA/SETNBE Set byte if above/Set byte if not below or equal seta: [{o: 0x0F97, ops: [rm8]}], setnbe: ['seta'], // SETAE/SETNB/SETNC Set byte if above or equal/Set byte if not below/Set byte if not carry setae: [{o: 0x0F93, ops: [rm8]}], setnb: ['setae'], setnc: ['setae'], // SETB/SETNAE/SETCSet byte if below/Set byte if not above or equal/Set byte if carry setb: [{o: 0x0F92, ops: [rm8]}], setnae: ['setb'], setc: ['setb'], // SETBE/SETNA Set byte if below or equal/Set byte if not above setbe: [{o: 0x0F96, ops: [rm8]}], setna: ['setbe'], // SETG/SETNLE Set byte if greater/Set byte if not less or equal setg: [{o: 0x0F9F, ops: [rm8]}], setnle: ['setg'], // SETGE/SETNL Set byte if greater or equal/Set byte if not less setge: [{o: 0x0F9D, ops: [rm8]}], setnl: ['setge'], // SETL/SETNGE Set byte if less/Set byte if not greater or equal setl: [{o: 0x0F9C, ops: [rm8]}], setnge: ['setl'], // SETLE/SETNG Set byte if less or equal/Set byte if not greater setle: [{o: 0x0F9E, ops: [rm8]}], setng: ['setle'], // SETS Set byte if sign (negative) sets: [{o: 0x0F98, ops: [rm8]}], // SETNS Set byte if not sign (non-negative) setns: [{o: 0x0F99, ops: [rm8]}], // SETO Set byte if overflow seto: [{o: 0x0F90, ops: [rm8]}], // SETNO Set byte if not overflow setno: [{o: 0x0F91, ops: [rm8]}], // SETPE/SETP Set byte if parity even/Set byte if parity setp: [{o: 0x0F9A, ops: [rm8]}], setpe: ['setp'], // SETPO/SETNP Set byte if parity odd/Set byte if not parity setnp: [{o: 0x0F9B, ops: [rm8]}], setpo: ['setnp'], // TEST Logical compare test: [{}, // A8 ib TEST AL, imm8 I Valid Valid AND imm8 with AL; set SF, ZF, PF according to result. {o: 0xA8, ops: [o.al, imm8]}, // A9 iw TEST AX, imm16 I Valid Valid AND imm16 with AX; set SF, ZF, PF according to result. {o: 0xA9, ops: [o.ax, imm16]}, // A9 id TEST EAX, imm32 I Valid Valid AND imm32 with EAX; set SF, ZF, PF according to result. {o: 0xA9, ops: [o.eax, imm32]}, // REX.W + A9 id TEST RAX, imm32 I Valid N.E. AND imm32 sign-extended to 64-bits with RAX; set SF, ZF, PF according to result. {o: 0xA9, ops: [o.rax, imm32]}, // F6 /0 ib TEST r/m8, imm8 MI Valid Valid AND imm8 with r/m8; set SF, ZF, PF according to result. // REX + F6 /0 ib TEST r/m8*, imm8 MI Valid N.E. AND imm8 with r/m8; set SF, ZF, PF according to result. {o: 0xF6, or: 0, ops: [rm8, imm8]}, // F7 /0 iw TEST r/m16, imm16 MI Valid Valid AND imm16 with r/m16; set SF, ZF, PF according to result. {o: 0xF7, or: 0, ops: [rm16, imm16]}, // F7 /0 id TEST r/m32, imm32 MI Valid Valid AND imm32 with r/m32; set SF, ZF, PF according to result. {o: 0xF7, or: 0, ops: [rm32, imm32]}, // REX.W + F7 /0 id TEST r/m64, imm32 MI Valid N.E. AND imm32 sign-extended to 64-bits with r/m64; set SF, ZF, PF according to result. {o: 0xF7, or: 0, ops: [rm64, imm32]}, // 84 /r TEST r/m8, r8 MR Valid Valid AND r8 with r/m8; set SF, ZF, PF according to result. // REX + 84 /r TEST r/m8*, r8* MR Valid N.E. AND r8 with r/m8; set SF, ZF, PF according to result. {o: 0x84, ops: [rm8, r8]}, // 85 /r TEST r/m16, r16 MR Valid Valid AND r16 with r/m16; set SF, ZF, PF according to result. {o: 0x85, ops: [rm16, r16]}, // 85 /r TEST r/m32, r32 MR Valid Valid AND r32 with r/m32; set SF, ZF, PF according to result. {o: 0x85, ops: [rm32, r32]}, // REX.W + 85 /r TEST r/m64, r64 MR Valid N.E. AND r64 with {o: 0x85, ops: [rm64, r64]}, ], // CRC32 Provides hardware acceleration to calculate cyclic redundancy checks for fast and efficient implementation of data integrity protocols. crc32: [{pfx: [0xF2]}, // F2 0F 38 F0 /r CRC32 r32, r/m8 RM Valid Valid Accumulate CRC32 on r/m8. // F2 REX 0F 38 F0 /r CRC32 r32, r/m8* RM Valid N.E. Accumulate CRC32 on r/m8. {o: 0x0F38F0, ops: [r32, rm8], s: S.D}, // F2 0F 38 F1 /r CRC32 r32, r/m16 RM Valid Valid Accumulate CRC32 on r/m16. {o: 0x0F38F1, ops: [r32, rm16], s: S.D}, // F2 0F 38 F1 /r CRC32 r32, r/m32 RM Valid Valid Accumulate CRC32 on r/m32. {o: 0x0F38F1, ops: [r32, rm32], s: S.D}, // F2 REX.W 0F 38 F0 /r CRC32 r64, r/m8 RM Valid N.E. Accumulate CRC32 on r/m8. {o: 0x0F38F0, ops: [r64, rm8], s: S.Q}, // F2 REX.W 0F 38 F1 /r CRC32 r64, r/m64 {o: 0x0F38F1, ops: [r64, rm64]}, ], // POPCNT This instruction calculates of number of bits set to 1 in the second popcnt: [{pfx: [0xF3]}, // F3 0F B8 /r POPCNT r16, r/m16 RM Valid Valid POPCNT on r/m16 {o: 0x0FB8, ops: [r16, rm16], s: S.W}, // F3 0F B8 /r POPCNT r32, r/m32 RM Valid Valid POPCNT on r/m32 {o: 0x0FB8, ops: [r32, rm32], s: S.D}, // F3 REX.W 0F B8 /r POPCNT r64, r/m64 RM Valid N.E. POPCNT on r/m64 {o: 0x0FB8, ops: [r64, rm64], s: S.Q}, ], // ## Control Transfer // JMP Jump jmp: [{ds: S.Q}, // relX is just immX // EB cb JMP rel8 D Valid Valid Jump short, RIP = RIP + 8-bit displacement sign extended to 64-bits {o: 0xEB, ops: [rel8]}, // E9 cd JMP rel32 D Valid Valid Jump near, relative, RIP = RIP + 32-bit displacement sign extended to 64-bits {o: 0xE9, ops: [rel32]}, // FF /4 JMP r/m64 M Valid N.E. Jump near, absolute indirect, RIP = 64-Bit offset from register or memory {o: 0xFF, or: 4, ops: [rm64]}, ], ljmp: [{ds: S.Q}, // FF /5 JMP m16:16 D Valid Valid Jump far, absolute indirect, address given in m16:16 // FF /5 JMP m16:32 D Valid Valid Jump far, absolute indirect, address given in m16:32. // REX.W + FF /5 JMP m16:64 D Valid N.E. Jump far, absolute // TODO: Improve this. {o: 0xFF, or: 5, ops: [m], s: S.Q}, ], // Jcc // E3 cb JECXZ rel8 D Valid Valid Jump short if ECX register is 0. jecxz: [{o: 0xE3, ops: [rel8], pfx: [0x67]}], // E3 cb JRCXZ rel8 D Valid N.E. Jump short if RCX register is 0. jrcxz: [{o: 0xE3, ops: [rel8]}], ja: tpl_ja(), jae: tpl_ja(0x73, 0x0F83), jb: tpl_ja(0x72, 0x0F82), jbe: tpl_ja(0x76, 0x0F86), jc: tpl_ja(0x72, 0x0F82), je: tpl_ja(0x74, 0x0F84), jg: tpl_ja(0x7F, 0x0F8F), jge: tpl_ja(0x7D, 0x0F8D), jl: tpl_ja(0x7C, 0x0F8C), jle: tpl_ja(0x7E, 0x0F8E), jna: tpl_ja(0x76, 0x0F86), jnae: tpl_ja(0x72, 0x0F82), jnb: tpl_ja(0x73, 0x0F83), jnbe: tpl_ja(0x77, 0x0F87), jnc: tpl_ja(0x73, 0x0F83), jne: tpl_ja(0x75, 0x0F85), jng: tpl_ja(0x7E, 0x0F8E), jnge: tpl_ja(0x7C, 0x0F8C), jnl: tpl_ja(0x7D, 0x0F8D), jnle: tpl_ja(0x7F, 0x0F8F), jno: tpl_ja(0x71, 0x0F81), jnp: tpl_ja(0x7B, 0x0F8B), jns: tpl_ja(0x79, 0x0F89), jnz: tpl_ja(0x75, 0x0F85), jo: tpl_ja(0x70, 0x0F80), jp: tpl_ja(0x7A, 0x0F8A), jpe: tpl_ja(0x7A, 0x0F8A), jpo: tpl_ja(0x7B, 0x0F8B), js: tpl_ja(0x78, 0x0F88), jz: tpl_ja(0x74, 0x0F84), // LOOP Loop with ECX counter // E2 cb LOOP rel8 D Valid Valid Decrement count; jump short if count ≠ 0. loop: [{o: 0xE2, ops: [rel8]}], // LOOPZ/LOOPE Loop with ECX and zero/Loop with ECX and equal // E1 cb LOOPE rel8 D Valid Valid Decrement count; jump short if count ≠ 0 and ZF = 1. loope: [{o: 0xE1, ops: [rel8]}], loopz: ['loope'], // LOOPNZ/LOOPNE Loop with ECX and not zero/Loop with ECX and not equal // E0 cb LOOPNE rel8 D Valid Valid Decrement count; jump short if count ≠ 0 and ZF = 0. loopne: [{o: 0xE0, ops: [rel8]}], loopnz: ['loopne'], // CALL Call procedure call: [{ds: S.Q}, {o: 0xE8, ops: [rel16], mod: M.OLD}, {o: 0xE8, ops: [rel32]}, {o: 0xFF, or: 2, ops: [rm16], mod: M.OLD}, {o: 0xFF, or: 2, ops: [rm32], mod: M.OLD}, {o: 0xFF, or: 2, ops: [rm64]}, ], lcall: [{ds: S.Q}, // FF /3 CALL m16:16 M Valid Valid Call far, absolute indirect address given in m16:16. // FF /3 CALL m16:32 M Valid Valid // REX.W + FF /3 CALL m16:64 M Valid N.E. // TODO: Test this. // {o: 0xFF, or: 3, ops: [m], s: S.Q}, {o: 0xFF, or: 3, ops: [m], s: S.D}, ], // RET Return ret: [{ds: S.Q}, {o: 0xC3}, {o: 0xC2, ops: [imm16]} ], lret: [{ds: S.Q}, {o: 0xCB}, {o: 0xCA, ops: [imm16]} ], // IRET Return from interrupt iret: [{o: 0xCF}], iretd: [{o: 0xCF}], iretq: [{o: 0xCF, rex: [1, 0, 0, 0]}], // ## String // MOVS Move string/Move byte string movs: tpl_movs(), // CMPS Compare string/Compare byte string cmps: tpl_movs(0xA6), // SCAS Scan string/Scan byte string scas: tpl_movs(0xAE), // LODS/LODSB Load string/Load byte string lods: tpl_movs(0xAC), lodsb: [{o: 0xAC, s: S.B}], lodsw: [{o: 0xAD, s: S.W}], lodsd: [{o: 0xAD, s: S.D}], lodsq: [{o: 0xAD, s: S.Q}], // STOS Store string/Store byte string stos: tpl_movs(0xAA), // ## I/O // IN Read from a port 'in': [{mr: false}, // E4 ib IN AL, imm8 I Valid Valid Input byte from imm8 I/O port address into AL. {o: 0xE4, ops: [o.al, imm8]}, // E5 ib IN AX, imm8 I Valid Valid Input word from imm8 I/O port address into AX. {o: 0xE5, ops: [o.ax, imm8]}, // E5 ib IN EAX, imm8 I Valid Valid Input dword from imm8 I/O port address into EAX. {o: 0xE5, ops: [o.eax, imm8]}, // EC IN AL,DX NP Valid Valid Input byte from I/O port in DX into AL. {o: 0xEC, ops: [o.al, o.dx], s: S.B}, // ED IN AX,DX NP Valid Valid Input word from I/O port in DX into AX. {o: 0xED, ops: [o.ax, o.dx], s: S.W}, // ED IN EAX,DX NP Valid Valid Input doubleword {o: 0xED, ops: [o.eax, o.dx], s: S.D}, ], // OUT Write to a port out: [{mr: false}, // E6 ib OUT imm8, AL I Valid Valid Output byte in AL to I/O port address imm8. {o: 0xE6, ops: [imm8, o.al]}, // E7 ib OUT imm8, AX I Valid Valid Output word in AX to I/O port address imm8. {o: 0xE7, ops: [imm8, o.ax]}, // E7 ib OUT imm8, EAX I Valid Valid Output doubleword in EAX to I/O port address imm8. {o: 0xE7, ops: [imm8, o.eax]}, // EE OUT DX, AL NP Valid Valid Output byte in AL to I/O port address in DX. {o: 0xEE, ops: [o.dx, o.al], s: S.B}, // EF OUT DX, AX NP Valid Valid Output word in AX to I/O port address in DX. {o: 0xEF, ops: [o.dx, o.ax], s: S.W}, // EF OUT DX, EAX NP Valid Valid Output {o: 0xEF, ops: [o.dx, o.eax], s: S.D}, ], // INS ins: [{o: 0x6D}, // INS/INSB Input string from port/Input byte string from port {o: 0x6C, s: S.B}, // INS/INSW Input string from port/Input word string from port {s: S.W}, // INS/INSD Input string from port/Input doubleword string from port {s: S.D}, ], insb: [{o: 0x6C}], insw: [{o: 0x6D}], insd: [{o: 0x6D}], // OUTS outs: [{o: 0x6F}, // OUTS/OUTSB Output string to port/Output byte string to port {o: 0x6E, s: S.B}, // OUTS/OUTSW Output string to port/Output word string to port {s: S.W}, // OUTS/OUTSD Output string to port/Output doubleword string to port {s: S.D}, ], // ## Enter and Leave // ENTER High-level procedure entry enter: [{o: 0xC8, ops: [imm16, imm8]}, // C8 iw 00 ENTER imm16, 0 II Valid Valid Create a stack frame for a procedure. // C8 iw 01 ENTER imm16,1 II Valid Valid Create a stack frame with a nested pointer for a procedure. // C8 iw ib ENTER imm16, imm8 II Valid Valid Create a stack frame ], // LEAVE High-level procedure exit leave: [{o: 0xC9}, {s: S.W}, {s: S.D, mod: M.COMP | M.LEG}, {s: S.Q, mod: M.X64}, ], // ## Flag Control // STC Set carry flag stc: [{o: 0xF9}], // CLC Clear the carry flag clc: [{o: 0xF8}], // CMC Complement the carry flag cmc: [{o: 0xF5}], // CLD Clear the direction flag cld: [{o: 0xFC}], // STD Set direction flag std: [{o: 0xFD}], // PUSHF/PUSHFD Push EFLAGS onto stack pushf: [{o: 0x9C}], // POPF/POPFD Pop EFLAGS from stack popf: [{o: 0x9D}], // STI Set interrupt flag sti: [{o: 0xFB}], // CLI Clear the interrupt flag cli: [{o: 0xFA}], clac: [{o: 0x0F01CA}], // ## Segment Register lds: [{o: 0xC5, mod: M.COMP | M.LEG}, {ops: [r16, m]}, {ops: [r32, m]}, ], les: [{o: 0xC4, mod: M.COMP | M.LEG}, {ops: [r16, m]}, {ops: [r32, m]}, ], lfs: tpl_lss(0x0FB4), // LGS Load far pointer using GS lgs: tpl_lss(0x0FB5), // LSS Load far pointer using SS lss: tpl_lss(), // ## Miscellaneous // LEA Load effective address lea: [{o: 0x8D}, {ops: [r16, m]}, {ops: [r32, m]}, {ops: [r64, m]}, ], // NOP No operation // TODO: Come back, review this. nop: [{}, // 90 NOP NP Valid Valid One byte no-operation instruction. {o: 0x90}, // 0F 1F /0 NOP r/m16 M Valid Valid Multi-byte no-operation instruction. {o: 0x0F1F, or: 0, ops: [rm16]}, // 0F 1F /0 NOP r/m32 M Valid Valid Multi-byte no-operation instruction. {o: 0x0F1F, or: 0, ops: [rm32]}, ], // UD2 Undefined instruction ud2: [{o: 0x0F0B}], // XLAT/XLATB Table lookup translation xlat: [{o: 0xD7}], // TODO: Review this. // CPUID Processor identification cpuid: [{o: 0x0FA2}], // MOVBE Move data after swapping data bytes movbe: [{}, // 0F 38 F0 /r MOVBE r16, m16 RM Valid Valid Reverse byte order in m16 and move to r16. {o: 0x0F38F0, ops: [r16, m16], dbit: true}, // 0F 38 F0 /r MOVBE r32, m32 RM Valid Valid Reverse byte order in m32 and move to r32. {o: 0x0F38F0, ops: [r32, m32], dbit: true}, // REX.W + 0F 38 F0 /r MOVBE r64, m64 RM Valid N.E. Reverse byte order in m64 and move to r64. {o: 0x0F38F0, ops: [r64, m64], dbit: true}, // 0F 38 F1 /r MOVBE m16, r16 MR Valid Valid Reverse byte order in r16 and move to m16. {o: 0x0F38F1, ops: [m16, r16], dbit: true}, // 0F 38 F1 /r MOVBE m32, r32 MR Valid Valid Reverse byte order in r32 and move to m32. {o: 0x0F38F1, ops: [m32, r32], dbit: true}, // REX.W + 0F 38 F1 /r MOVBE m64, r64 MR Valid N.E. Reverse byte order in r64 and move to m64. {o: 0x0F38F1, ops: [m64, r64], dbit: true}, ], // PREFETCHW Prefetch data into cache in anticipation of write prefetchw: [{o: 0x0F0D, or: 1, ops: [m]}], // PREFETCHWT1 Prefetch hint T1 with intent to write prefetchwt1: [{o: 0x0F0D, or: 2, ops: [m]}], // CLFLUSH Flushes and invalidates a memory operand and its associated cache line from all levels of the processor’s cache hierarchy cflush: [{o: 0x0FAE, or: 7, ops: [m]}], // CLFLUSHOPT Flushes and invalidates a memory operand and its associated cache line from all levels of the processor’s cache hierarchy with optimized memory system throughput. cflushopt: [{o: 0x0FAE, or: 7, pfx: [0x66], ops: [m]}], // ## User Mode Extended Sate Save/Restore // XSAVE Save processor extended states to memory xsave: [{o: 0x0FAE, or: 4, ops: [m]}], // XSAVEC Save processor extended states with compaction to memory xsavec: [{o: 0x0FC7, or: 4, ops: [m]}], // XSAVEOPT Save processor extended states to memory, optimized xsaveopt: [{o: 0x0FAE, or: 6, ops: [m]}], // XRSTOR Restore processor extended states from memory xrstor: [{o: 0x0FAE, or: 5, ops: [m]}], // XGETBV Reads the state of an extended control register xgetbv: [{o: 0x0F01D0}], // ## Random Number // RDRAND Retrieves a random number generated from hardware rdrand: [{o: 0x0FC7, or: 6}, // 0F C7 /6 RDRAND r16 M {ops: [r16]}, // 0F C7 /6 RDRAND r32 M {ops: [r32]}, // REX.W + 0F C7 /6 RDRAND r64 M {ops: [r64]}, ], // RDSEED Retrieves a random number generated from hardware rdseed: [{o: 0x0FC7, or: 7}, {ops: [r16]}, {ops: [r32]}, {ops: [r64]}, ], // ## BMI1, BMI2 // ANDN Bitwise AND of first source with inverted 2nd source operands. // BEXTR Contiguous bitwise extract // BLSI Extract lowest set bit // BLSMSK Set all lower bits below first set bit to 1 // BLSR Reset lowest set bit // BZHI Zero high bits starting from specified bit position // LZCNT Count the number leading zero bits // MULX Unsigned multiply without affecting arithmetic flags // PDEP Parallel deposit of bits using a mask // PEXT Parallel extraction of bits using a mask // RORX Rotate right without affecting arithmetic flags // SARX Shift arithmetic right // SHLX Shift logic left // SHRX Shift logic right // TZCNT Count the number trailing zero bits // System syscall: [{o: 0x0F05}], sysret: [{o: 0x0F07}], sysenter: [{o: 0x0F34}], sysexit: [{o: 0x0F35}], // VEX vextractf128: [{o: 0x19, vex: '256.66.0F3A.W0', ops: [[xmm, m], ymm, imm8], s: S.X}], vcvtph2ps: [{o: 0x13, vex: '256.66.0F38.W0', ops: [ymm, [xmm, m]], s: 256}], vfmadd132pd: [{o: 0x98, vex: 'DDS.128.66.0F38.W1', en: 'rvm', ops: [xmm, xmm, [xmm, m]]}], };
the_stack
import type { ProxyAccessor } from '../Cache'; import type { InnerClientState } from '../Client/client'; import { GQtyError } from '../Error'; import { DeepPartial, parseSchemaType, Schema, SchemaUnionsKey, Type, } from '../Schema'; import { Selection, SelectionType } from '../Selection'; import { decycle, isInteger, isObject, retrocycle, isObjectWithType, } from '../Utils'; const ProxySymbol = Symbol('gqty-proxy'); export class SchemaUnion { constructor( /** union name */ public name: string, public types: Record< /** object type name */ string, /** schema type of object type */ Record<string, Type> >, /** * Proxy target, pre-made for performance */ public fieldsProxy: Record<string, typeof ProxySymbol> ) {} } export type SchemaUnions = { unions: Record<string, SchemaUnion>; unionObjectTypesForSelections: Record<string, [string]>; }; export function createSchemaUnions(schema: Readonly<Schema>): SchemaUnions { const unionObjectTypesForSelections: Record<string, [string]> = {}; const unions = Object.entries( schema[SchemaUnionsKey] /* istanbul ignore next */ || {} ).reduce<SchemaUnions['unions']>((acum, [name, unionTypes]) => { const types = unionTypes.reduce((typeAcum, objectTypeName) => { unionObjectTypesForSelections[objectTypeName] ||= [objectTypeName]; const objectType = schema[objectTypeName]; /* istanbul ignore else */ if (objectType) { typeAcum[objectTypeName] = objectType; } return typeAcum; }, {} as SchemaUnion['types']); acum[name] = new SchemaUnion( name, types, unionTypes.reduce<SchemaUnion['fieldsProxy']>((fieldsAcum, fieldName) => { fieldsAcum[fieldName] = ProxySymbol; return fieldsAcum; }, {}) ); return acum; }, {}); return { unions, unionObjectTypesForSelections, }; } export interface SetCache { (selection: Selection, data: unknown): void; <A extends object>( accessor: A, data: DeepPartial<A> | null | undefined ): void; <B extends (args?: any) => unknown>( accessor: B, args: Parameters<B>['0'], data: DeepPartial<ReturnType<B>> | null | undefined ): void; } export interface AssignSelections { <A extends object, B extends A>( source: A | null | undefined, target: B | null | undefined ): void; } export interface AccessorCreators< GeneratedSchema extends { query: {}; mutation: {}; subscription: {}; } > { createAccessor: ( schemaValue: Schema[string] | SchemaUnion, prevSelection: Selection, unions?: string[] | undefined, parentTypename?: string | undefined ) => ProxyAccessor | null; createArrayAccessor: ( schemaValue: Schema[string] | SchemaUnion, prevSelection: Selection, unions?: string[] | undefined, parentTypename?: string | undefined ) => ProxyAccessor | null; assignSelections: AssignSelections; setCache: SetCache; query: GeneratedSchema['query']; mutation: GeneratedSchema['mutation']; subscription: GeneratedSchema['subscription']; } export function createAccessorCreators< GeneratedSchema extends { query: {}; mutation: {}; subscription: {}; } = never >(innerState: InnerClientState): AccessorCreators<GeneratedSchema> { const { accessorCache, selectionManager, interceptorManager, scalarsEnumsHash, schema, eventHandler, schemaUnions: { unions: schemaUnions, unionObjectTypesForSelections }, clientCache: schedulerClientCache, scheduler: { errors: { map: schedulerErrorsMap }, }, normalizationHandler, depthLimit, } = innerState; const ResolveInfoSymbol = Symbol(); interface ResolveInfo { key: string | number; prevSelection: Selection; argTypes: Record<string, string> | undefined; } const proxySymbolArray = [ProxySymbol]; function extractDataFromProxy(value: unknown): unknown { if (accessorCache.isProxy(value)) { const accessorSelection = accessorCache.getProxySelection(value); // An edge case hard to reproduce /* istanbul ignore if */ if (!accessorSelection) return; const selectionCache = innerState.clientCache.getCacheFromSelection(accessorSelection); if (selectionCache === undefined) return; return selectionCache; } else if (isObject(value)) { /** * This is necessary to be able to extract data from proxies * inside user-made objects and arrays */ return retrocycle<object>(JSON.parse(JSON.stringify(value))); } return value; } function setCache(selection: Selection, data: unknown): void; function setCache<A extends object>( accessor: A, data: DeepPartial<A> | null | undefined ): void; function setCache<B extends (args?: any) => unknown>( accessor: B, args: Parameters<B>['0'], data: DeepPartial<ReturnType<B>> | null | undefined ): void; function setCache( accessorOrSelection: unknown, dataOrArgs: unknown, possibleData?: unknown ) { if (accessorOrSelection instanceof Selection) { const data = extractDataFromProxy(dataOrArgs); innerState.clientCache.setCacheFromSelection(accessorOrSelection, data); eventHandler.sendCacheChange({ data, selection: accessorOrSelection, }); } else if (typeof accessorOrSelection === 'function') { if (dataOrArgs !== undefined && typeof dataOrArgs !== 'object') { throw new GQtyError('Invalid arguments of type: ' + typeof dataOrArgs, { caller: setCache, }); } const resolveInfo = ( accessorOrSelection as Function & { [ResolveInfoSymbol]?: ResolveInfo; } )[ResolveInfoSymbol]; if (!resolveInfo) { throw new GQtyError('Invalid gqty function', { caller: setCache, }); } const selection = innerState.selectionManager.getSelection({ ...resolveInfo, args: dataOrArgs as Record<string, unknown>, }); const data = extractDataFromProxy(possibleData); innerState.clientCache.setCacheFromSelection(selection, data); eventHandler.sendCacheChange({ data, selection, }); } else if (accessorCache.isProxy(accessorOrSelection)) { const selection = accessorCache.getProxySelection(accessorOrSelection); // An edge case hard to reproduce /* istanbul ignore if */ if (!selection) { throw new GQtyError('Invalid proxy selection', { caller: setCache, }); } const data = extractDataFromProxy(dataOrArgs); innerState.clientCache.setCacheFromSelection(selection, data); eventHandler.sendCacheChange({ data, selection, }); } else { throw new GQtyError('Invalid gqty proxy', { caller: setCache, }); } } function createArrayAccessor( schemaValue: Schema[string] | SchemaUnion, prevSelection: Selection, unions?: string[], parentTypename?: string ) { const arrayCacheValue = innerState.clientCache.getCacheFromSelection< undefined | null | unknown[] >(prevSelection); if (innerState.allowCache && arrayCacheValue === null) return null; const proxyValue: unknown[] = arrayCacheValue === undefined || !Array.isArray(arrayCacheValue) || (!innerState.allowCache && Array.isArray(arrayCacheValue) && arrayCacheValue.length === 0) ? proxySymbolArray : arrayCacheValue; const accessor = accessorCache.getArrayAccessor( prevSelection, proxyValue, () => { return new Proxy(proxyValue, { set(_target, key: string, value: unknown) { let index: number | undefined; try { index = parseInt(key); } catch (err) {} if (isInteger(index)) { const selection = innerState.selectionManager.getSelection({ key: index, prevSelection, }); const data = extractDataFromProxy(value); innerState.clientCache.setCacheFromSelection(selection, data); eventHandler.sendCacheChange({ selection, data, }); return true; } if (key === 'length') { if (!Array.isArray(arrayCacheValue)) { console.warn( 'Invalid array assignation to unresolved proxy array' ); return true; } Reflect.set(arrayCacheValue, key, value); eventHandler.sendCacheChange({ selection: prevSelection, data: innerState.clientCache.getCacheFromSelection( prevSelection ), }); return true; } throw TypeError('Invalid array assignation: ' + key); }, get(target, key: string, receiver) { if (key === 'length') { if (proxyValue === proxySymbolArray) { const lengthSelection = innerState.selectionManager.getSelection({ key: 0, prevSelection, }); const childAccessor = createAccessor( schemaValue, lengthSelection, unions, parentTypename ); accessorCache.addAccessorChild(accessor, childAccessor); if (childAccessor) Reflect.get(childAccessor, '__typename'); } return target.length; } else if (key === 'toJSON') { return () => decycle<unknown[]>( innerState.clientCache.getCacheFromSelection( prevSelection, [] ) ); } let index: number | undefined; try { index = parseInt(key); } catch (err) {} if (isInteger(index)) { const selection = innerState.selectionManager.getSelection({ key: index, prevSelection, }); // For the subscribers of data changes interceptorManager.addSelectionCache(selection); if ( innerState.allowCache && arrayCacheValue !== undefined && arrayCacheValue?.[index] == null ) { /** * If cache is enabled and arrayCacheValue[index] is 'null' or 'undefined', return it */ return arrayCacheValue?.[index]; } const childAccessor = createAccessor( schemaValue, selection, unions, parentTypename ); accessorCache.addAccessorChild(accessor, childAccessor); return childAccessor; } return Reflect.get(target, key, receiver); }, }); } ); return accessor; } const notFoundObjectKey = {}; const nullObjectKey = {}; const unionsCacheValueMap = new WeakMap<string[], WeakMap<object, object>>(); function getCacheValueReference( cacheValue: unknown, unions: string[] | undefined ) { if (unions === undefined) return cacheValue; const mapKey: object = cacheValue == null ? nullObjectKey : typeof cacheValue === 'object' ? cacheValue! : notFoundObjectKey; let cacheValueMap = unionsCacheValueMap.get(unions); if (!cacheValueMap) { cacheValueMap = new WeakMap(); cacheValueMap.set(unions, mapKey); } let cacheReference = cacheValueMap.get(mapKey); if (!cacheReference) { cacheReference = {}; cacheValueMap.set(mapKey, cacheReference); } return cacheReference; } function getCacheTypename(selection: Selection): string | void { const cacheValue: unknown = innerState.clientCache.getCacheFromSelection(selection); if (isObjectWithType(cacheValue)) return cacheValue.__typename; interceptorManager.addSelection( innerState.selectionManager.getSelection({ key: '__typename', prevSelection: selection, }) ); } const emptyScalarArray = Object.freeze([]); const querySelection = selectionManager.getSelection({ key: 'query', type: SelectionType.Query, }); const mutationSelection = selectionManager.getSelection({ key: 'mutation', type: SelectionType.Mutation, }); const subscriptionSelection = selectionManager.getSelection({ key: 'subscription', type: SelectionType.Subscription, }); function createAccessor( schemaValue: Schema[string] | SchemaUnion, prevSelection: Selection, unions?: string[], parentTypename?: string ) { let cacheValue: unknown = innerState.clientCache.getCacheFromSelection(prevSelection); if (innerState.allowCache && cacheValue === null) return null; const accessor = accessorCache.getAccessor( prevSelection, getCacheValueReference(cacheValue, unions), () => { const isUnionsInterfaceSelection = Boolean(unions && parentTypename); if (normalizationHandler && (parentTypename || unions)) { if (unions) { const schemaKeys = normalizationHandler.schemaKeys; for (const objectTypeName of unions) { const objectNormalizationKeys = schemaKeys[objectTypeName]; if (objectNormalizationKeys?.length) { const coFetchSelections = objectNormalizationKeys.map((key) => innerState.selectionManager.getSelection({ key, prevSelection, unions: unionObjectTypesForSelections[objectTypeName] || [ objectTypeName, ], }) ); prevSelection.addCofetchSelections(coFetchSelections); } } } else if (parentTypename) { const normalizationKeys = normalizationHandler.schemaKeys[parentTypename]; if (normalizationKeys?.length) { const selections = normalizationKeys.map((key) => innerState.selectionManager.getSelection({ key, prevSelection, }) ); prevSelection.addCofetchSelections(selections); } } } const autoFetchUnionTypename = isUnionsInterfaceSelection ? () => { if (isUnionsInterfaceSelection) { interceptorManager.addSelection( innerState.selectionManager.getSelection({ key: '__typename', prevSelection, }) ); } } : undefined; const proxyValue = schemaValue instanceof SchemaUnion ? schemaValue.fieldsProxy : Object.keys(schemaValue).reduce((acum, key) => { acum[key] = ProxySymbol; return acum; }, {} as Record<string, unknown>); return new Proxy(proxyValue, { set(_target, key: string, value: unknown) { if (!proxyValue.hasOwnProperty(key)) throw TypeError('Invalid proxy assignation'); const targetSelection = innerState.selectionManager.getSelection({ key, prevSelection, unions, }); const data = extractDataFromProxy(value); innerState.clientCache.setCacheFromSelection(targetSelection, data); eventHandler.sendCacheChange({ data, selection: targetSelection, }); return true; }, get(_target, key: string, _receiver) { if (key === 'toJSON') return () => decycle<{}>( innerState.clientCache.getCacheFromSelection( prevSelection, {} ) ); if (schemaValue instanceof SchemaUnion) { if (!(key in schemaValue.types)) return; if (innerState.allowCache) { const typename = getCacheTypename(prevSelection); if (typename && typename !== key) return; } return createAccessor( schemaValue.types[key], prevSelection, [key], key ); } if (!proxyValue.hasOwnProperty(key)) return; const { __type, __args } = schemaValue[key]; let { pureType, isArray } = parseSchemaType(__type); const resolve = (args?: { argValues: Record<string, unknown>; argTypes: Record<string, string>; }): unknown => { const selection = innerState.selectionManager.getSelection({ key, prevSelection, args: args != null ? args.argValues : undefined, argTypes: args != null ? args.argTypes : undefined, unions, }); if (selection.selectionsList.length > depthLimit) return null; // For the subscribers of data changes interceptorManager.addSelectionCache(selection); if (scalarsEnumsHash[pureType]) { const cacheValue = innerState.clientCache.getCacheFromSelection(selection); accessorCache.addSelectionToAccessorHistory( accessor, selection ); if (cacheValue === undefined) { innerState.foundValidCache = false; let unionTypename: string | undefined | void; const isUnionWithDifferentTypeResult = isUnionsInterfaceSelection ? !!(unionTypename = getCacheTypename(prevSelection)) && unionTypename !== parentTypename : false; /** * If cache was not found & the selection doesn't have errors, * add the selection to the queue, except when querying unions or interfaces * and the __typename doesn't correspond to the target object type */ if ( // SelectionType.Subscription === 2 selection.type === 2 || (!isUnionWithDifferentTypeResult && (schedulerClientCache !== innerState.clientCache || !schedulerErrorsMap.has(selection))) ) { interceptorManager.addSelection(selection); autoFetchUnionTypename?.(); } return isArray ? emptyScalarArray : undefined; } else if ( !innerState.allowCache || // SelectionType.Subscription === 2 selection.type === 2 ) { // Or if you are making the network fetch always interceptorManager.addSelection(selection); autoFetchUnionTypename?.(); } else { // Support cache-and-network / stale-while-revalidate pattern interceptorManager.addSelectionCacheRefetch(selection); } return cacheValue; } let typeValue: Record<string, Type> | SchemaUnion = schema[pureType]; if (!typeValue && pureType.startsWith('$')) { typeValue = schemaUnions[(pureType = pureType.slice(1))]; } if (typeValue) { const childAccessor = ( isArray ? createArrayAccessor : createAccessor )(typeValue, selection, undefined, pureType); accessorCache.addAccessorChild(accessor, childAccessor); return childAccessor; } throw new GQtyError( `GraphQL Type not found: ${pureType}, available fields: "${Object.keys( schemaValue ).join(' | ')}"` ); }; if (__args) { const resolveInfo: ResolveInfo = { key, prevSelection, argTypes: __args, }; return Object.assign( function ProxyFn( argValues: Record<string, unknown> = emptyVariablesObject ) { return resolve({ argValues, argTypes: __args, }); }, { [ResolveInfoSymbol]: resolveInfo, } ); } return resolve(); }, }); } ); return accessor; } const query: GeneratedSchema['query'] = createAccessor( schema.query, querySelection )!; const mutation: GeneratedSchema['mutation'] = createAccessor( schema.mutation, mutationSelection )!; const subscription: GeneratedSchema['subscription'] = createAccessor( schema.subscription, subscriptionSelection )!; function assignSelections<A extends object, B extends A>( source: A | null | undefined, target: B | null | undefined ): void { if (source == null || target == null) return; let sourceSelection: Selection; let targetSelection: Selection; if ( !accessorCache.isProxy(source) || !(sourceSelection = accessorCache.getProxySelection(source)!) ) throw new GQtyError('Invalid source proxy', { caller: assignSelections, }); if ( !accessorCache.isProxy(target) || !(targetSelection = accessorCache.getProxySelection(target)!) ) throw new GQtyError('Invalid target proxy', { caller: assignSelections, }); const sourceSelections = accessorCache.getSelectionSetHistory(source); if (!sourceSelections) { if (process.env.NODE_ENV !== 'production') { console.warn("Source proxy doesn't have any selections made"); } return; } for (const selection of sourceSelections) { let mappedSelection = targetSelection; const filteredSelections = selection.selectionsList.filter( (value) => !sourceSelection.selectionsList.includes(value) ); for (const { key, args, argTypes } of filteredSelections) { mappedSelection = innerState.selectionManager.getSelection({ key, args, argTypes, prevSelection: mappedSelection, }); } accessorCache.addSelectionToAccessorHistory(target, mappedSelection); interceptorManager.addSelection(mappedSelection); } } return { createAccessor, createArrayAccessor, assignSelections, setCache, query, mutation, subscription, }; } const emptyVariablesObject = {};
the_stack
import { forkJoin, Observable, of } from "rxjs"; import { map } from "rxjs/operators"; import { RestApiConnectorService } from "../services/connectors/rest-api/rest-api-connector.service"; import { Serializable, ValidationData } from "./serializable"; import { StixObject } from "./stix/stix-object"; import { logger } from "../util/logger"; export class ExternalReferences extends Serializable { private _externalReferences : Map<string, ExternalReference> = new Map(); private _externalReferencesIndex : Map<string, number> = new Map(); private usedReferences : string[] = []; // array to store used references private missingReferences : string[] = []; // array to store missing references private brokenCitations : string[] = []; // array to store broken citations /** * return external references list */ public get externalReferences() { return this._externalReferences; } /** * Return list of external references in order */ public list() : Array<[number, ExternalReference]> { let externalRefList : Array<[number, ExternalReference]> = []; for (let [key, value] of this._externalReferencesIndex) { if (this.getReference(key)) externalRefList.push([value, this.getReference(key)]); } return externalRefList; } /** * Sort _externalReferences by alphabetical order * Restart map for displaying references */ public sortReferences() : void { // Sort map by alphabetical order on descriptions this._externalReferences = new Map([...this._externalReferences.entries()].sort((a,b) => a[1].description.localeCompare(b[1].description))); // Restart _externalReferencesIndex map this._externalReferencesIndex = new Map(); // Start index at 1 let index = 1; // Index 1 for (let [key, value] of this._externalReferences) { // Add to map if it has a description if(value.description){ // Do not include if description has (Citation: *) if(!value.description.includes("(Citation:")) { this._externalReferencesIndex.set(key, index); index += 1; } } } } /** * Return index of reference to display * Returns null if not found * @param sourceName source name of reference */ public getIndexOfReference(sourceName : string) : number { if(this._externalReferencesIndex.get(sourceName)) { return this._externalReferencesIndex.get(sourceName); } return null; } /** * Return if value exists in external references * @param sourceName source name of reference */ public hasValue(sourceName: string) : boolean { if (this._externalReferences.get(sourceName)) { return true; } return false; } /** * Return description of reference * @param sourceName source name of reference */ public getDescription(sourceName: string) : string { if (this._externalReferences.get(sourceName)) { let source = this._externalReferences.get(sourceName) if (source["description"]) { return source["description"]; } } return ""; } /** * Return ExternalReference object of given source name * return undefined if not found * @param sourceName source name of reference */ public getReference(sourceName : string) : ExternalReference { return this._externalReferences.get(sourceName); } /** * Add ExternalReference object to external references list * @param sourceName source name of reference * @param externalReference external reference object */ private addReference(sourceName : string, externalReference : ExternalReference) { if (sourceName && externalReference) { this._externalReferences.set(sourceName, externalReference); // Sort references by description and update index map this.sortReferences() } } /** * Check if the reference is on the object, and add it if it is not. * Returns an observable that is true if the reference exists or has been added, and false if it couldn't be added * @param {string} sourceName source name string of references * @param {RestApiConnectorService} restApiConnector the service to get references * @returns {Observable<boolean>} true if references is found in object or global external reference list, false if not */ private checkAndAddReference(sourceName : string, restApiConnector: RestApiConnectorService): Observable<boolean> { if (this.getReference(sourceName)) return of(true); return restApiConnector.getReference(sourceName).pipe( map((result) => { let x = result as any[]; if (x.length > 0) { this.addReference(sourceName, x[0]); return true; } return false; }) ); } /** * Parses value for references * @param value the value to match citations within * @param restApiConnector to connect to the REST API * @param validateReferencesAndCitations */ public parseCitations(value: string, restApiConnector: RestApiConnectorService): Observable<CitationParseResult> { let reReference = /\(Citation: (.*?)\)/gmu; let citations = value.match(reReference); let result = new CitationParseResult({ brokenCitations: this.validateBrokenCitations(value, [/\(Citation:([^ ].*?)\)/gmu, /\(citation:(.*?)\)/gmu]) }) if (citations) { // build lookup api map let api_map = {}; for (let i = 0; i < citations.length; i++) { // Split to get source name from citation let sourceName = citations[i].split("(Citation: ")[1].slice(0, -1); api_map[sourceName] = this.checkAndAddReference(sourceName, restApiConnector); } // check/add each citation return forkJoin(api_map).pipe( map((api_results) => { let citation_results = api_results as any; for (let key of Object.keys(citation_results)) { // was the result able to be found/added? if (citation_results[key]) result.usedCitations.add(key) else result.missingCitations.add(key) } return result; }) ) } else { return of(result); } } /** * validate given field for broken citation found by regular expression * @param field descriptive field that may contain citation * @param {regex[]} regExes regular expression */ private validateBrokenCitations(field, regExes): Set<string> { let result = new Set<string>(); for (let regex of regExes) { let brokenReferences = field.match(regex); if (brokenReferences) { for (let i = 0; i < brokenReferences.length; i++) { result.add(brokenReferences[i]); } } } return result; } /** * Parse citations from aliases which stores descriptions in external references * Add missing references to object if found in global external reference list * @param aliases list of alias names * @param restApiConnector * @param validateReferencesAndCitations? Optional param to validate references and citations */ public parseCitationsFromAliases(aliases : string[], restApiConnector : RestApiConnectorService): Observable<CitationParseResult> { // Parse citations from the alias descriptions stored in external references let api_calls = []; let result = new CitationParseResult(); for (let i = 0; i < aliases.length; i++) { if (this._externalReferences.get(aliases[i])) { result.usedCitations.add(aliases[i]); api_calls.push(this.parseCitations(this._externalReferences.get(aliases[i]).description, restApiConnector)); } } if (api_calls.length == 0) return of(result); else return forkJoin(api_calls).pipe( // get citation errors for each alias map((api_results) => { let citation_results = api_results as any; for (let citation_result of citation_results) { //merge into master list result.merge(citation_result); } return result; //return master list }) ) } /** * Update external references map with given reference list * @param references list of references */ public set externalReferences(references: any) { this._externalReferences = new Map(); this._externalReferencesIndex = new Map(); if (references){ // Create externalReferences list for (let i = 0; i < references.length; i++){ if ("source_name" in references[i] && !("external_id" in references[i])) { let description = "" if(references[i].description) { description = references[i].description; } let url = "" if(references[i].url) { url = references[i].url; } let externalRef : ExternalReference = { url : url, description : description } this._externalReferences.set(references[i]['source_name'], externalRef); } } // Sort references by description and update index map this.sortReferences() } } /** * Construct an external references object * optional @param references external references list from collection */ constructor(references?) { super(); if (references) this.deserialize(references); } /** * Transform the current object into a raw object for sending to the back-end, stripping any unnecessary fields * @abstract * @returns {*} the raw object to send */ public serialize(): ExternalReference[] { let rep: Array<{}> = []; for (const [key, value] of this._externalReferences) { let temp = {}; temp["source_name"] = key; if (value["url"]) temp["url"] = value["url"]; if (value["description"]) temp["description"] = value["description"]; rep.push(temp); } return rep; } /** * Parse the object from the record returned from the back-end * @abstract * @param {*} raw the raw object to parse */ public deserialize(raw: any) { if (typeof(raw) === "object") this.externalReferences = raw; else logger.error("TypeError: external_references field is not an object:", raw, "(",typeof(raw),")") } /** * Remove references which do not have the source name * * @param {string[]} usedSourceNames the source names that are used on the object; all other source names will be removed * @memberof ExternalReferences */ public removeUnusedReferences(usedSourceNames: string[]) { // Create temp external references map from used references // Resulting map will remove unused references let temp_externalReferences : Map<string, ExternalReference> = new Map(); for (let i = 0; i < usedSourceNames.length; i++) { let sourceName = usedSourceNames[i]; if (this._externalReferences.get(sourceName)) temp_externalReferences.set(sourceName, this._externalReferences.get(sourceName)); } let pre_delete_keys = Array.from(this._externalReferences.keys()); // Update external references with used references this._externalReferences = temp_externalReferences; let post_delete_keys = Array.from(this._externalReferences.keys()); logger.log("removed unused references", pre_delete_keys.filter((x) => !post_delete_keys.includes(x))) // Sort references by description and update index map this.sortReferences() } /* * Validate the current object state and return information on the result of the validation * Also removes unused external references. * @returns {Observable<ValidationData>} the validation warnings and errors once validation is complete. */ public validate(restAPIService: RestApiConnectorService, options: {fields: string[], object: StixObject}): Observable<ValidationData> { let result = new ValidationData(); let parse_apis = []; for (let field of options.fields) { if (!Object.keys(options.object)) continue; //object does not implement the field if (field == "aliases") parse_apis.push(this.parseCitationsFromAliases(options.object[field], restAPIService)) else parse_apis.push(this.parseCitations(options.object[field], restAPIService)); } return forkJoin(parse_apis).pipe( map(api_results => { let parse_results = api_results as CitationParseResult[]; let citationResult = new CitationParseResult(); for (let parse_result of parse_results) { citationResult.merge(parse_result); //merge all results into a single object } // use merged object to remove unused citations this.removeUnusedReferences(Array.from(citationResult.usedCitations)); // add to validation result // broken citations let brokenCitations = Array.from(citationResult.brokenCitations); if (brokenCitations.length == 1) result.errors.push({ result: "error", field: "external_references", //TODO set this to the actual field to improve warnings message: `Citation ${brokenCitations[0]} does not match format (Citation: source name)` }) else if (brokenCitations.length > 1) result.errors.push({ result: "error", field: "external_references", //TODO set this to the actual field to improve warnings message: `Citations ${brokenCitations.join(", ")} do not match format (Citation: source name)` }) //missing citations let missingCitations = Array.from(citationResult.missingCitations); if (missingCitations.length == 1) result.errors.push({ result: "error", field: "external_references", //TODO set this to the actual field to improve warnings message: `Cannot find reference: ${missingCitations[0]} ` }) else if (missingCitations.length > 1) result.errors.push({ result: "error", field: "external_references", //TODO set this to the actual field to improve warnings message: `Cannot find references: ${missingCitations.join(", ")}` }) //return the result return result; }) ) } } export interface ExternalReference { /** source name of the reference */ source_name?: string; /** url; url of reference */ url?: string; /** description; description of reference */ description?: string; } /** * The results of parsing citations in a single field */ export class CitationParseResult { //list of reference source names which have been used in this field public usedCitations: Set<string> = new Set(); //citations that could not be found public missingCitations: Set<string> = new Set(); // list of broken references detected in the field public brokenCitations: Set<string> = new Set(); constructor(initData?: {usedCitations?: Set<string>, missingCitations?: Set<string>, brokenCitations: Set<string>}) { if (initData && initData.usedCitations) this.usedCitations = initData.usedCitations; if (initData && initData.missingCitations) this.missingCitations = initData.missingCitations; if (initData && initData.brokenCitations) this.brokenCitations = initData.brokenCitations; } /** * Merge results from another CitationParseResult into this object * @param {CitationParseResult} that results from other object */ public merge(that: CitationParseResult) { this.usedCitations = new Set([...this.usedCitations, ...that.usedCitations]); this.missingCitations = new Set([...this.missingCitations, ...that.missingCitations]); this.brokenCitations = new Set([...this.brokenCitations, ...that.brokenCitations]); } }
the_stack
import React, {useEffect, useState} from 'react'; import { useIntl } from 'react-intl'; import { get } from 'lodash'; import { Text, View, FlatList } from 'react-native'; import { NoPost, PostCardPlaceHolder, UserListItem } from '../..'; import globalStyles from '../../../globalStyles'; import { CommunityListItem, EmptyScreen } from '../../basicUIElements'; import styles from './tabbedPostsStyles'; import { default as ROUTES } from '../../../constants/routeNames'; import { withNavigation } from 'react-navigation'; import {useSelector, useDispatch } from 'react-redux'; import { fetchCommunities, leaveCommunity, subscribeCommunity } from '../../../redux/actions/communitiesAction'; import { fetchLeaderboard, followUser, unfollowUser } from '../../../redux/actions/userAction'; import { getCommunity } from '../../../providers/hive/dhive'; interface TabEmptyViewProps { filterKey:string, isNoPost:boolean, navigation:any, } const TabEmptyView = ({ filterKey, isNoPost, navigation, }: TabEmptyViewProps) => { const intl = useIntl(); const dispatch = useDispatch(); //redux properties const isLoggedIn = useSelector((state) => state.application.isLoggedIn); const subscribingCommunities = useSelector( (state) => state.communities.subscribingCommunitiesInFeedScreen, ); const [recommendedCommunities, setRecommendedCommunities] = useState([]); const [recommendedUsers, setRecommendedUsers] = useState([]); const followingUsers = useSelector((state) => state.user.followingUsersInFeedScreen); const currentAccount = useSelector((state) => state.account.currentAccount); const pinCode = useSelector((state) => state.application.pin); const leaderboard = useSelector((state) => state.user.leaderboard); const communities = useSelector((state) => state.communities.communities); //hooks useEffect(()=>{ if (isNoPost) { if (filterKey === 'friends') { if (recommendedUsers.length === 0) { _getRecommendedUsers(); } } else if(filterKey === 'communities') { if (recommendedCommunities.length === 0) { _getRecommendedCommunities(); } } } }, [isNoPost]) useEffect(() => { const {loading, error, data} = leaderboard; if (!loading) { if (!error && data && data.length > 0) { _formatRecommendedUsers(data); } } }, [leaderboard]); useEffect(() => { const {loading, error, data} = communities; if (!loading) { if (!error && data && data?.length > 0) { _formatRecommendedCommunities(data); } } }, [communities]); useEffect(() => { const recommendeds = [...recommendedCommunities]; Object.keys(subscribingCommunities).map((communityId) => { if (!subscribingCommunities[communityId].loading) { if (!subscribingCommunities[communityId].error) { if (subscribingCommunities[communityId].isSubscribed) { recommendeds.forEach((item) => { if (item.name === communityId) { item.isSubscribed = true; } }); } else { recommendeds.forEach((item) => { if (item.name === communityId) { item.isSubscribed = false; } }); } } } }); setRecommendedCommunities(recommendeds); }, [subscribingCommunities]); useEffect(() => { const recommendeds = [...recommendedUsers]; Object.keys(followingUsers).map((following) => { if (!followingUsers[following].loading) { if (!followingUsers[following].error) { if (followingUsers[following].isFollowing) { recommendeds.forEach((item) => { if (item._id === following) { item.isFollowing = true; } }); } else { recommendeds.forEach((item) => { if (item._id === following) { item.isFollowing = false; } }); } } } }); setRecommendedUsers(recommendeds); }, [followingUsers]); //fetching const _getRecommendedUsers = () => dispatch(fetchLeaderboard()); const _getRecommendedCommunities = () => dispatch(fetchCommunities('', 10)); //formating const _formatRecommendedCommunities = async (communitiesArray) => { try { const ecency = await getCommunity('hive-125125'); const recommendeds = [ecency, ...communitiesArray]; recommendeds.forEach((item) => Object.assign(item, { isSubscribed: false })); setRecommendedCommunities(recommendeds); } catch (err) { console.log(err, '_getRecommendedUsers Error'); } }; const _formatRecommendedUsers = (usersArray) => { const recommendeds = usersArray.slice(0, 10); recommendeds.unshift({ _id: 'good-karma' }); recommendeds.unshift({ _id: 'ecency' }); recommendeds.forEach((item) => Object.assign(item, { isFollowing: false })); setRecommendedUsers(recommendeds); }; //actions related routines const _handleSubscribeCommunityButtonPress = (data) => { let subscribeAction; let successToastText = ''; let failToastText = ''; if (!data.isSubscribed) { subscribeAction = subscribeCommunity; successToastText = intl.formatMessage({ id: 'alert.success_subscribe', }); failToastText = intl.formatMessage({ id: 'alert.fail_subscribe', }); } else { subscribeAction = leaveCommunity; successToastText = intl.formatMessage({ id: 'alert.success_leave', }); failToastText = intl.formatMessage({ id: 'alert.fail_leave', }); } dispatch( subscribeAction(currentAccount, pinCode, data, successToastText, failToastText, 'feedScreen'), ); }; const _handleFollowUserButtonPress = (data, isFollowing) => { let followAction; let successToastText = ''; let failToastText = ''; if (!isFollowing) { followAction = followUser; successToastText = intl.formatMessage({ id: 'alert.success_follow', }); failToastText = intl.formatMessage({ id: 'alert.fail_follow', }); } else { followAction = unfollowUser; successToastText = intl.formatMessage({ id: 'alert.success_unfollow', }); failToastText = intl.formatMessage({ id: 'alert.fail_unfollow', }); } data.follower = get(currentAccount, 'name', ''); dispatch(followAction(currentAccount, pinCode, data, successToastText, failToastText)); }; const _handleOnPressLogin = () => { navigation.navigate(ROUTES.SCREENS.LOGIN); }; //render related operations if ((filterKey === 'feed' || filterKey === 'friends' || filterKey === 'communities') && !isLoggedIn) { return ( <NoPost imageStyle={styles.noImage} isButtonText defaultText={intl.formatMessage({ id: 'profile.login_to_see', })} handleOnButtonPress={_handleOnPressLogin} /> ); } if (isNoPost) { if (filterKey === 'friends') { return ( <> <Text style={[globalStyles.subTitle, styles.noPostTitle]}> {intl.formatMessage({ id: 'profile.follow_people' })} </Text> <FlatList data={recommendedUsers} extraData={recommendedUsers} keyExtractor={(item, index) => `${item._id || item.id}${index}`} renderItem={({ item, index }) => ( <UserListItem index={index} username={item._id} isHasRightItem rightText={ item.isFollowing ? intl.formatMessage({ id: 'user.unfollow' }) : intl.formatMessage({ id: 'user.follow' }) } rightTextStyle={[styles.followText, item.isFollowing && styles.unfollowText]} isLoggedIn={isLoggedIn} isFollowing={item.isFollowing} isLoadingRightAction={ followingUsers.hasOwnProperty(item._id) && followingUsers[item._id].loading } onPressRightText={_handleFollowUserButtonPress} handleOnPress={(username) => navigation.navigate({ routeName: ROUTES.SCREENS.PROFILE, params: { username, }, key: username, }) } /> )} /> </> ); } else if (filterKey === 'communities') { return ( <> <Text style={[globalStyles.subTitle, styles.noPostTitle]}> {intl.formatMessage({ id: 'profile.follow_communities' })} </Text> <FlatList data={recommendedCommunities} keyExtractor={(item, index) => `${item.id || item.title}${index}`} renderItem={({ item, index }) => ( <CommunityListItem index={index} title={item.title} about={item.about} admins={item.admins} id={item.id} authors={item.num_authors} posts={item.num_pending} subscribers={item.subscribers} isNsfw={item.is_nsfw} name={item.name} handleOnPress={(name) => navigation.navigate({ routeName: ROUTES.SCREENS.COMMUNITY, params: { tag: name, }, }) } handleSubscribeButtonPress={_handleSubscribeCommunityButtonPress} isSubscribed={item.isSubscribed} isLoadingRightAction={ subscribingCommunities.hasOwnProperty(item.name) && subscribingCommunities[item.name].loading } isLoggedIn={isLoggedIn} /> )} /> </> ); } else { return ( <EmptyScreen style={styles.emptyAnimationContainer} /> ) } } return ( <View style={styles.placeholderWrapper}> <PostCardPlaceHolder /> </View> ); }; export default withNavigation(TabEmptyView);
the_stack
import * as utils from "tsutils"; import * as ts from "typescript"; import { ENABLE_DISABLE_REGEX } from "../enableDisableRules"; import * as Lint from "../index"; import { escapeRegExp, isLowerCase, isUpperCase } from "../utils"; interface IExceptionsObject { "ignore-words"?: string[]; "ignore-pattern"?: string; } interface Options { space: boolean; case: Case; exceptions?: RegExp; failureSuffix: string; allowTrailingLowercase: boolean; } interface CommentStatus { text: string; start: number; leadingSpaceError: boolean; uppercaseError: boolean; lowercaseError: boolean; firstLetterPos: number; validForTrailingLowercase: boolean; } const enum Case { None, Lower, Upper, } const OPTION_SPACE = "check-space"; const OPTION_LOWERCASE = "check-lowercase"; const OPTION_UPPERCASE = "check-uppercase"; const OPTION_ALLOW_TRAILING_LOWERCASE = "allow-trailing-lowercase"; export class Rule extends Lint.Rules.AbstractRule { /* tslint:disable:object-literal-sort-keys */ public static metadata: Lint.IRuleMetadata = { ruleName: "comment-format", description: "Enforces formatting rules for single-line comments.", rationale: "Helps maintain a consistent, readable style in your codebase.", optionsDescription: Lint.Utils.dedent` Four arguments may be optionally provided: * \`"${OPTION_SPACE}"\` requires that all single-line comments must begin with a space, as in \`// comment\` * note that for comments starting with multiple slashes, e.g. \`///\`, leading slashes are ignored * TypeScript reference comments are ignored completely * \`"${OPTION_LOWERCASE}"\` requires that the first non-whitespace character of a comment must be lowercase, if applicable. * \`"${OPTION_UPPERCASE}"\` requires that the first non-whitespace character of a comment must be uppercase, if applicable. * \`"${OPTION_ALLOW_TRAILING_LOWERCASE}"\` allows that only the first comment of a series of comments needs to be uppercase. * requires \`"${OPTION_UPPERCASE}"\` * comments must start at the same position Exceptions to \`"${OPTION_LOWERCASE}"\` or \`"${OPTION_UPPERCASE}"\` can be managed with object that may be passed as last argument. One of two options can be provided in this object: * \`"ignore-words"\` - array of strings - words that will be ignored at the beginning of the comment. * \`"ignore-pattern"\` - string - RegExp pattern that will be ignored at the beginning of the comment. `, options: { type: "array", items: { anyOf: [ { type: "string", enum: [ OPTION_SPACE, OPTION_LOWERCASE, OPTION_UPPERCASE, OPTION_ALLOW_TRAILING_LOWERCASE, ], }, { type: "object", properties: { "ignore-words": { type: "array", items: { type: "string", }, }, "ignore-pattern": { type: "string", }, }, minProperties: 1, maxProperties: 1, }, ], }, minLength: 1, maxLength: 5, }, optionExamples: [ [true, OPTION_SPACE, OPTION_UPPERCASE, OPTION_ALLOW_TRAILING_LOWERCASE], [true, OPTION_LOWERCASE, { "ignore-words": ["TODO", "HACK"] }], [true, OPTION_LOWERCASE, { "ignore-pattern": "STD\\w{2,3}\\b" }], ], type: "style", typescriptOnly: false, hasFix: true, }; /* tslint:enable:object-literal-sort-keys */ public static LOWERCASE_FAILURE = "comment must start with lowercase letter"; public static SPACE_LOWERCASE_FAILURE = "comment must start with a space and lowercase letter"; public static UPPERCASE_FAILURE = "comment must start with uppercase letter"; public static SPACE_UPPERCASE_FAILURE = "comment must start with a space and uppercase letter"; public static LEADING_SPACE_FAILURE = "comment must start with a space"; public static IGNORE_WORDS_FAILURE_FACTORY = (words: string[]): string => ` or the word(s): ${words.join(", ")}`; public static IGNORE_PATTERN_FAILURE_FACTORY = (pattern: string): string => ` or its start must match the regex pattern "${pattern}"`; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { const commentFormatWalker = new CommentFormatWalker( sourceFile, this.ruleName, parseOptions(this.ruleArguments), ); return this.applyWithWalker(commentFormatWalker); } } function parseOptions(options: Array<string | IExceptionsObject>): Options { return { allowTrailingLowercase: has(OPTION_ALLOW_TRAILING_LOWERCASE), case: options.indexOf(OPTION_LOWERCASE) !== -1 ? Case.Lower : options.indexOf(OPTION_UPPERCASE) !== -1 ? Case.Upper : Case.None, failureSuffix: "", space: has(OPTION_SPACE), ...composeExceptions(options[options.length - 1]), }; function has(option: string): boolean { return options.indexOf(option) !== -1; } } function composeExceptions( option?: string | IExceptionsObject, ): undefined | { exceptions: RegExp; failureSuffix: string } { if (typeof option !== "object") { return undefined; } const ignorePattern = option["ignore-pattern"]; if (ignorePattern !== undefined) { return { exceptions: new RegExp(`^\\s*(${ignorePattern})`), failureSuffix: Rule.IGNORE_PATTERN_FAILURE_FACTORY(ignorePattern), }; } const ignoreWords = option["ignore-words"]; if (ignoreWords !== undefined && ignoreWords.length !== 0) { return { exceptions: new RegExp( `^\\s*(?:${ignoreWords.map(word => escapeRegExp(word.trim())).join("|")})\\b`, ), failureSuffix: Rule.IGNORE_WORDS_FAILURE_FACTORY(ignoreWords), }; } return undefined; } class CommentFormatWalker extends Lint.AbstractWalker<Options> { private prevComment: ts.LineAndCharacter | undefined; private prevCommentIsValid: boolean | undefined; public walk(sourceFile: ts.SourceFile) { utils.forEachComment(sourceFile, (fullText, comment) => { const commentStatus = this.checkComment(fullText, comment); this.handleFailure(commentStatus, comment.end); // cache position of last comment this.prevComment = ts.getLineAndCharacterOfPosition(sourceFile, comment.pos); this.prevCommentIsValid = commentStatus.validForTrailingLowercase; }); } private checkComment(fullText: string, { kind, pos, end }: ts.CommentRange): CommentStatus { const status: CommentStatus = { firstLetterPos: -1, leadingSpaceError: false, lowercaseError: false, start: pos + 2, text: "", uppercaseError: false, validForTrailingLowercase: false, }; if ( kind !== ts.SyntaxKind.SingleLineCommentTrivia || // exclude empty comments status.start === end || // exclude /// <reference path="..."> (fullText[status.start] === "/" && this.sourceFile.referencedFiles.some(ref => ref.pos >= pos && ref.end <= end)) ) { return status; } // skip all leading slashes while (fullText[status.start] === "/") { ++status.start; } if (status.start === end) { return status; } status.text = fullText.slice(status.start, end); // whitelist //#region and //#endregion and JetBrains IDEs' "//noinspection ...", "//region", "//endregion" if (/^(?:#?(?:end)?region|noinspection\s)/.test(status.text)) { return status; } if (this.options.space && status.text[0] !== " ") { status.leadingSpaceError = true; } if ( this.options.case === Case.None || (this.options.exceptions !== undefined && this.options.exceptions.test(status.text)) || ENABLE_DISABLE_REGEX.test(status.text) ) { return status; } // search for first non-space character to check if lower or upper const charPos = status.text.search(/\S/); if (charPos === -1) { return status; } // All non-empty and not whitelisted comments are valid for the trailing lowercase rule status.validForTrailingLowercase = true; status.firstLetterPos = charPos; if (this.options.case === Case.Lower && !isLowerCase(status.text[charPos])) { status.lowercaseError = true; } else if (this.options.case === Case.Upper && !isUpperCase(status.text[charPos])) { status.uppercaseError = true; if ( this.options.allowTrailingLowercase && this.prevComment !== undefined && this.prevCommentIsValid ) { const currentComment = ts.getLineAndCharacterOfPosition(this.sourceFile, pos); if ( this.prevComment.line + 1 === currentComment.line && this.prevComment.character === currentComment.character ) { status.uppercaseError = false; } } } return status; } private handleFailure(status: CommentStatus, end: number) { // No failure detected if (!status.leadingSpaceError && !status.lowercaseError && !status.uppercaseError) { return; } // Only whitespace failure if (status.leadingSpaceError && !status.lowercaseError && !status.uppercaseError) { this.addFailure( status.start, end, Rule.LEADING_SPACE_FAILURE, Lint.Replacement.appendText(status.start, " "), ); return; } let msg: string; let firstLetterFix: string; if (status.lowercaseError) { msg = status.leadingSpaceError ? Rule.SPACE_LOWERCASE_FAILURE : Rule.LOWERCASE_FAILURE; firstLetterFix = status.text[status.firstLetterPos].toLowerCase(); } else { msg = status.leadingSpaceError ? Rule.SPACE_UPPERCASE_FAILURE : Rule.UPPERCASE_FAILURE; firstLetterFix = status.text[status.firstLetterPos].toUpperCase(); } const fix = status.leadingSpaceError ? new Lint.Replacement(status.start, 1, ` ${firstLetterFix}`) : new Lint.Replacement(status.start + status.firstLetterPos, 1, firstLetterFix); this.addFailure(status.start, end, msg + this.options.failureSuffix, fix); } }
the_stack
import { FsService } from "backend/fs/fs-service"; import { dispose, Disposer, IDisposable, IDisposableObject } from "fxdk/base/disposable"; import { createFsWatcherEvent, FsWatcher, FsWatcherEvent, FsWatcherEventType } from 'backend/fs/fs-watcher'; import { FsUpdateKind, IFsEntry, IFsUpdate } from "../../common/project.types"; import { AssetMeta, assetMetaFileExt } from "shared/asset.types"; import { ProjectFsExtensions } from "../projectExtensions"; import { UniqueQueue } from "backend/queue"; import { ApiClient } from "backend/api/api-client"; import { ProjectFsEvents } from "../project-events"; import { ProjectRuntime } from "./project-runtime"; import { APIRQ } from "shared/api.requests"; import { joaatString } from "utils/joaat"; import { isAssetMetaFile, stripAssetMetaExt } from "utils/project"; import { ScopedLogService } from "backend/logger/scoped-logger"; import { lazyInject } from "backend/container-access"; import { ProjectApi } from "fxdk/project/common/project.api"; import { disposableTimeout } from "fxdk/base/async"; function hashFsWatcherEvent(event: FsWatcherEvent): string { return joaatString(`${event[0]}:${event[1]}:${event[2] ?? null}`); } enum ScanDepth { Deep, Auto, Shallow, } export class ProjectFsController implements IDisposableObject { @lazyInject(FsService) protected readonly fsService: FsService; protected readonly logService = new ScopedLogService('ProjectFS'); @lazyInject(ApiClient) protected readonly apiClient: ApiClient; private path!: string; private rootFsEntry: IFsEntry | null = null; private toDispose = new Disposer(); private fsEventsQueue: UniqueQueue<FsWatcherEvent>; private ignoredPaths: string[]; private fsEventSuppression: Record<FsWatcherEventType, Set<string>> = { [FsWatcherEventType.CREATED]: new Set(), [FsWatcherEventType.DELETED]: new Set(), [FsWatcherEventType.MODIFIED]: new Set(), [FsWatcherEventType.RENAMED]: new Set(), }; private fsUpdateErrorDisposals: Record<string, IDisposable> = {}; constructor() { this.fsEventsQueue = this.toDispose.register(new UniqueQueue(this.processFsEvent, hashFsWatcherEvent)); this.toDispose.register(this.apiClient.on(ProjectApi.FsEndpoints.shallowScanChildren, async (fsEntryPath) => { if (typeof fsEntryPath !== 'string') { return; } const fsEntry = this.getFsEntry(fsEntryPath); if (!fsEntry) { return; } await this.scanFsEntryChildren(fsEntryPath, fsEntry, ScanDepth.Shallow); this.sendFsUpdate({ kind: FsUpdateKind.Update, fsEntry, path: this.getEntryPathParts(fsEntryPath), }); })); } getFsEntry(fullEntryPath: string): IFsEntry | null { return this.getFsEntryByPath(this.getEntryPathParts(fullEntryPath)); } getRootFsEntry(): IFsEntry { if (!this.rootFsEntry) { throw new Error('Missing root fs entry'); } return this.rootFsEntry; } async init(rt: ProjectRuntime) { this.path = rt.state.path; this.ignoredPaths = [ rt.state.storagePath, rt.state.manifestPath, this.fsService.joinPath(rt.state.path, '.vscode'), ]; this.rootFsEntry = await this.spawnFsEntry(this.path); if (!this.rootFsEntry) { throw new Error('Failed to scan project fs entry'); } this.toDispose.register(new FsWatcher({ path: this.path, ignoredPaths: this.ignoredPaths, logger: (...args) => this.logService.log('[WATCHER]', ...args), onEvents: (events) => this.fsEventsQueue.appendMany(events), })); await this.scanFsEntryChildren(this.path, this.rootFsEntry); ProjectFsEvents.Hydrated.emit(this.rootFsEntry); } async dispose() { dispose(this.toDispose); for (const disposable of Object.values(this.fsUpdateErrorDisposals)) { dispose(disposable); } } //#region API async createFile({ filePath, fileName }: APIRQ.ProjectCreateFile): Promise<string> { const fileFullPath = this.fsService.joinPath(filePath, fileName); if (!(await this.fsService.statSafe(fileFullPath))) { await this.fsService.writeFile(fileFullPath, ''); } return fileFullPath; } async createDirectory({ directoryName, directoryPath }: APIRQ.ProjectCreateDirectory) { const directoryFullPath = this.fsService.joinPath(directoryPath, directoryName); if (!(await this.fsService.statSafe(directoryFullPath))) { await this.fsService.mkdirp(directoryFullPath); } } async copyEntry(request: APIRQ.CopyEntry) { const sourceDirName = this.fsService.dirname(request.sourcePath); if (sourceDirName === request.targetPath) { return; } this.fsService.copy(request.sourcePath, request.targetPath); } async copyEntries(request: APIRQ.CopyEntries) { if (!request.sourcePaths.length) { return; } await Promise.all(request.sourcePaths.map((sourcePath) => { return this.fsService.copy(sourcePath, request.targetPath); })); } // This will trigger actual RENAMED fs event async renameEntry(request: APIRQ.RenameEntry) { const newEntryPath = this.fsService.joinPath(this.fsService.dirname(request.entryPath), request.newName); if (newEntryPath === request.entryPath) { return; } await ProjectFsEvents.BeforeRename.emit({ oldEntryPath: request.entryPath, entryPath: newEntryPath }); await this.fsService.rename(request.entryPath, newEntryPath); this.logService.log('Renamed entry', request); } // While this one will trigger sequence of CREATED -> DELETED events, so we fake the renaming async moveEntry(request: APIRQ.MoveEntry) { const { sourcePath, targetPath } = request; const newPath = this.fsService.joinPath(targetPath, this.fsService.basename(sourcePath)); if (newPath === sourcePath) { return; } await ProjectFsEvents.BeforeRename.emit({ oldEntryPath: sourcePath, entryPath: newPath }); this.fsEventSuppression[FsWatcherEventType.CREATED].add(newPath); this.fsEventSuppression[FsWatcherEventType.DELETED].add(sourcePath); await this.fsService.rename(sourcePath, newPath); await this.processRenamed(newPath, sourcePath); } async deleteEntry(request: APIRQ.DeleteEntry): Promise<APIRQ.DeleteEntryResponse> { const { entryPath, hardDelete } = request; if (!(await this.fsService.statSafe(entryPath))) { return APIRQ.DeleteEntryResponse.Ok; } if (hardDelete) { await this.fsService.rimraf(entryPath); } else { try { await this.fsService.moveToTrashBin(entryPath); } catch (e) { this.logService.log(`Failed to recycle fs entry: ${e.toString()}`); this.fsEventsQueue.append(createFsWatcherEvent(FsWatcherEventType.MODIFIED, entryPath)); return APIRQ.DeleteEntryResponse.FailedToRecycle; } } return APIRQ.DeleteEntryResponse.Ok; } async setEntryMeta(entryPath: string, meta: AssetMeta) { const entryMetaPath = this.getEntryMetaPath(entryPath); return this.fsService.writeFileJson(entryMetaPath, meta); } async deleteEntryMeta(entryPath: string) { const entryMetaPath = this.getEntryMetaPath(entryPath); return this.fsService.unlink(entryMetaPath); } //#endregion API private async spawnFsEntry(entryPath: string): Promise<IFsEntry | null> { const entryMetaPath = this.getEntryMetaPath(entryPath); let [stat, fxmeta] = await Promise.all([ this.fsService.statSafeRetries(entryPath), this.fsService.readFileJson<AssetMeta>(entryMetaPath).catch(() => undefined), ]); if (!stat) { this.logService.error(new Error(`Failed to stat ${entryPath}`)); return null; } const isDirectory = stat.isDirectory(); const fsEntry: IFsEntry = { handle: isDirectory ? 'directory' : 'file', name: this.fsService.basename(entryPath), fxmeta, isDirectory, ctime: stat.ctimeMs, mtime: stat.mtimeMs, children: {}, childrenScanned: false, }; fsEntry.handle = await ProjectFsExtensions.getHandle(fsEntry, entryPath); await ProjectFsEvents.FsEntrySpawned.emit({ fsEntry, entryPath }); return fsEntry; } private async updateFsEntry(entryPath: string, fsEntry: IFsEntry): Promise<Partial<IFsEntry> | null> { const mainStat = await this.fsService.statSafeRetries(entryPath); if (!mainStat) { // It could be that we have a delete event in the next events batch, so delay this error a bit this.addFsUpdateErrorNoEntry(entryPath); return null; } ([fsEntry.handle, fsEntry.fxmeta] = await Promise.all([ ProjectFsExtensions.getHandle(fsEntry, entryPath), this.fsService.readFileJson<AssetMeta>(this.getEntryMetaPath(entryPath)).catch(() => undefined) ])); fsEntry.ctime = mainStat.ctimeMs; fsEntry.mtime = mainStat.mtimeMs; await ProjectFsEvents.FsEntryUpdated.emit({ fsEntry, entryPath }); return { handle: fsEntry.handle, fxmeta: fsEntry.fxmeta, ctime: fsEntry.ctime, mtime: fsEntry.mtime, }; } private addFsUpdateErrorNoEntry(entryPath: string) { this.extinguishFsUpdateError(entryPath); this.fsUpdateErrorDisposals[entryPath] = disposableTimeout( () => { this.logService.error(new Error(`Failed to update fs entry as it is missing in filesystem`), { entryPath }); }, 1000, // defensively large timeout ); } private extinguishFsUpdateError(entryPath: string) { if (this.fsUpdateErrorDisposals[entryPath]) { dispose(this.fsUpdateErrorDisposals[entryPath]); delete this.fsUpdateErrorDisposals[entryPath]; } } private async scanFsEntryChildren(entryPath: string, fsEntry: IFsEntry, depth = ScanDepth.Auto) { const entryNames = await this.fsService.readdir(entryPath); await Promise.all(entryNames.map(async (entryName) => { // TODO: Git integration if (entryName === '.git') { return; } if (isAssetMetaFile(entryName)) { return; } const childEntryPath = this.fsService.joinPath(entryPath, entryName); if (this.ignoredPaths.find((ignoredPath) => childEntryPath.startsWith(ignoredPath))) { return; } const childFsEntry = await this.spawnFsEntry(childEntryPath); if (!childFsEntry) { return; } fsEntry.children[entryName] = childFsEntry; // So far only this folder needs lazy-loading // this implies no asset runtimes will be spawned for this folder children, // which would be weird in general if (childFsEntry.name === 'node_modules' && depth !== ScanDepth.Deep) { return; } if (childFsEntry.isDirectory && depth !== ScanDepth.Shallow) { await this.scanFsEntryChildren(childEntryPath, childFsEntry); } })); fsEntry.childrenScanned = true; await ProjectFsEvents.FsEntryChildrenScanned.emit({ fsEntry, entryPath }); } private getEntryMetaPath(entryPath: string): string { const assetName = this.fsService.basename(entryPath); const assetMetaFilename = assetName + assetMetaFileExt; return this.fsService.joinPath(this.fsService.dirname(entryPath), assetMetaFilename);; } private readonly processFsEvent = async (event: FsWatcherEvent) => { const [type, entryPath, oldEntryPath] = event; const assetMetaFile = isAssetMetaFile(entryPath); if (!assetMetaFile) { // Expand events if needed this.fsEventsQueue.appendMany(ProjectFsExtensions.expandEvent(event)); } // Handle suppression, yes, Set.delete returns whether or not it has deleted entry if (this.fsEventSuppression[type].delete(entryPath)) { return; } // Repurpose asset meta file update to it's associated entry MODIFIED event if (assetMetaFile) { this.fsEventsQueue.append(createFsWatcherEvent(FsWatcherEventType.MODIFIED, stripAssetMetaExt(entryPath))); return; } try { switch (type) { case FsWatcherEventType.CREATED: { await this.processCreated(entryPath); return; } case FsWatcherEventType.MODIFIED: { await this.processModified(entryPath); return; } case FsWatcherEventType.RENAMED: { if (oldEntryPath) { await this.processRenamed(entryPath, oldEntryPath); } else { await this.processCreated(entryPath); } return; } case FsWatcherEventType.DELETED: { await this.processDeleted(entryPath); return; } } } catch (e) { this.logService.error(e); } }; private async processCreated(entryPath: string) { const fsEntry = await this.spawnFsEntry(entryPath); if (!fsEntry) { return; } const entryPathParts = this.getEntryPathParts(entryPath); const parentEntryPathParts = this.getEntryPathPartsParent(entryPathParts); // Only "legit" case when there's no parent fs entry - project root, // but that can't be created when we're already there const parentFsEntry = this.getFsEntryByPath(parentEntryPathParts); if (!parentFsEntry) { return; } parentFsEntry.children[fsEntry.name] = fsEntry; if (fsEntry.isDirectory && this.shouldScanFsEntryChildren(entryPath)) { await this.scanFsEntryChildren(entryPath, fsEntry); } this.sendFsUpdate({ kind: FsUpdateKind.Set, parentPath: parentEntryPathParts, fsEntry, }); await ProjectFsEvents.AfterCreated.emit({ fsEntry, entryPath }); } private async processModified(entryPath: string) { const entryPathParts = this.getEntryPathParts(entryPath); const fsEntry = this.getFsEntryByPath(entryPathParts); if (!fsEntry) { return; } const update = await this.updateFsEntry(entryPath, fsEntry); if (!update) { return; } this.sendFsUpdate({ kind: FsUpdateKind.Update, path: entryPathParts, fsEntry: update, }); await ProjectFsEvents.AfterModified.emit({ fsEntry, entryPath }); } private async processRenamed(entryPath: string, oldEntryPath: string) { const oldEntryPathParts = this.getEntryPathParts(oldEntryPath); const oldEntryName = this.getEntryPathPartsName(oldEntryPathParts); const fsEntry = this.getFsEntryByPath(oldEntryPathParts); if (!fsEntry) { this.logService.log(`Unable to handle rename event of entry that did not exist in project tree before`); return; } const newEntryPathParts = this.getEntryPathParts(entryPath); const newEntryName = this.getEntryPathPartsName(newEntryPathParts); const newParentEntryPathParts = this.getEntryPathPartsParent(newEntryPathParts); const newParentFsEntry = this.getFsEntryByPath(newParentEntryPathParts); const oldParentEntryPathParts = this.getEntryPathPartsParent(oldEntryPathParts); const oldParentFsEntry = this.getFsEntryByPath(oldParentEntryPathParts); delete oldParentFsEntry?.children[oldEntryName]; if (newParentFsEntry) { newParentFsEntry.children[newEntryName] = fsEntry; } this.sendFsUpdate({ kind: FsUpdateKind.Rename, oldName: oldEntryName, newName: newEntryName, newParentPath: newParentEntryPathParts, oldParentPath: oldParentEntryPathParts, }); this.apiClient.emit(ProjectApi.FsEndpoints.entryRenamed, { fromEntryPath: oldEntryPath, toEntryPath: entryPath, }); await ProjectFsEvents.AfterRenamed.emit({ fsEntry, oldEntryPath, entryPath }); } private async processDeleted(oldEntryPath: string) { // There could be an update error pending this.extinguishFsUpdateError(oldEntryPath); const entryPathParts = this.getEntryPathParts(oldEntryPath); const parentEntryPathParts = this.getEntryPathPartsParent(entryPathParts); const entryName = this.getEntryPathPartsName(entryPathParts); const parentEntry = this.getFsEntryByPath(parentEntryPathParts); delete parentEntry?.children[entryName]; this.sendFsUpdate({ kind: FsUpdateKind.Delete, name: entryName, parentPath: parentEntryPathParts, }); this.apiClient.emit(ProjectApi.FsEndpoints.entryDeleted, { entryPath: oldEntryPath }); await ProjectFsEvents.AfterDeleted.emit({ oldEntryPath }); } private shouldScanFsEntryChildren(entryPath: string): boolean { return true; } private getEntryPathParts(entryPath: string): string[] { return this.fsService.splitPath(entryPath.substr(this.path.length + 1)); } private getEntryPathPartsParent(entryPathParts: string[]): string[] { return entryPathParts.slice(0, -1); } private getEntryPathPartsName(entryPathParts: string[]): string { return entryPathParts[entryPathParts.length - 1]; } private getFsEntryByPath(entryPathParts: string[]): IFsEntry | null { return entryPathParts.reduce((fsEntry, pathPart) => fsEntry?.children[pathPart] || null, this.rootFsEntry); } private sendFsUpdate(update: IFsUpdate) { this.apiClient.emit(ProjectApi.FsEndpoints.update, update); } }
the_stack
import type { ParserOptions as HTMLParserOptions } from 'htmlparser2' import { Parser as HTMLParser } from 'htmlparser2' import type { ParserOptions } from '@babel/parser' import type { AttributeNode, DirectiveNode, ExpressionNode, TemplateChildNode, } from '@vue/compiler-core' import { baseParse } from '@vue/compiler-core' import { parserOptions } from '@vue/compiler-dom' import { camelize } from '@vue/shared' import type { ParsedSFC, ScriptSetupTransformOptions, ScriptTagMeta, } from '../types' import { getIdentifierUsages } from './identifiers' import { parse } from './babel' import { exhaustiveCheckReturnUndefined, isNotNil, pascalize } from './utils' namespace NodeTypes { export const ROOT = 0, ELEMENT = 1, TEXT = 2, COMMENT = 3, SIMPLE_EXPRESSION = 4, INTERPOLATION = 5, ATTRIBUTE = 6, DIRECTIVE = 7, COMPOUND_EXPRESSION = 8, IF = 9, IF_BRANCH = 10, FOR = 11, TEXT_CALL = 12, VNODE_CALL = 13, JS_CALL_EXPRESSION = 14, JS_OBJECT_EXPRESSION = 15, JS_PROPERTY = 16, JS_ARRAY_EXPRESSION = 17, JS_FUNCTION_EXPRESSION = 18, JS_CONDITIONAL_EXPRESSION = 19, JS_CACHE_EXPRESSION = 20, JS_BLOCK_STATEMENT = 21, JS_TEMPLATE_LITERAL = 22, JS_IF_STATEMENT = 23, JS_ASSIGNMENT_EXPRESSION = 24, JS_SEQUENCE_EXPRESSION = 25, JS_RETURN_STATEMENT = 26 } namespace ElementTypes { export const ELEMENT = 0, COMPONENT = 1, SLOT = 2, TEMPLATE = 3 } const multilineCommentsRE = /\/\*\s(.|[\r\n])*?\*\//gm const singlelineCommentsRE = /\/\/\s.*/g const BUILD_IN_DIRECTIVES = new Set([ 'if', 'else', 'else-if', 'for', 'once', 'model', 'on', 'bind', 'slot', 'slot-scope', 'key', 'ref', 'text', 'html', 'show', 'pre', 'cloak', // 'el', // 'ref', ]) function getComponents(node: TemplateChildNode): string[] { const current = node.type === NodeTypes.ELEMENT && node.tagType === ElementTypes.COMPONENT ? [node.tag] : node.type === NodeTypes.ELEMENT && node.tagType === ElementTypes.ELEMENT ? [node.tag] : [] const children = node.type === NodeTypes.IF ? node.branches : node.type === NodeTypes.ELEMENT || node.type === NodeTypes.IF_BRANCH || node.type === NodeTypes.FOR ? node.children : node.type === NodeTypes.TEXT || node.type === NodeTypes.COMMENT || node.type === NodeTypes.COMPOUND_EXPRESSION || node.type === NodeTypes.TEXT_CALL || node.type === NodeTypes.INTERPOLATION ? [] : exhaustiveCheckReturnUndefined(node) ?? [] return [...current, ...children.flatMap(getComponents)] } function getDirectiveNames(node: TemplateChildNode): string[] { if (node.type === NodeTypes.ELEMENT) { const directives = node.props.flatMap(x => x.type === NodeTypes.DIRECTIVE ? [x.name] : [], ) return [...directives, ...node.children.flatMap(getDirectiveNames)] } else if (node.type === NodeTypes.IF) { return node.branches.flatMap(getDirectiveNames) } else if (node.type === NodeTypes.IF_BRANCH || node.type === NodeTypes.FOR) { return node.children.flatMap(getDirectiveNames) } else if ( node.type === NodeTypes.INTERPOLATION || node.type === NodeTypes.COMPOUND_EXPRESSION || node.type === NodeTypes.TEXT || node.type === NodeTypes.COMMENT || node.type === NodeTypes.TEXT_CALL ) { return [] } else { exhaustiveCheckReturnUndefined(node) return [] } } function getFreeVariablesForText(input: string): string[] { const identifiers = new Set<string>() const inputWithPrefix = input.trimStart()[0] === '{' ? `(${input})` : input const nodes = parse(inputWithPrefix).program.body nodes.forEach(node => getIdentifierUsages(node, identifiers)) return [...identifiers.values()] } function getFreeVariablesForPropsNode( node: AttributeNode | DirectiveNode, ): string[] { if (node.type === NodeTypes.DIRECTIVE) { const arg = node.arg === undefined ? [] : getFreeVariablesForNode(node.arg) const exp = node.exp === undefined ? [] : getFreeVariablesForNode(node.exp) return [...arg, ...exp] } return [] } function getFreeVariablesForNode( node: TemplateChildNode | ExpressionNode, ): string[] { if (node.type === NodeTypes.SIMPLE_EXPRESSION) { return node.isStatic ? [] : getFreeVariablesForText(node.content) } else if (node.type === NodeTypes.COMPOUND_EXPRESSION) { return node.children.flatMap(x => typeof x !== 'object' ? [] : getFreeVariablesForNode(x), ) } else if (node.type === NodeTypes.INTERPOLATION) { return getFreeVariablesForNode(node.content) } else if (node.type === NodeTypes.ELEMENT) { const children = node.children.flatMap(getFreeVariablesForNode) const directiveProps = node.props .flatMap(x => x.type === NodeTypes.DIRECTIVE ? [x] : [], ) const attributeProps = node.props .flatMap(x => x.type === NodeTypes.ATTRIBUTE ? [x] : [], ) const refNode = attributeProps.find(node => node.name === 'ref' && node.value !== undefined) const refIdentifier = refNode?.value?.content const vSlotNode = directiveProps.find(node => node.name === 'slot') const vSlotArgIdentifiers = vSlotNode?.arg === undefined ? [] : getFreeVariablesForNode(vSlotNode.arg) // TODO: Variable shadowing const vSlotExpVariableShadowingIdentifiers: string[] = [] const vForNode = directiveProps.find(node => node.name === 'for') const vForIdentifiers = vForNode?.exp?.type === NodeTypes.SIMPLE_EXPRESSION ? getFreeVariablesForText(vForNode.exp.content.replace(/^.*\s(?:in|of)\s/, '')) : [] // TODO: Variable shadowing const vForExpVariableShadowingIdentifiers: string[] = [] const props = directiveProps .filter(({ name }) => name !== 'slot' && name !== 'for') .flatMap(getFreeVariablesForPropsNode) const shadowingIdentifiers = new Set([...vSlotExpVariableShadowingIdentifiers, ...vForExpVariableShadowingIdentifiers]) return [ ...vSlotArgIdentifiers, refIdentifier, ...vForIdentifiers, ...([...children, ...props]).filter(x => !shadowingIdentifiers.has(x)), ].filter(isNotNil) } else if (node.type === NodeTypes.FOR) { // If we use `baseCompiler`, we need add variable shadowing here // But we use `baseParse` now. So this branch will never be reached. // `NodeTypes.IF` and `NodeTypes.IF_BRANCH` will never be reached, also. // eslint-disable-next-line @typescript-eslint/no-unused-vars const { keyAlias, valueAlias } = node return [node.source, ...node.children].flatMap(getFreeVariablesForNode) } else if (node.type === NodeTypes.IF) { return (node.branches ?? []).flatMap(getFreeVariablesForNode) } else if (node.type === NodeTypes.IF_BRANCH) { return [node.condition, ...node.children] .filter(isNotNil) .flatMap(getFreeVariablesForNode) } else if (node.type === NodeTypes.TEXT || node.type === NodeTypes.COMMENT || node.type === NodeTypes.TEXT_CALL) { return [] } else { exhaustiveCheckReturnUndefined(node) return [] } } export function findReferencesForSFC(code: string) { const rootNode = baseParse(code, parserOptions) const templateChildNodes = rootNode.children.flatMap(node => node.type === NodeTypes.ELEMENT && node.tagType === ElementTypes.ELEMENT ? [node] : [], ) const templateNode = templateChildNodes.find( ({ tag }) => tag === 'template', ) const components = templateNode?.children.flatMap(getComponents) ?? [] const directives = templateNode?.children.flatMap(getDirectiveNames) ?? [] const identifiers = templateNode?.children.flatMap(getFreeVariablesForNode) ?? [] return { components, directives, identifiers, } } const htmlParserOptions: HTMLParserOptions = { xmlMode: true, lowerCaseTags: false, lowerCaseAttributeNames: false, recognizeSelfClosing: true, } export function parseSFC( code: string, id?: string, options?: ScriptSetupTransformOptions, ): ParsedSFC { let templateLevel = 0 let inScriptSetup = false let inScript = false const striped = code .replace(multilineCommentsRE, r => ' '.repeat(r.length)) .replace(singlelineCommentsRE, r => ' '.repeat(r.length)) const scriptSetup: ScriptTagMeta = { start: 0, end: 0, contentStart: 0, contentEnd: 0, content: '', attrs: {}, found: false, ast: undefined!, } const script: ScriptTagMeta = { start: 0, end: 0, contentStart: 0, contentEnd: 0, content: '', attrs: {}, found: false, ast: undefined!, } let templateStart: number | undefined let templateEnd: number | undefined let templateLang: 'html' | 'pug' = 'html' const parser = new HTMLParser( { onopentag(name, attributes) { if (!name) return if (name === 'template') { if (templateLevel === 0) { templateStart = parser.endIndex! + 1 if (attributes.lang === 'pug') templateLang = 'pug' } templateLevel += 1 } if (name === 'script') { if ('setup' in attributes) { scriptSetup.start = parser.startIndex scriptSetup.contentStart = parser.endIndex! + 1 scriptSetup.attrs = attributes scriptSetup.found = true inScriptSetup = true } else { script.start = parser.startIndex script.contentStart = parser.endIndex! + 1 script.attrs = attributes script.found = true inScript = true } } }, onclosetag(name) { if (name === 'template') { templateLevel -= 1 if (templateLevel === 0 && templateStart != null) templateEnd = parser.startIndex } if (inScriptSetup && name === 'script') { scriptSetup.end = parser.endIndex! + 1 scriptSetup.contentEnd = parser.startIndex scriptSetup.content = code.slice( scriptSetup.contentStart, scriptSetup.contentEnd, ) inScriptSetup = false } if (inScript && name === 'script') { script.end = parser.endIndex! + 1 script.contentEnd = parser.startIndex script.content = code.slice(script.contentStart, script.contentEnd) inScript = false } }, }, htmlParserOptions, ) parser.write(striped) parser.end() if ( script.found && scriptSetup.found && scriptSetup.attrs.lang !== script.attrs.lang ) { throw new SyntaxError( '<script setup> language must be the same as <script>', ) } const parserOptions: ParserOptions = { sourceType: 'module', plugins: [], } const lang = scriptSetup.attrs.lang || script.attrs.lang || 'js' if (lang === 'ts') parserOptions.plugins!.push('typescript') else if (lang === 'jsx') parserOptions.plugins!.push('jsx') else if (lang === 'tsx') parserOptions.plugins!.push('typescript', 'jsx') else if (lang !== 'js') throw new SyntaxError(`Unsupported script language: ${lang}`) scriptSetup.ast = parse(scriptSetup.content, parserOptions).program script.ast = parse(script.content || '', parserOptions).program scriptSetup.ast = options?.astTransforms?.scriptSetup?.(scriptSetup.ast) || scriptSetup.ast script.ast = options?.astTransforms?.script?.(script.ast) || script.ast const codeOfTemplate = (() => { if (templateStart == null || templateEnd == null) return undefined const templateCode = code.slice(templateStart, templateEnd) const html = templateLang === 'html' ? templateCode // eslint-disable-next-line @typescript-eslint/no-var-requires : require('pug').compile(templateCode, { filename: id })() return `<template>\n${html}\n</template>` })() const a = codeOfTemplate ? findReferencesForSFC(codeOfTemplate) : undefined return { id, template: { components: new Set(a?.components.map(pascalize)), directives: new Set(a?.directives.filter(x => !BUILD_IN_DIRECTIVES.has(x)).map(camelize)), identifiers: new Set(a?.identifiers), }, scriptSetup, script, parserOptions, extraDeclarations: [], } }
the_stack
import '@material/mwc-icon'; import { MobxLitElement } from '@adobe/lit-mobx'; import { css, customElement, html } from 'lit-element'; import { repeat } from 'lit-html/directives/repeat'; import { styleMap } from 'lit-html/directives/style-map'; import { computed, observable } from 'mobx'; import '../../expandable_entry'; import '../../copy_to_clipboard'; import './result_entry'; import { AppState, consumeAppState } from '../../../context/app_state'; import { GA_ACTIONS, GA_CATEGORIES, generateRandomLabel, trackEvent } from '../../../libs/analytics_utils'; import { VARIANT_STATUS_CLASS_MAP, VARIANT_STATUS_ICON_MAP } from '../../../libs/constants'; import { lazyRendering, RenderPlaceHolder } from '../../../libs/observer_element'; import { sanitizeHTML } from '../../../libs/sanitize_html'; import { TestVariant, TestVariantStatus } from '../../../services/resultdb'; import colorClasses from '../../../styles/color_classes.css'; import commonStyle from '../../../styles/common_style.css'; // This list defines the order in which variant def keys should be displayed. // Any unrecognized keys will be listed after the ones defined below. const ORDERED_VARIANT_DEF_KEYS = Object.freeze(['bucket', 'builder', 'test_suite']); // Only track test variants with unexpected, non-exonerated test results. const TRACKED_STATUS = [TestVariantStatus.UNEXPECTED, TestVariantStatus.UNEXPECTEDLY_SKIPPED, TestVariantStatus.FLAKY]; /** * Renders an expandable entry of the given test variant. */ @customElement('milo-test-variant-entry') @lazyRendering export class TestVariantEntryElement extends MobxLitElement implements RenderPlaceHolder { @observable.ref @consumeAppState() appState!: AppState; @observable.ref variant!: TestVariant; @observable.ref columnGetters: Array<(v: TestVariant) => unknown> = []; @observable.ref private _expanded = false; @computed get expanded() { return this._expanded; } set expanded(newVal: boolean) { this._expanded = newVal; // Always render the content once it was expanded so the descendants' states // don't get reset after the node is collapsed. this.shouldRenderContent = this.shouldRenderContent || newVal; if (newVal) { trackEvent(GA_CATEGORIES.TEST_RESULTS_TAB, GA_ACTIONS.EXPAND_ENTRY, VISIT_ID, 1); } } @observable.ref private shouldRenderContent = false; private rendered = false; @computed private get shortName() { if (this.variant.testMetadata?.name) { return this.variant.testMetadata.name; } // Generate a good enough short name base on the test ID. const suffix = this.variant.testId.match(/^.*[./]([^./]*?.{40})$/); if (suffix) { return '...' + suffix[1]; } return this.variant.testId; } @computed private get longName() { if (this.variant.testMetadata?.name) { return this.variant.testMetadata.name; } return this.variant.testId; } private genTestLink() { const location = window.location; const query = new URLSearchParams(location.search); query.set('q', `ExactID:${this.variant.testId} VHash:${this.variant.variantHash}`); return `${location.protocol}//${location.host}${location.pathname}?${query}`; } @computed private get sourceUrl() { const testLocation = this.variant.testMetadata?.location; if (!testLocation) { return null; } return ( testLocation.repo + '/+/HEAD' + testLocation.fileName.slice(1) + (testLocation.line ? '#' + testLocation.line : '') ); } @computed private get hasSingleChild() { return (this.variant.results?.length ?? 0) + (this.variant.exonerations?.length ?? 0) === 1; } @computed private get variantDef() { const def = this.variant!.variant?.def || {}; const res: Array<[string, string]> = []; const seen = new Set(); for (const key of ORDERED_VARIANT_DEF_KEYS) { if (Object.prototype.hasOwnProperty.call(def, key)) { res.push([key, def[key]]); seen.add(key); } } for (const [key, value] of Object.entries(def)) { if (!seen.has(key)) { res.push([key, value]); } } return res; } @computed private get expandedResultIndex() { // If there's only a single result, just expand it (even if it passed). if (this.hasSingleChild) { return 0; } // Otherwise expand the first failed result, or -1 if there aren't any. return this.variant.results?.findIndex((e) => !e.result.expected) ?? -1; } @computed get columnValues() { return this.columnGetters.map((fn) => fn(this.variant)); } private trackInteraction = () => { if (TRACKED_STATUS.includes(this.variant.status)) { trackEvent(GA_CATEGORIES.TEST_VARIANT_WITH_UNEXPECTED_RESULTS, GA_ACTIONS.INSPECT_TEST, VISIT_ID); } }; connectedCallback() { super.connectedCallback(); this.addEventListener('click', this.trackInteraction); } disconnectedCallback() { this.removeEventListener('click', this.trackInteraction); super.disconnectedCallback(); } private renderBody() { if (!this.shouldRenderContent) { return html``; } return html` <div id="basic-info"> <a href=${this.sourceUrl} target="_blank" style=${styleMap({ display: this.sourceUrl ? '' : 'none' })} >source</a > ${this.sourceUrl ? '|' : ''} <div id="test-id"> <span class="greyed-out" title=${this.variant.testId}>ID: ${this.variant.testId}</span> <milo-copy-to-clipboard .textToCopy=${this.variant.testId} @click=${(e: Event) => { e.stopPropagation(); this.trackInteraction(); }} title="copy test ID to clipboard" ></milo-copy-to-clipboard> </div> ${this.variantDef.length !== 0 ? '|' : ''} <span class="greyed-out"> ${this.variantDef.map( ([k, v]) => html` <span class="kv"> <span class="kv-key">${k}</span> <span class="kv-value">${v}</span> </span> ` )} </span> </div> ${repeat( this.variant.exonerations || [], (e) => e.exonerationId, (e) => html` <div class="explanation-html"> ${sanitizeHTML( e.explanationHtml || 'This test variant had unexpected results, but was exonerated (reason not provided).' )} </div> ` )} ${repeat( this.variant.results || [], (r) => r.result.resultId, (r, i) => html` <milo-result-entry .id=${i + 1} .testResult=${r.result} .expanded=${i === this.expandedResultIndex} ></milo-result-entry> ` )} `; } renderPlaceHolder() { return ''; } protected render() { this.rendered = true; return html` <milo-expandable-entry .expanded=${this.expanded} .onToggle=${(expanded: boolean) => (this.expanded = expanded)}> <div id="header" slot="header"> <mwc-icon class=${VARIANT_STATUS_CLASS_MAP[this.variant.status]}> ${VARIANT_STATUS_ICON_MAP[this.variant.status]} </mwc-icon> ${this.columnValues.map((v) => html`<div title=${v}>${v}</div>`)} <div id="test-name"> <span title=${this.longName}>${this.shortName}</span> <milo-copy-to-clipboard .textToCopy=${this.longName} @click=${(e: Event) => { e.stopPropagation(); this.trackInteraction(); }} title="copy test name to clipboard" ></milo-copy-to-clipboard> <milo-copy-to-clipboard id="link-copy-button" .textToCopy=${() => this.genTestLink()} @click=${(e: Event) => { e.stopPropagation(); this.trackInteraction(); }} title="copy link to the test" > <mwc-icon slot="copy-icon">link</mwc-icon> </milo-copy-to-clipboard> </div> </div> <div id="body" slot="content">${this.renderBody()}</div> </milo-expandable-entry> `; } protected updated() { if (!this.rendered || this.appState.sentTestResultsTabLoadingTimeToGA) { return; } this.appState.sentTestResultsTabLoadingTimeToGA = true; trackEvent( GA_CATEGORIES.TEST_RESULTS_TAB, GA_ACTIONS.LOADING_TIME, generateRandomLabel(VISIT_ID + '_'), Date.now() - this.appState.tabSelectionTime ); } static styles = [ commonStyle, colorClasses, css` :host { display: block; min-height: 24px; } #header { display: grid; grid-template-columns: 24px var(--columns) 1fr; grid-gap: 5px; font-size: 16px; line-height: 24px; } #header > * { overflow: hidden; text-overflow: ellipsis; } #test-name { display: flex; font-size: 16px; line-height: 24px; } #test-name > span { overflow: hidden; text-overflow: ellipsis; } #body { overflow: hidden; } #basic-info { font-weight: 500; line-height: 24px; margin-left: 5px; } #test-id { display: inline-flex; max-width: 300px; overflow: hidden; white-space: nowrap; } #test-id > span { display: inline-block; overflow: hidden; text-overflow: ellipsis; } .kv-key::after { content: ':'; } .kv-value::after { content: ','; } .kv:last-child > .kv-value::after { content: ''; } #def-table { margin-left: 29px; } .greyed-out { color: var(--greyed-out-text-color); } .explanation-html { background-color: var(--block-background-color); padding: 5px; } milo-copy-to-clipboard { flex: 0 0 16px; margin-left: 2px; display: none; } :hover > milo-copy-to-clipboard { display: inline-block; } `, ]; }
the_stack
import { MetadataUtils } from '../../core/model/element-metadata-utils' import { ElementInstanceMetadata, ElementInstanceMetadataMap, } from '../../core/shared/element-template' import { ElementPath } from '../../core/shared/project-file-types' import { KeyCharacter } from '../../utils/keyboard' import Utils from '../../utils/utils' import { CanvasPoint, CanvasRectangle, rectangleIntersection, canvasRectangle, } from '../../core/shared/math-utils' import { EditorAction } from '../editor/action-types' import * as EditorActions from '../editor/actions/action-creators' import { DerivedState, EditorState } from '../editor/store/editor-state' import * as EP from '../../core/shared/element-path' export enum TargetSearchType { ParentsOfSelected = 'ParentsOfSelected', SiblingsOfSelected = 'SiblingsOfSelected', ChildrenOfSelected = 'ChildrenOfSelected', SelectedElements = 'SelectedElements', TopLevelElements = 'TopLevelElements', All = 'all', } type FrameWithPath = { path: ElementPath frame: CanvasRectangle } const Canvas = { parentsAndSiblings: [ TargetSearchType.SelectedElements, TargetSearchType.SiblingsOfSelected, TargetSearchType.ParentsOfSelected, ], parentsSiblingsAndChildren: [ TargetSearchType.ChildrenOfSelected, TargetSearchType.SelectedElements, TargetSearchType.SiblingsOfSelected, TargetSearchType.ParentsOfSelected, ], getFramesInCanvasContext( metadata: ElementInstanceMetadataMap, useBoundingFrames: boolean, ): Array<FrameWithPath> { function recurseChildren( component: ElementInstanceMetadata, ): { boundingRect: CanvasRectangle | null; frames: Array<FrameWithPath> } { const globalFrame = component.globalFrame if (globalFrame == null) { return { boundingRect: null, frames: [], } } const overflows = MetadataUtils.overflows(component) const includeClippedNext = useBoundingFrames && overflows const { children, unfurledComponents, } = MetadataUtils.getAllChildrenElementsIncludingUnfurledFocusedComponents( component.elementPath, metadata, ) const childFrames = children.map((child) => { const recurseResults = recurseChildren(child) const rectToBoundWith = includeClippedNext ? recurseResults.boundingRect : globalFrame return { boundingRect: rectToBoundWith, frames: recurseResults.frames } }) const unfurledFrames = unfurledComponents.map((unfurledElement) => { const recurseResults = recurseChildren(unfurledElement) const rectToBoundWith = includeClippedNext ? recurseResults.boundingRect : globalFrame return { boundingRect: rectToBoundWith, frames: recurseResults.frames } }) const allFrames = [...childFrames, ...unfurledFrames] const allChildrenBounds = Utils.boundingRectangleArray(Utils.pluck(allFrames, 'boundingRect')) if (allFrames.length > 0 && allChildrenBounds != null) { const allChildrenFrames = Utils.pluck(allFrames, 'frames').flat() const boundingRect = Utils.boundingRectangle(globalFrame, allChildrenBounds) const toAppend: FrameWithPath = { path: component.elementPath, frame: boundingRect } return { boundingRect: boundingRect, frames: [toAppend].concat(allChildrenFrames), } } else { const boundingRect = globalFrame const toAppend = { path: component.elementPath, frame: boundingRect } return { boundingRect: boundingRect, frames: [toAppend] } } } const storyboardChildren = MetadataUtils.getAllStoryboardChildren(metadata) return storyboardChildren.flatMap((storyboardChild) => { return recurseChildren(storyboardChild).frames }) }, jumpToParent(selectedViews: Array<ElementPath>): ElementPath | 'CLEAR' | null { switch (selectedViews.length) { case 0: // Nothing is selected, so do nothing. return null case 1: // Only a single element is selected... const parentPath = EP.parentPath(selectedViews[0]) if (parentPath == null) { // ...the selected element is a top level one, so deselect. return 'CLEAR' } else { // ...the selected element has a parent, so select that. return parentPath } default: // Multiple elements are selected so select the topmost element amongst them. const newSelection: ElementPath | null = selectedViews.reduce( (working: ElementPath | null, selectedView) => { if (working == null) { return selectedView } else { if (EP.depth(selectedView) < EP.depth(working)) { return selectedView } else { return working } } }, null, ) return Utils.forceNotNull('Internal Error.', newSelection) } }, jumpToSibling( selectedViews: Array<ElementPath>, components: ElementInstanceMetadataMap, forwards: boolean, ): ElementPath | null { switch (selectedViews.length) { case 0: return null case 1: const singleSelectedElement = selectedViews[0] const siblings = MetadataUtils.getSiblings(components, singleSelectedElement) const pathsToStep = siblings.map((s) => s.elementPath) return Utils.stepInArray( EP.pathsEqual, forwards ? 1 : -1, pathsToStep, singleSelectedElement, ) default: // Multiple elements are selected so select the topmost element amongst them. const newSelection: ElementPath | null = selectedViews.reduce( (working: ElementPath | null, selectedView) => { if (working == null) { return selectedView } else { if (EP.depth(selectedView) < EP.depth(working)) { return selectedView } else { return working } } }, null, ) return Utils.forceNotNull('Internal Error.', newSelection) } }, getFirstChild( selectedViews: Array<ElementPath>, components: ElementInstanceMetadataMap, ): ElementPath | null { if (selectedViews.length !== 1) { return null } else { const children = MetadataUtils.getImmediateChildren(components, selectedViews[0]) return children.length > 0 ? children[0].elementPath : null } }, targetFilter( selectedViews: Array<ElementPath>, searchTypes: Array<TargetSearchType>, ): Array<(path: ElementPath) => boolean> { return searchTypes.map((searchType) => { switch (searchType) { case TargetSearchType.ParentsOfSelected: return (path: ElementPath) => { for (const selectedView of selectedViews) { if (EP.isDescendantOfOrEqualTo(selectedView, path)) { return true } } return false } case TargetSearchType.ChildrenOfSelected: return (path: ElementPath) => { for (const selectedView of selectedViews) { if (EP.isChildOf(path, selectedView)) { return true } } return false } case TargetSearchType.SiblingsOfSelected: return (path: ElementPath) => { for (const selectedView of selectedViews) { if (EP.isSiblingOf(selectedView, path) && !EP.containsPath(path, selectedViews)) { return true } } return false } case TargetSearchType.TopLevelElements: return (path: ElementPath) => { // TODO Scene Implementation if (EP.depth(path) === 2) { return true } return false } case TargetSearchType.SelectedElements: return (path: ElementPath) => { if (EP.containsPath(path, selectedViews)) { return true } return false } case TargetSearchType.All: return (path: ElementPath) => { return true } default: const _exhaustiveCheck: never = searchType throw new Error(`Unknown search type ${JSON.stringify(searchType)}`) } }) }, getAllTargetsAtPoint( componentMetadata: ElementInstanceMetadataMap, selectedViews: Array<ElementPath>, hiddenInstances: Array<ElementPath>, canvasPosition: CanvasPoint, searchTypes: Array<TargetSearchType>, useBoundingFrames: boolean, looseTargetingForZeroSizedElements: 'strict' | 'loose', ): Array<{ elementPath: ElementPath; canBeFilteredOut: boolean }> { const looseReparentThreshold = 5 const targetFilters = Canvas.targetFilter(selectedViews, searchTypes) const framesWithPaths = Canvas.getFramesInCanvasContext(componentMetadata, useBoundingFrames) const filteredFrames = framesWithPaths.filter((frameWithPath) => { const shouldUseLooseTargeting = looseTargetingForZeroSizedElements === 'loose' && (frameWithPath.frame.width <= 0 || frameWithPath.frame.height <= 0) return targetFilters.some((filter) => filter(frameWithPath.path)) && !hiddenInstances.some((hidden) => EP.isDescendantOfOrEqualTo(frameWithPath.path, hidden)) && shouldUseLooseTargeting ? rectangleIntersection( canvasRectangle({ x: frameWithPath.frame.x, y: frameWithPath.frame.y, width: frameWithPath.frame.width ?? 1, height: frameWithPath.frame.height ?? 1, }), canvasRectangle({ x: canvasPosition.x - looseReparentThreshold, y: canvasPosition.y - looseReparentThreshold, width: 2 * looseReparentThreshold, height: 2 * looseReparentThreshold, }), ) != null : Utils.rectContainsPoint(frameWithPath.frame, canvasPosition) }) filteredFrames.reverse() const targets = filteredFrames.map((filteredFrame) => { const zeroSized = filteredFrame.frame.width === 0 || filteredFrame.frame.height === 0 return { elementPath: filteredFrame.path, canBeFilteredOut: !zeroSized, } }) return targets }, getNextTarget(current: Array<ElementPath>, targetStack: Array<ElementPath>): ElementPath | null { if (current.length <= 1) { const currentIndex = current.length === 0 ? -1 : targetStack.findIndex((target) => EP.pathsEqual(target, current[0])) const endOrNotFound = currentIndex === -1 || currentIndex === targetStack.length - 1 if (endOrNotFound) { return targetStack[0] } else { return targetStack[currentIndex + 1] } } else { return null } }, handleKeyUp(key: KeyCharacter, editor: EditorState, derived: DerivedState): Array<EditorAction> { switch (key) { case 'z': return [EditorActions.setHighlightsEnabled(true)] default: return [] } }, } export default Canvas
the_stack
import zlib from "zlib"; import { IClient } from "../IClient"; import { EventEmitter } from "events"; import { Watcher } from "../Watcher"; import { BasicClient } from "../BasicClient"; import { Ticker } from "../Ticker"; import { Trade } from "../Trade"; import { Level2Point } from "../Level2Point"; import { Level2Snapshot } from "../Level2Snapshots"; import { Candle } from "../Candle"; import { SubscriptionType } from "../SubscriptionType"; import { CandlePeriod } from "../CandlePeriod"; import { throttle } from "../flowcontrol/Throttle"; import { wait } from "../Util"; import { Market } from "../Market"; import { CancelableFn } from "../flowcontrol/Fn"; import { NotImplementedAsyncFn, NotImplementedFn } from "../NotImplementedFn"; export type BatchedClient = IClient & { parent?: IClient; subCount?: number; }; export class BiboxClient extends EventEmitter implements IClient { public readonly throttleMs: number; public readonly timeoutMs: number; public readonly subsPerClient: number; public readonly options: any; public readonly hasTickers: boolean; public readonly hasTrades: boolean; public readonly hasCandles: boolean; public readonly hasLevel2Snapshots: boolean; public readonly hasLevel2Updates: boolean; public readonly hasLevel3Snapshots: boolean; public readonly hasLevel3Updates: boolean; public candlePeriod: CandlePeriod; protected _subClients: Map<string, BiboxBasicClient>; protected _clients: BiboxBasicClient[]; protected _subscribe: CancelableFn; public subscribeLevel2Updates = NotImplementedFn; public unsubscribeLevel2Updates = NotImplementedAsyncFn; public subscribeLevel3Snapshots = NotImplementedFn; public unsubscribeLevel3Snapshots = NotImplementedAsyncFn; public subscribeLevel3Updates = NotImplementedFn; public unsubscribeLevel3Updates = NotImplementedFn; /** Bibox allows listening to multiple markets on the same socket. Unfortunately, they throw errors if you subscribe to too more than 20 markets at a time re: https://github.com/Biboxcom/API_Docs_en/wiki/WS_request#1-access-to-the-url This makes like hard and we need to batch connections, which is why we can't use the BasicMultiClient. */ constructor(options?: any) { super(); /** Stores the client used for each subscription request with teh key: remoteId_subType The value is the underlying client that is used. */ this._subClients = new Map(); /** List of all active clients. Clients will be removed when all subscriptions have vanished. */ this._clients = []; this.options = options; this.hasTickers = true; this.hasTrades = true; this.hasCandles = true; this.hasLevel2Snapshots = true; this.hasLevel2Updates = false; this.hasLevel3Snapshots = false; this.hasLevel3Updates = false; this.subsPerClient = 20; this.throttleMs = 200; this._subscribe = throttle(this.__subscribe.bind(this), this.throttleMs); this.candlePeriod = CandlePeriod._1m; } public subscribeTicker(market: Market) { this._subscribe(market, SubscriptionType.ticker); } public async unsubscribeTicker(market) { this._unsubscribe(market, SubscriptionType.ticker); } public subscribeTrades(market) { this._subscribe(market, SubscriptionType.trade); } public unsubscribeTrades(market) { this._unsubscribe(market, SubscriptionType.trade); } public subscribeCandles(market) { this._subscribe(market, SubscriptionType.candle); } public async unsubscribeCandles(market) { this._unsubscribe(market, SubscriptionType.candle); } public async subscribeLevel2Snapshots(market) { this._subscribe(market, SubscriptionType.level2snapshot); } public async unsubscribeLevel2Snapshots(market) { this._unsubscribe(market, SubscriptionType.level2snapshot); } public close() { this._subscribe.cancel(); for (const client of this._clients) { client.close(); } } public async reconnect() { for (const client of this._clients) { client.reconnect(); await wait(this.timeoutMs); } } protected __subscribe(market: Market, subscriptionType: SubscriptionType) { // construct the subscription key from the remote_id and the type // of subscription being performed const subKey = market.id + "_" + subscriptionType; // try to find the subscription client from the existing lookup let client = this._subClients.get(subKey); // if we haven't seen this market sub before first try // to find an available existing client if (!client) { // first try to find a client that has less than 20 subscriptions... client = this._clients.find(p => p.subCount < this.subsPerClient); // make sure we set the value this._subClients.set(subKey, client); } // if we were unable to find any avaialble clients, we will need // to create a new client. if (!client) { // construct a new client client = new BiboxBasicClient(this.options); // set properties client.parent = this; // wire up the events to pass through client.on("connecting", () => this.emit("connecting", market, subscriptionType)); client.on("connected", () => this.emit("connected", market, subscriptionType)); client.on("disconnected", () => this.emit("disconnected", market, subscriptionType)); client.on("reconnecting", () => this.emit("reconnecting", market, subscriptionType)); client.on("closing", () => this.emit("closing", market, subscriptionType)); client.on("closed", () => this.emit("closed", market, subscriptionType)); client.on("ticker", (ticker, market) => this.emit("ticker", ticker, market)); client.on("trade", (trade, market) => this.emit("trade", trade, market)); client.on("candle", (candle, market) => this.emit("candle", candle, market)); client.on("l2snapshot", (l2snapshot, market) => this.emit("l2snapshot", l2snapshot, market), ); client.on("error", err => this.emit("error", err)); // push it into the list of clients this._clients.push(client); // make sure we set the value this._subClients.set(subKey, client); } // now that we have a client, call the sub method, which // should be an idempotent method, so no harm in calling it again switch (subscriptionType) { case SubscriptionType.ticker: client.subscribeTicker(market); break; case SubscriptionType.trade: client.subscribeTrades(market); break; case SubscriptionType.candle: client.subscribeCandles(market); break; case SubscriptionType.level2snapshot: client.subscribeLevel2Snapshots(market); break; } } protected _unsubscribe(market: Market, subscriptionType: SubscriptionType) { // construct the subscription key from the remote_id and the type // of subscription being performed const subKey = market.id + "_" + subscriptionType; // find the client const client = this._subClients.get(subKey); // abort if nothign to do if (!client) return; // perform the unsubscribe operation switch (subscriptionType) { case SubscriptionType.ticker: client.unsubscribeTicker(market); break; case SubscriptionType.trade: client.unsubscribeTrades(market); break; case SubscriptionType.candle: client.unsubscribeCandles(market); break; case SubscriptionType.level2snapshot: client.unsubscribeLevel2Snapshots(market); break; } // remove the client if nothing left to do if (client.subCount === 0) { client.close(); const idx = this._clients.indexOf(client); this._clients.splice(idx, 1); } } } export class BiboxBasicClient extends BasicClient { public subCount: number; public parent: BiboxClient; protected _sendSubLevel2Updates = NotImplementedFn; protected _sendUnsubLevel2Updates = NotImplementedAsyncFn; protected _sendSubLevel3Snapshots = NotImplementedFn; protected _sendUnsubLevel3Snapshots = NotImplementedAsyncFn; protected _sendSubLevel3Updates = NotImplementedFn; protected _sendUnsubLevel3Updates = NotImplementedAsyncFn; /** Manages connections for a single market. A single socket is only allowed to work for 20 markets. */ constructor({ wssPath = "wss://push.bibox.com", watcherMs = 600 * 1000 } = {}) { super(wssPath, "Bibox"); this._watcher = new Watcher(this, watcherMs); this.hasTickers = true; this.hasTrades = true; this.hasCandles = true; this.hasLevel2Snapshots = true; this.subCount = 0; } public get candlePeriod(): CandlePeriod { return this.parent.candlePeriod; } /** Server will occassionally send ping messages. Client is expected to respond with a pong message that matches the identifier. If client fails to do this, server will abort connection after second attempt. */ protected _sendPong(id) { this._wss.send(JSON.stringify({ pong: id })); } protected _sendSubTicker(remote_id: string) { this.subCount++; this._wss.send( JSON.stringify({ event: "addChannel", channel: `bibox_sub_spot_${remote_id}_ticker`, }), ); } protected async _sendUnsubTicker(remote_id: string) { this.subCount--; this._wss.send( JSON.stringify({ event: "removeChannel", channel: `bibox_sub_spot_${remote_id}_ticker`, }), ); } protected async _sendSubTrades(remote_id: string) { this.subCount++; this._wss.send( JSON.stringify({ event: "addChannel", channel: `bibox_sub_spot_${remote_id}_deals`, }), ); } protected _sendUnsubTrades(remote_id: string) { this.subCount--; this._wss.send( JSON.stringify({ event: "removeChannel", channel: `bibox_sub_spot_${remote_id}_deals`, }), ); } protected _sendSubCandles(remote_id) { this.subCount++; this._wss.send( JSON.stringify({ event: "addChannel", channel: `bibox_sub_spot_${remote_id}_kline_${candlePeriod(this.candlePeriod)}`, }), ); } protected async _sendUnsubCandles(remote_id) { this.subCount--; this._wss.send( JSON.stringify({ event: "removeChannel", channel: `bibox_sub_spot_${remote_id}_kline_${candlePeriod(this.candlePeriod)}`, }), ); } protected async _sendSubLevel2Snapshots(remote_id) { this.subCount++; this._wss.send( JSON.stringify({ event: "addChannel", channel: `bibox_sub_spot_${remote_id}_depth`, }), ); } protected async _sendUnsubLevel2Snapshots(remote_id) { this.subCount--; this._wss.send( JSON.stringify({ event: "removeChannel", channel: `bibox_sub_spot_${remote_id}_depth`, }), ); } /** Message usually arives as a string, that must first be converted to JSON. Then we can process each message in the payload and perform gunzip on the data. */ protected _onMessage(raw: any) { const msgs = typeof raw == "string" ? JSON.parse(raw) : raw; if (Array.isArray(msgs)) { for (const msg of msgs) { this._processsMessage(msg); } } else { this._processsMessage(msgs); } } /** Process the individaul message that was sent from the server. Message will be informat: { channel: 'bibox_sub_spot_BTC_USDT_deals', binary: '1', data_type: 1, data: 'H4sIAAAAAAAA/xTLMQ6CUAyA4bv8c0Ne4RWeHdUbiJMxhghDB5QgTsa7Gw/wXT4sQ6w4+/5wO5+OPcIW84SrWdPtsllbrAjLGvcJJ6cmVZoNYZif78eGo1UqjSK8YvxLIUa8bjWnrtbyvf4CAAD//1PFt6BnAAAA' } */ protected _processsMessage(msg: any) { // if we detect gzip data, we need to process it if (msg.binary == 1) { const buffer = zlib.gunzipSync(Buffer.from(msg.data, "base64")); msg.data = JSON.parse(buffer.toString()); } // server will occassionally send a ping message and client // must respon with appropriate identifier if (msg.ping) { this._sendPong(msg.ping); return; } // watch for error messages if (msg.error) { const err = new Error(msg.error); err.message = msg; this.emit("error", err); return; } if (!msg.channel) { return; } if (msg.channel.endsWith("_deals")) { // trades are send in descendinging order // out library standardize to asc order so perform a reverse const data = msg.data.slice().reverse(); for (const datum of data) { const market = this._tradeSubs.get(datum.pair); if (!market) return; const trade = this._constructTradesFromMessage(datum, market); this.emit("trade", trade, market); } return; } // tickers if (msg.channel.endsWith("_ticker")) { const market = this._tickerSubs.get(msg.data.pair); if (!market) return; const ticker = this._constructTicker(msg, market); this.emit("ticker", ticker, market); return; } // l2 updates if (msg.channel.endsWith("depth")) { const remote_id = msg.data.pair; const market = this._level2SnapshotSubs.get(remote_id) || this._level2UpdateSubs.get(remote_id); if (!market) return; const snapshot = this._constructLevel2Snapshot(msg, market); this.emit("l2snapshot", snapshot, market); return; } // candle if (msg.channel.endsWith(`kline_${candlePeriod(this.candlePeriod)}`)) { // bibox_sub_spot_BTC_USDT_kline_1min const remote_id = msg.channel .replace("bibox_sub_spot_", "") .replace(`_kline_${candlePeriod(this.candlePeriod)}`, ""); const market = this._candleSubs.get(remote_id); if (!market) return; for (const datum of msg.data) { const candle = this._constructCandle(datum); this.emit("candle", candle, market); } } } /* Constructs a ticker from the source { channel: 'bibox_sub_spot_BIX_BTC_ticker', binary: 1, data_type: 1, data: { last: '0.00003573', buy: '0.00003554', sell: '0.00003589', base_last_cny: '0.86774973', last_cny: '0.86', buy_amount: '6.1867', percent: '-1.68%', pair: 'BIX_BTC', high: '0.00003700', vol: '737995', last_usd: '0.12', low: '0.00003535', sell_amount: '880.0475', timestamp: 1547546988399 } } */ protected _constructTicker(msg: any, market: Market) { let { last, buy, sell, vol, percent, low, high, timestamp } = msg.data; percent = percent.replace(/%|\+/g, ""); const change = (parseFloat(last) * parseFloat(percent)) / 100; const open = parseFloat(last) - change; return new Ticker({ exchange: "Bibox", base: market.base, quote: market.quote, timestamp, last, open: open.toFixed(8), high: high, low: low, volume: vol, change: change.toFixed(8), changePercent: percent, bid: buy, ask: sell, }); } /* Construct a trade { channel: 'bibox_sub_spot_BIX_BTC_deals', binary: '1', data_type: 1, data: [ { pair: 'BIX_BTC', time: 1547544945204, price: 0.0000359, amount: 6.1281, side: 2, id: 189765713 } ] } */ protected _constructTradesFromMessage(datum: any, market: Market) { let { time, price, amount, side, id } = datum; side = side === 1 ? "buy" : "sell"; return new Trade({ exchange: "Bibox", base: market.base, quote: market.quote, tradeId: id, side, unix: time, price, amount, }); } /** { channel: 'bibox_sub_spot_BTC_USDT_kline_1min', binary: 1, data_type: 1, data: [ { time: 1597259460000, open: '11521.38000000', high: '11540.58990000', low: '11521.28990000', close: '11540.56990000', vol: '11.24330000' }, { time: 1597259520000, open: '11540.55990000', high: '11540.58990000', low: '11533.13000000', close: '11536.83990000', vol: '10.88200000' } ] } */ protected _constructCandle(datum: any) { return new Candle(datum.time, datum.open, datum.high, datum.low, datum.close, datum.vol); } /* Converts from a raw message { "binary": 0, "channel": "ok_sub_spot_bch_btc_depth", "data": { update_time: 1547549824601, asks: [ { volume: '433.588', price: '0.00003575' }, { volume: '1265.6753', price: '0.00003576' }, .. { volume: '69.5745', price: '0.000041' }, { volume: '5.277', price: '0.00004169' }, ... 100 more items ], bids: [ { volume: '6.1607', price: '0.00003571' }, { volume: '704.8954', price: '0.00003538' }, .. { volume: '155000', price: '2e-8' }, { volume: '8010000', price: '1e-8' } ], pair: 'BIX_BTC' } } */ protected _constructLevel2Snapshot(msg: any, market: Market) { const asks = msg.data.asks.map(p => new Level2Point(p.price, p.volume)); const bids = msg.data.bids.map(p => new Level2Point(p.price, p.volume)); return new Level2Snapshot({ exchange: "Bibox", base: market.base, quote: market.quote, timestampMs: msg.data.update_time, asks, bids, }); } } function candlePeriod(period) { switch (period) { case CandlePeriod._1m: return "1min"; case CandlePeriod._5m: return "5min"; case CandlePeriod._15m: return "15min"; case CandlePeriod._30m: return "30min"; case CandlePeriod._1h: return "1hour"; case CandlePeriod._2h: return "2hour"; case CandlePeriod._4h: return "4hour"; case CandlePeriod._6h: return "6hour"; case CandlePeriod._12h: return "12hour"; case CandlePeriod._1d: return "day"; case CandlePeriod._1w: return "week"; } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsdyn_orderlinetransaction_Project_Information { interface tab__8C79EFB9_B8BB_4A4A_B617_0CE1C5C65186_Sections { AmountSection: DevKit.Controls.Section; BillingSection: DevKit.Controls.Section; DateSection: DevKit.Controls.Section; GeneralSection: DevKit.Controls.Section; ProductResourceSection: DevKit.Controls.Section; ProjectSection: DevKit.Controls.Section; QuantitySection: DevKit.Controls.Section; VendorSection: DevKit.Controls.Section; } interface tab_SummaryTab_Sections { SummaryTab_section_2: DevKit.Controls.Section; SummaryTab_section_3: DevKit.Controls.Section; tab_2_section_1: DevKit.Controls.Section; } interface tab__8C79EFB9_B8BB_4A4A_B617_0CE1C5C65186 extends DevKit.Controls.ITab { Section: tab__8C79EFB9_B8BB_4A4A_B617_0CE1C5C65186_Sections; } interface tab_SummaryTab extends DevKit.Controls.ITab { Section: tab_SummaryTab_Sections; } interface Tabs { _8C79EFB9_B8BB_4A4A_B617_0CE1C5C65186: tab__8C79EFB9_B8BB_4A4A_B617_0CE1C5C65186; SummaryTab: tab_SummaryTab; } interface Body { Tab: Tabs; /** Select the customer who this contract belongs to. */ msdyn_AccountCustomer: DevKit.Controls.Lookup; msdyn_AccountVendor: DevKit.Controls.Lookup; /** Enter the amount on the project contract line estimate. */ msdyn_Amount: DevKit.Controls.Money; /** Enter the amount on the project contract line estimate. */ msdyn_Amount_1: DevKit.Controls.Money; msdyn_amount_after_tax: DevKit.Controls.Money; /** Select the amount calculation method used for this project contract estimate line. Valid values are: 0: Multiply Quantity By Price 1: Fixed Price 2: Multiply Basis Quantity By Price 3: Multiply Basis Amount By Percent */ msdyn_AmountMethod: DevKit.Controls.OptionSet; msdyn_BasisAmount: DevKit.Controls.Money; msdyn_BasisQuantity: DevKit.Controls.Decimal; /** Select whether this project contract line estimate will be charged to the customer or not. Only chargeable project contract line estimates will add to the invoice total */ msdyn_BillingType: DevKit.Controls.OptionSet; /** Select whether this project contract line estimate will be charged to the customer or not. Only chargeable project contract line estimates will add to the invoice total */ msdyn_BillingType_1: DevKit.Controls.OptionSet; /** Shows the resource. */ msdyn_bookableresource: DevKit.Controls.Lookup; /** Select the customer contact of this Project Contract. */ msdyn_ContactCustomer: DevKit.Controls.Lookup; msdyn_ContactVendor: DevKit.Controls.Lookup; /** Select whether the customer was a account or a contact */ msdyn_CustomerType: DevKit.Controls.OptionSet; /** Type a description of the project contract line estimate */ msdyn_description: DevKit.Controls.String; /** Type a description of the project contract line estimate */ msdyn_description_1: DevKit.Controls.String; /** Enter the document date. */ msdyn_DocumentDate: DevKit.Controls.Date; /** Enter the end date on the project contract line estimate. */ msdyn_EndDateTime: DevKit.Controls.Date; /** Enter the end date on the project contract line estimate. */ msdyn_EndDateTime_1: DevKit.Controls.Date; /** Foreign key to the detail line that originated this entry. For example, revenue line points to it's related cost line. */ msdyn_Origin: DevKit.Controls.Lookup; /** Relevant when amount calculation method on the Project Contract line transactions is "Multiply basis amount by percent" */ msdyn_Percent: DevKit.Controls.Decimal; /** Enter the price on the project contract line estimate. */ msdyn_Price: DevKit.Controls.Money; /** Enter the price on the project contract line estimate. */ msdyn_Price_1: DevKit.Controls.Money; /** Select the price list used for defaulting price on this project contract line estimate. */ msdyn_PriceList: DevKit.Controls.Lookup; /** Select the price list used for defaulting price on this project contract line estimate. */ msdyn_PriceList_1: DevKit.Controls.Lookup; /** Select the product on this project contract line estimate. */ msdyn_Product: DevKit.Controls.Lookup; /** Select the name of the project on the project contract estimate line. */ msdyn_Project: DevKit.Controls.Lookup; /** Enter the quantity of the project contract line estimate. */ msdyn_Quantity: DevKit.Controls.Decimal; /** Enter the quantity of the project contract line estimate. */ msdyn_Quantity_1: DevKit.Controls.Decimal; /** Select the name of the role that is estimated to perform this work. */ msdyn_ResourceCategory: DevKit.Controls.Lookup; /** Select the name of the role that is estimated to perform this work. */ msdyn_ResourceCategory_1: DevKit.Controls.Lookup; /** Select the organizational unit of the resource who is estimated to perform the work. */ msdyn_ResourceOrganizationalUnitId: DevKit.Controls.Lookup; /** Select the project contract that this estimate line is for. */ msdyn_SalesContract: DevKit.Controls.Lookup; /** Select the project contract that this estimate line is for. */ msdyn_SalesContract_1: DevKit.Controls.Lookup; /** Unique identifier for Project Contract Line associated with Project Contract Line Detail. */ msdyn_SalesContractLineId: DevKit.Controls.Lookup; /** Enter the estimate start date of the portion of work that is being estimated on the project contract estimate line. */ msdyn_StartDateTime: DevKit.Controls.Date; /** Enter the estimate start date of the portion of work that is being estimated on the project contract estimate line. */ msdyn_StartDateTime_1: DevKit.Controls.Date; /** Select the name of the work breakdown structure (WBS) task on the project contract line estimate. */ msdyn_Task: DevKit.Controls.Lookup; msdyn_tax: DevKit.Controls.Money; /** Select the transaction category on the project contract line estimate. */ msdyn_TransactionCategory: DevKit.Controls.Lookup; /** Select the transaction category on the project contract line estimate. */ msdyn_TransactionCategory_1: DevKit.Controls.Lookup; /** Transaction classification of the Project Contract line transaction */ msdyn_TransactionClassification: DevKit.Controls.OptionSet; /** Transaction classification of the Project Contract line transaction */ msdyn_TransactionClassification_1: DevKit.Controls.OptionSet; /** Transaction type of the Project Contract line transaction */ msdyn_TransactionTypeCode: DevKit.Controls.OptionSet; /** Transaction type of the Project Contract line transaction */ msdyn_TransactionTypeCode_1: DevKit.Controls.OptionSet; /** Select the unit on the project contract line estimate. */ msdyn_Unit: DevKit.Controls.Lookup; /** Select the unit on the project contract line estimate. */ msdyn_Unit_1: DevKit.Controls.Lookup; /** Select the unit schedule of the project contract line estimate. */ msdyn_UnitSchedule: DevKit.Controls.Lookup; msdyn_VendorType: DevKit.Controls.OptionSet; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Shows the currency associated with the entity. */ TransactionCurrencyId: DevKit.Controls.Lookup; } } class Formmsdyn_orderlinetransaction_Project_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_orderlinetransaction_Project_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form msdyn_orderlinetransaction_Project_Information */ Body: DevKit.Formmsdyn_orderlinetransaction_Project_Information.Body; } namespace Formmsdyn_orderlinetransaction_Project_Quick_Create { interface tab_tab_1_Sections { tab_1_column_1_section_1: DevKit.Controls.Section; tab_1_column_2_section_1: DevKit.Controls.Section; tab_1_column_3_section_1: DevKit.Controls.Section; } interface tab_tab_1 extends DevKit.Controls.ITab { Section: tab_tab_1_Sections; } interface Tabs { tab_1: tab_tab_1; } interface Body { Tab: Tabs; /** Enter the amount on the project contract line estimate. */ msdyn_Amount: DevKit.Controls.Money; /** Type a description of the project contract line estimate */ msdyn_description: DevKit.Controls.String; /** Enter the end date on the project contract line estimate. */ msdyn_EndDateTime: DevKit.Controls.Date; /** Enter the price on the project contract line estimate. */ msdyn_Price: DevKit.Controls.Money; /** Enter the quantity of the project contract line estimate. */ msdyn_Quantity: DevKit.Controls.Decimal; /** Select the name of the role that is estimated to perform this work. */ msdyn_ResourceCategory: DevKit.Controls.Lookup; /** Select the organizational unit of the resource who is estimated to perform the work. */ msdyn_ResourceOrganizationalUnitId: DevKit.Controls.Lookup; /** Select the project contract that this estimate line is for. */ msdyn_SalesContract: DevKit.Controls.Lookup; /** Enter the estimate start date of the portion of work that is being estimated on the project contract estimate line. */ msdyn_StartDateTime: DevKit.Controls.Date; msdyn_tax: DevKit.Controls.Money; /** Select the transaction category on the project contract line estimate. */ msdyn_TransactionCategory: DevKit.Controls.Lookup; /** Transaction classification of the Project Contract line transaction */ msdyn_TransactionClassification: DevKit.Controls.OptionSet; /** Transaction type of the Project Contract line transaction */ msdyn_TransactionTypeCode: DevKit.Controls.OptionSet; /** Select the unit on the project contract line estimate. */ msdyn_Unit: DevKit.Controls.Lookup; /** Select the unit schedule of the project contract line estimate. */ msdyn_UnitSchedule: DevKit.Controls.Lookup; } } class Formmsdyn_orderlinetransaction_Project_Quick_Create extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_orderlinetransaction_Project_Quick_Create * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form msdyn_orderlinetransaction_Project_Quick_Create */ Body: DevKit.Formmsdyn_orderlinetransaction_Project_Quick_Create.Body; } class msdyn_orderlinetransactionApi { /** * DynamicsCrm.DevKit msdyn_orderlinetransactionApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Exchange rate for the currency associated with the entity with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Select the customer who this contract belongs to. */ msdyn_AccountCustomer: DevKit.WebApi.LookupValue; msdyn_AccountingDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; msdyn_AccountVendor: DevKit.WebApi.LookupValue; /** Enter the amount on the project contract line estimate. */ msdyn_Amount: DevKit.WebApi.MoneyValue; msdyn_amount_after_tax: DevKit.WebApi.MoneyValueReadonly; /** Value of the amount_after_tax in base currency. */ msdyn_amount_after_tax_Base: DevKit.WebApi.MoneyValueReadonly; /** Value of the Amount in base currency. */ msdyn_amount_Base: DevKit.WebApi.MoneyValueReadonly; /** Select the amount calculation method used for this project contract estimate line. Valid values are: 0: Multiply Quantity By Price 1: Fixed Price 2: Multiply Basis Quantity By Price 3: Multiply Basis Amount By Percent */ msdyn_AmountMethod: DevKit.WebApi.OptionSetValue; msdyn_BasisAmount: DevKit.WebApi.MoneyValue; /** Value of the Basis Amount in base currency. */ msdyn_basisamount_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_BasisPrice: DevKit.WebApi.MoneyValue; /** Value of the Basis Price in base currency. */ msdyn_basisprice_Base: DevKit.WebApi.MoneyValueReadonly; msdyn_BasisQuantity: DevKit.WebApi.DecimalValue; /** Select whether this project contract line estimate will be charged to the customer or not. Only chargeable project contract line estimates will add to the invoice total */ msdyn_BillingType: DevKit.WebApi.OptionSetValue; /** Shows the resource. */ msdyn_bookableresource: DevKit.WebApi.LookupValue; /** Select the customer contact of this Project Contract. */ msdyn_ContactCustomer: DevKit.WebApi.LookupValue; msdyn_ContactVendor: DevKit.WebApi.LookupValue; /** Select whether the customer was a account or a contact */ msdyn_CustomerType: DevKit.WebApi.OptionSetValue; /** Type a description of the project contract line estimate */ msdyn_description: DevKit.WebApi.StringValue; /** Enter the document date. */ msdyn_DocumentDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the end date on the project contract line estimate. */ msdyn_EndDateTime_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; msdyn_ExchangeRateDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Shows the project contract line that this estimate line belongs to. */ msdyn_orderlinetransactionId: DevKit.WebApi.GuidValue; /** Foreign key to the detail line that originated this entry. For example, revenue line points to it's related cost line. */ msdyn_Origin: DevKit.WebApi.LookupValue; /** Relevant when amount calculation method on the Project Contract line transactions is "Multiply basis amount by percent" */ msdyn_Percent: DevKit.WebApi.DecimalValue; /** Enter the price on the project contract line estimate. */ msdyn_Price: DevKit.WebApi.MoneyValue; /** Value of the Price in base currency. */ msdyn_price_Base: DevKit.WebApi.MoneyValueReadonly; /** Select the price list used for defaulting price on this project contract line estimate. */ msdyn_PriceList: DevKit.WebApi.LookupValue; /** Select the product on this project contract line estimate. */ msdyn_Product: DevKit.WebApi.LookupValue; /** Select the name of the project on the project contract estimate line. */ msdyn_Project: DevKit.WebApi.LookupValue; /** Enter the quantity of the project contract line estimate. */ msdyn_Quantity: DevKit.WebApi.DecimalValue; /** Unique identifier for Quote Line Detail that Order Line Detail is created from. */ msdyn_QuoteLineTransactionId: DevKit.WebApi.LookupValue; /** Select the name of the role that is estimated to perform this work. */ msdyn_ResourceCategory: DevKit.WebApi.LookupValue; /** Select the organizational unit of the resource who is estimated to perform the work. */ msdyn_ResourceOrganizationalUnitId: DevKit.WebApi.LookupValue; /** Select the project contract that this estimate line is for. */ msdyn_SalesContract: DevKit.WebApi.LookupValue; /** (Deprecated) Shows the project contract line that this project contract line estimate will be mapped to for operating margin calculations. */ msdyn_SalesContractLine: DevKit.WebApi.StringValue; /** Unique identifier for Project Contract Line associated with Project Contract Line Detail. */ msdyn_SalesContractLineId: DevKit.WebApi.LookupValue; /** Enter the estimate start date of the portion of work that is being estimated on the project contract estimate line. */ msdyn_StartDateTime_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Select the name of the work breakdown structure (WBS) task on the project contract line estimate. */ msdyn_Task: DevKit.WebApi.LookupValue; msdyn_tax: DevKit.WebApi.MoneyValue; /** Value of the tax in base currency. */ msdyn_tax_Base: DevKit.WebApi.MoneyValueReadonly; /** Select the transaction category on the project contract line estimate. */ msdyn_TransactionCategory: DevKit.WebApi.LookupValue; /** Transaction classification of the Project Contract line transaction */ msdyn_TransactionClassification: DevKit.WebApi.OptionSetValue; /** Transaction type of the Project Contract line transaction */ msdyn_TransactionTypeCode: DevKit.WebApi.OptionSetValue; /** Select the unit on the project contract line estimate. */ msdyn_Unit: DevKit.WebApi.LookupValue; /** Select the unit schedule of the project contract line estimate. */ msdyn_UnitSchedule: DevKit.WebApi.LookupValue; msdyn_VendorType: DevKit.WebApi.OptionSetValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Status of the Estimate Details */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the Estimate Details */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Shows the currency associated with the entity. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyn_orderlinetransaction { enum msdyn_AmountMethod { /** 192350001 */ Fixed_Price, /** 192350003 */ Multiply_Basis_Amount_By_Percent, /** 192350002 */ Multiply_Basis_Quantity_By_Price, /** 192350000 */ Multiply_Quantity_By_Price, /** 690970000 */ Tax_Calculation } enum msdyn_BillingType { /** 192350001 */ Chargeable, /** 192350002 */ Complimentary, /** 192350000 */ Non_Chargeable, /** 192350003 */ Not_Available } enum msdyn_CustomerType { /** 192350001 */ Account, /** 192350002 */ Contact } enum msdyn_TransactionClassification { /** 690970001 */ Additional, /** 690970000 */ Commission, /** 192350001 */ Expense, /** 192350004 */ Fee, /** 192350002 */ Material, /** 192350003 */ Milestone, /** 690970002 */ Tax, /** 192350000 */ Time } enum msdyn_TransactionTypeCode { /** 192350006 */ Billed_Sales, /** 192350000 */ Cost, /** 192350008 */ Inter_Organizational_Sales, /** 192350004 */ Project_Contract, /** 192350007 */ Resourcing_Unit_Cost, /** 192350005 */ Unbilled_Sales } enum msdyn_VendorType { /** 192350001 */ Account, /** 192350002 */ Contact } enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Project Information','Quick Create'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { Matrix } from './Matrix' import { FloatArray, Epsilon } from './types' import { Scalar } from './Scalar' /** @public */ export type ReadOnlyVector2 = { readonly x: number readonly y: number } /** * Class representing a vector containing 2 coordinates * @public */ export class Vector2 { /** * Creates a new Vector2 from the given x and y coordinates * @param x - defines the first coordinate * @param y - defines the second coordinate */ constructor( /** defines the first coordinate */ public x: number = 0, /** defines the second coordinate */ public y: number = 0 ) {} /** * Gets a new Vector2(0, 0) * @returns a new Vector2 */ public static Zero(): Vector2 { return new Vector2(0, 0) } /** * Gets a new Vector2(1, 1) * @returns a new Vector2 */ public static One(): Vector2 { return new Vector2(1, 1) } /** * Returns a new Vector2 as the result of the addition of the two given vectors. * @param vector1 - the first vector * @param vector2 - the second vector * @returns the resulting vector */ public static Add(vector1: ReadOnlyVector2, vector2: ReadOnlyVector2): Vector2 { return new Vector2(vector1.x, vector1.y).addInPlace(vector2) } /** * Gets a new Vector2 set from the given index element of the given array * @param array - defines the data source * @param offset - defines the offset in the data source * @returns a new Vector2 */ public static FromArray(array: ArrayLike<number>, offset: number = 0): Vector2 { return new Vector2(array[offset], array[offset + 1]) } /** * Sets "result" from the given index element of the given array * @param array - defines the data source * @param offset - defines the offset in the data source * @param result - defines the target vector */ public static FromArrayToRef(array: ArrayLike<number>, offset: number, result: Vector2): void { result.x = array[offset] result.y = array[offset + 1] } /** * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2 * @param value1 - defines 1st point of control * @param value2 - defines 2nd point of control * @param value3 - defines 3rd point of control * @param value4 - defines 4th point of control * @param amount - defines the interpolation factor * @returns a new Vector2 */ public static CatmullRom( value1: ReadOnlyVector2, value2: ReadOnlyVector2, value3: ReadOnlyVector2, value4: ReadOnlyVector2, amount: number ): Vector2 { let squared = amount * amount let cubed = amount * squared let x = 0.5 * (2.0 * value2.x + (-value1.x + value3.x) * amount + (2.0 * value1.x - 5.0 * value2.x + 4.0 * value3.x - value4.x) * squared + (-value1.x + 3.0 * value2.x - 3.0 * value3.x + value4.x) * cubed) let y = 0.5 * (2.0 * value2.y + (-value1.y + value3.y) * amount + (2.0 * value1.y - 5.0 * value2.y + 4.0 * value3.y - value4.y) * squared + (-value1.y + 3.0 * value2.y - 3.0 * value3.y + value4.y) * cubed) return new Vector2(x, y) } /** * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max". * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate * @param value - defines the value to clamp * @param min - defines the lower limit * @param max - defines the upper limit * @returns a new Vector2 */ public static Clamp(value: ReadOnlyVector2, min: ReadOnlyVector2, max: ReadOnlyVector2): Vector2 { let x = value.x x = x > max.x ? max.x : x x = x < min.x ? min.x : x let y = value.y y = y > max.y ? max.y : y y = y < min.y ? min.y : y return new Vector2(x, y) } /** * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2" * @param value1 - defines the 1st control point * @param tangent1 - defines the outgoing tangent * @param value2 - defines the 2nd control point * @param tangent2 - defines the incoming tangent * @param amount - defines the interpolation factor * @returns a new Vector2 */ public static Hermite( value1: ReadOnlyVector2, tangent1: ReadOnlyVector2, value2: ReadOnlyVector2, tangent2: ReadOnlyVector2, amount: number ): Vector2 { let squared = amount * amount let cubed = amount * squared let part1 = 2.0 * cubed - 3.0 * squared + 1.0 let part2 = -2.0 * cubed + 3.0 * squared let part3 = cubed - 2.0 * squared + amount let part4 = cubed - squared let x = value1.x * part1 + value2.x * part2 + tangent1.x * part3 + tangent2.x * part4 let y = value1.y * part1 + value2.y * part2 + tangent1.y * part3 + tangent2.y * part4 return new Vector2(x, y) } /** * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end". * @param start - defines the start vector * @param end - defines the end vector * @param amount - defines the interpolation factor * @returns a new Vector2 */ public static Lerp(start: ReadOnlyVector2, end: ReadOnlyVector2, amount: number): Vector2 { let x = start.x + (end.x - start.x) * amount let y = start.y + (end.y - start.y) * amount return new Vector2(x, y) } /** * Gets the dot product of the vector "left" and the vector "right" * @param left - defines first vector * @param right - defines second vector * @returns the dot product (float) */ public static Dot(left: ReadOnlyVector2, right: ReadOnlyVector2): number { return left.x * right.x + left.y * right.y } /** * Returns a new Vector2 equal to the normalized given vector * @param vector - defines the vector to normalize * @returns a new Vector2 */ public static Normalize(vector: ReadOnlyVector2): Vector2 { let newVector = new Vector2(vector.x, vector.y) newVector.normalize() return newVector } /** * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors * @param left - defines 1st vector * @param right - defines 2nd vector * @returns a new Vector2 */ public static Minimize(left: ReadOnlyVector2, right: ReadOnlyVector2): Vector2 { let x = left.x < right.x ? left.x : right.x let y = left.y < right.y ? left.y : right.y return new Vector2(x, y) } /** * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors * @param left - defines 1st vector * @param right - defines 2nd vector * @returns a new Vector2 */ public static Maximize(left: ReadOnlyVector2, right: ReadOnlyVector2): Vector2 { let x = left.x > right.x ? left.x : right.x let y = left.y > right.y ? left.y : right.y return new Vector2(x, y) } /** * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix * @param vector - defines the vector to transform * @param transformation - defines the matrix to apply * @returns a new Vector2 */ public static Transform(vector: Vector2, transformation: Matrix): Vector2 { let r = Vector2.Zero() Vector2.TransformToRef(vector, transformation, r) return r } /** * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates * @param vector - defines the vector to transform * @param transformation - defines the matrix to apply * @param result - defines the target vector */ public static TransformToRef(vector: ReadOnlyVector2, transformation: Matrix, result: Vector2) { const m = transformation.m let x = vector.x * m[0] + vector.y * m[4] + m[12] let y = vector.x * m[1] + vector.y * m[5] + m[13] result.x = x result.y = y } /** * Determines if a given vector is included in a triangle * @param p - defines the vector to test * @param p0 - defines 1st triangle point * @param p1 - defines 2nd triangle point * @param p2 - defines 3rd triangle point * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2" */ public static PointInTriangle(p: ReadOnlyVector2, p0: ReadOnlyVector2, p1: ReadOnlyVector2, p2: ReadOnlyVector2) { let a = (1 / 2) * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y) let sign = a < 0 ? -1 : 1 let s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign let t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign return s > 0 && t > 0 && s + t < 2 * a * sign } /** * Gets the distance between the vectors "value1" and "value2" * @param value1 - defines first vector * @param value2 - defines second vector * @returns the distance between vectors */ public static Distance(value1: Vector2, value2: Vector2): number { return Math.sqrt(Vector2.DistanceSquared(value1, value2)) } /** * Returns the squared distance between the vectors "value1" and "value2" * @param value1 - defines first vector * @param value2 - defines second vector * @returns the squared distance between vectors */ public static DistanceSquared(value1: ReadOnlyVector2, value2: ReadOnlyVector2): number { let x = value1.x - value2.x let y = value1.y - value2.y return x * x + y * y } /** * Gets a new Vector2 located at the center of the vectors "value1" and "value2" * @param value1 - defines first vector * @param value2 - defines second vector * @returns a new Vector2 */ public static Center(value1: ReadOnlyVector2, value2: ReadOnlyVector2): Vector2 { let center = Vector2.Add(value1, value2) center.scaleInPlace(0.5) return center } /** * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB". * @param p - defines the middle point * @param segA - defines one point of the segment * @param segB - defines the other point of the segment * @returns the shortest distance */ public static DistanceOfPointFromSegment(p: Vector2, segA: Vector2, segB: Vector2): number { let l2 = Vector2.DistanceSquared(segA, segB) if (l2 === 0.0) { return Vector2.Distance(p, segA) } let v = segB.subtract(segA) let t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2)) let proj = segA.add(v.multiplyByFloats(t, t)) return Vector2.Distance(p, proj) } /** * Gets a string with the Vector2 coordinates * @returns a string with the Vector2 coordinates */ public toString(): string { return '{X: ' + this.x + ' Y:' + this.y + '}' } /** * Gets class name * @returns the string "Vector2" */ public getClassName(): string { return 'Vector2' } /** * Gets current vector hash code * @returns the Vector2 hash code as a number */ public getHashCode(): number { let hash = this.x || 0 hash = (hash * 397) ^ (this.y || 0) return hash } // Operators /** * Sets the Vector2 coordinates in the given array or FloatArray from the given index. * @param array - defines the source array * @param index - defines the offset in source array * @returns the current Vector2 */ public toArray(array: FloatArray, index: number = 0): Vector2 { array[index] = this.x array[index + 1] = this.y return this } /** * Copy the current vector to an array * @returns a new array with 2 elements: the Vector2 coordinates. */ public asArray(): number[] { let result = new Array<number>() this.toArray(result, 0) return result } /** * Sets the Vector2 coordinates with the given Vector2 coordinates * @param source - defines the source Vector2 * @returns the current updated Vector2 */ public copyFrom(source: ReadOnlyVector2): Vector2 { this.x = source.x this.y = source.y return this } /** * Sets the Vector2 coordinates with the given floats * @param x - defines the first coordinate * @param y - defines the second coordinate * @returns the current updated Vector2 */ public copyFromFloats(x: number, y: number): Vector2 { this.x = x this.y = y return this } /** * Sets the Vector2 coordinates with the given floats * @param x - defines the first coordinate * @param y - defines the second coordinate * @returns the current updated Vector2 */ public set(x: number, y: number): Vector2 { return this.copyFromFloats(x, y) } /** * Add another vector with the current one * @param otherVector - defines the other vector * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates */ public add(otherVector: ReadOnlyVector2): Vector2 { return new Vector2(this.x + otherVector.x, this.y + otherVector.y) } /** * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates * @param otherVector - defines the other vector * @param result - defines the target vector * @returns the unmodified current Vector2 */ public addToRef(otherVector: ReadOnlyVector2, result: Vector2): Vector2 { result.x = this.x + otherVector.x result.y = this.y + otherVector.y return this } /** * Set the Vector2 coordinates by adding the given Vector2 coordinates * @param otherVector - defines the other vector * @returns the current updated Vector2 */ public addInPlace(otherVector: ReadOnlyVector2): Vector2 { this.x += otherVector.x this.y += otherVector.y return this } /** * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates * @param otherVector - defines the other vector * @returns a new Vector2 */ public addVector3(otherVector: ReadOnlyVector2): Vector2 { return new Vector2(this.x + otherVector.x, this.y + otherVector.y) } /** * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2 * @param otherVector - defines the other vector * @returns a new Vector2 */ public subtract(otherVector: ReadOnlyVector2): Vector2 { return new Vector2(this.x - otherVector.x, this.y - otherVector.y) } /** * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates. * @param otherVector - defines the other vector * @param result - defines the target vector * @returns the unmodified current Vector2 */ public subtractToRef(otherVector: ReadOnlyVector2, result: Vector2): Vector2 { result.x = this.x - otherVector.x result.y = this.y - otherVector.y return this } /** * Sets the current Vector2 coordinates by subtracting from it the given one coordinates * @param otherVector - defines the other vector * @returns the current updated Vector2 */ public subtractInPlace(otherVector: ReadOnlyVector2): Vector2 { this.x -= otherVector.x this.y -= otherVector.y return this } /** * Multiplies in place the current Vector2 coordinates by the given ones * @param otherVector - defines the other vector * @returns the current updated Vector2 */ public multiplyInPlace(otherVector: ReadOnlyVector2): Vector2 { this.x *= otherVector.x this.y *= otherVector.y return this } /** * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates * @param otherVector - defines the other vector * @returns a new Vector2 */ public multiply(otherVector: ReadOnlyVector2): Vector2 { return new Vector2(this.x * otherVector.x, this.y * otherVector.y) } /** * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates * @param otherVector - defines the other vector * @param result - defines the target vector * @returns the unmodified current Vector2 */ public multiplyToRef(otherVector: ReadOnlyVector2, result: Vector2): Vector2 { result.x = this.x * otherVector.x result.y = this.y * otherVector.y return this } /** * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats * @param x - defines the first coordinate * @param y - defines the second coordinate * @returns a new Vector2 */ public multiplyByFloats(x: number, y: number): Vector2 { return new Vector2(this.x * x, this.y * y) } /** * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates * @param otherVector - defines the other vector * @returns a new Vector2 */ public divide(otherVector: ReadOnlyVector2): Vector2 { return new Vector2(this.x / otherVector.x, this.y / otherVector.y) } /** * Sets the "result" coordinates with the Vector2 divided by the given one coordinates * @param otherVector - defines the other vector * @param result - defines the target vector * @returns the unmodified current Vector2 */ public divideToRef(otherVector: ReadOnlyVector2, result: Vector2): Vector2 { result.x = this.x / otherVector.x result.y = this.y / otherVector.y return this } /** * Divides the current Vector2 coordinates by the given ones * @param otherVector - defines the other vector * @returns the current updated Vector2 */ public divideInPlace(otherVector: ReadOnlyVector2): Vector2 { return this.divideToRef(otherVector, this) } /** * Gets a new Vector2 with current Vector2 negated coordinates * @returns a new Vector2 */ public negate(): Vector2 { return new Vector2(-this.x, -this.y) } /** * Multiply the Vector2 coordinates by scale * @param scale - defines the scaling factor * @returns the current updated Vector2 */ public scaleInPlace(scale: number): Vector2 { this.x *= scale this.y *= scale return this } /** * Returns a new Vector2 scaled by "scale" from the current Vector2 * @param scale - defines the scaling factor * @returns a new Vector2 */ public scale(scale: number): Vector2 { let result = new Vector2(0, 0) this.scaleToRef(scale, result) return result } /** * Scale the current Vector2 values by a factor to a given Vector2 * @param scale - defines the scale factor * @param result - defines the Vector2 object where to store the result * @returns the unmodified current Vector2 */ public scaleToRef(scale: number, result: Vector2): Vector2 { result.x = this.x * scale result.y = this.y * scale return this } /** * Scale the current Vector2 values by a factor and add the result to a given Vector2 * @param scale - defines the scale factor * @param result - defines the Vector2 object where to store the result * @returns the unmodified current Vector2 */ public scaleAndAddToRef(scale: number, result: Vector2): Vector2 { result.x += this.x * scale result.y += this.y * scale return this } /** * Gets a boolean if two vectors are equals * @param otherVector - defines the other vector * @returns true if the given vector coordinates strictly equal the current Vector2 ones */ public equals(otherVector: ReadOnlyVector2): boolean { return otherVector && this.x === otherVector.x && this.y === otherVector.y } /** * Gets a boolean if two vectors are equals (using an epsilon value) * @param otherVector - defines the other vector * @param epsilon - defines the minimal distance to consider equality * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon. */ public equalsWithEpsilon(otherVector: ReadOnlyVector2, epsilon: number = Epsilon): boolean { return ( otherVector && Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) ) } /** * Gets a new Vector2 from current Vector2 floored values * @returns a new Vector2 */ public floor(): Vector2 { return new Vector2(Math.floor(this.x), Math.floor(this.y)) } /** * Gets a new Vector2 from current Vector2 floored values * @returns a new Vector2 */ public fract(): Vector2 { return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y)) } // Properties /** * Gets the length of the vector * @returns the vector length (float) */ public length(): number { return Math.sqrt(this.x * this.x + this.y * this.y) } /** * Gets the vector squared length * @returns the vector squared length (float) */ public lengthSquared(): number { return this.x * this.x + this.y * this.y } // Methods /** * Normalize the vector * @returns the current updated Vector2 */ public normalize(): Vector2 { let len = this.length() if (len === 0) { return this } let num = 1.0 / len this.x *= num this.y *= num return this } /** * Gets a new Vector2 copied from the Vector2 * @returns a new Vector2 */ public clone(): Vector2 { return new Vector2(this.x, this.y) } }
the_stack
import Vue from 'vue'; import countBy from 'lodash/countBy'; import defaultsDeep from 'lodash/defaultsDeep'; import each from 'lodash/each'; import every from 'lodash/every'; import filter from 'lodash/filter'; import find from 'lodash/find'; import findIndex from 'lodash/findIndex'; import first from 'lodash/first'; import get from 'lodash/get'; import has from 'lodash/has'; import isArray from 'lodash/isArray'; import isEmpty from 'lodash/isEmpty'; import isFunction from 'lodash/isFunction'; import isNil from 'lodash/isNil'; import isObject from 'lodash/isObject'; import isPlainObject from 'lodash/isPlainObject'; import join from 'lodash/join'; import keyBy from 'lodash/keyBy'; import last from 'lodash/last'; import map from 'lodash/map'; import max from 'lodash/max'; import merge from 'lodash/merge'; import method from 'lodash/method'; import reduce from 'lodash/reduce'; import set from 'lodash/set'; import size from 'lodash/size'; import sortBy from 'lodash/sortBy'; import sumBy from 'lodash/sumBy'; import toSafeInteger from 'lodash/toSafeInteger'; import unset from 'lodash/unset'; import values from 'lodash/values'; import Base, {Options, RequestOperation} from './Base'; import Model, {ValidationResultErrorFinalResult} from './Model'; import ResponseError from '../Errors/ResponseError'; import ValidationError from '../Errors/ValidationError'; import ProxyResponse from '../HTTP/ProxyResponse'; import Response from '../HTTP/Response'; /** * Used as a marker to indicate that pagination is not enabled. */ const NO_PAGE = null; /** * Used as a marker to indicate that a collection has paged through all results. */ const LAST_PAGE = 0; /** * Base collection class. */ class Collection extends Base { models!: Model[]; readonly loading!: boolean; readonly saving!: boolean; readonly deleting!: boolean; readonly fatal!: boolean; private readonly _attributes!: Record<string, any>; private readonly _page!: number | null; private readonly _registry!: Record<string, string>; /** * Accessor to support Array.length semantics. */ get length(): number { return this.size(); } /** * Creates a new instance, called when using 'new'. * * @param {Array} [models] Models to add to this collection. * @param {Object} [options] Extra options to set on this collection. */ constructor(models: Model[] = [], options: Options = {}, attributes: Record<string, any> = {}) { super(options); Vue.set(this, 'models', []); // Model store. Vue.set(this, '_attributes', {}); // Property store. Vue.set(this, '_registry', {}); // Model registry. Vue.set(this, '_page', NO_PAGE); this.clearState(); // Set all given attributes. this.set(defaultsDeep({}, attributes, this.defaults())); // Add all given models (if any) to this collection. We explicitly ask // for the values here as it's common for some sources to be objects. if (models) { this.add(values(models)); } } /** * Creates a copy of this collection. Model references are preserved so * changes to the models inside the clone will also affect the subject. * * @returns {Collection} */ clone(): Collection { return new (this.constructor as typeof Collection) (this.getModels(), this.getOptions(), this.getAttributes()); } /** * @return {Model} The class/constructor for this collection's model type. */ model(): typeof Model { return this.getOption('model'); } /** * @return {Object} Default attributes */ defaults(): Record<string, any> { return {}; } /** * @return {*} The value of an attribute, or a given fallback if not set. */ get(attribute: string, fallback?: any): any { return get(this._attributes, attribute, fallback); } /** * Sets an attribute's value, or an object of attributes. * * @param {string|Object} attribute * @param {*} value */ // set<T>(attribute: string | Record<string, any>, value?: T): T | undefined set(attribute: string | Record<string, any>, value?: any): void { if (isPlainObject(attribute)) { each(attribute as Record<string, any>, (value, key): void => { this.set(key, value); }); return; } Vue.set(this._attributes, attribute as string, value); } /** * @return {Object} */ getAttributes(): Record<string, any> { return this._attributes; } /** * @return {Model[]} */ getModels(): Model[] { return this.models; } /** * Returns the default options for this model. * * @returns {Object} */ getDefaultOptions(): Options { return merge(super.getDefaultOptions(), { // The class/constructor for this collection's model type. model: Model, // Whether this collection should send model identifiers as JSON // in the body of a delete request, instead of a query parameter. useDeleteBody: true, }); } /** * @returns {Object} Parameters to use for replacement in route patterns. */ getRouteParameters(): Record<string, any> { return merge({}, super.getRouteParameters(), this._attributes, { page: this._page, }); } /** * Removes all errors from the models in this collection. */ clearErrors(): void { each(this.models, method('clearErrors')); } /** * Resets model state, ie. `loading`, etc back to their initial states. */ clearState(): void { Vue.set(this, 'loading', false); Vue.set(this, 'saving', false); Vue.set(this, 'deleting', false); Vue.set(this, 'fatal', false); } /** * Removes all models from this collection. */ clearModels(): void { let models: Model[] = this.models; // Clear the model store, but keep a reference. Vue.set(this, 'models', []); // Notify each model that it has been removed from this collection. each(models, (model: Model): void => { this.onRemove(model); }); } /** * Removes all models from this collection. */ clear(): void { this.clearModels(); this.clearState(); } /** * Syncs all models in this collection. This method delegates to each model * so follows the same signature and effects as `Model.sync`. */ sync(): void { each(this.models, method('sync')); } /** * Resets all models in this collection. This method delegates to each model * so follows the same signature and effects as `Model.reset`. * * @param {string|string[]} attribute */ reset(...attribute: string[]): void { each(this.models, method('reset', ...attribute)); } /** * Returns the number of models in this collection. */ size(): number { return size(this.models); } /** * @returns {boolean} `true` if the collection is empty, `false` otherwise. */ isEmpty(): boolean { return this.size() === 0; } /** * @returns {Object} A native representation of this collection that will * determine the contents of JSON.stringify(collection). */ toJSON(): Model[] { return this.models; } /** * @returns {Promise} */ validate(): Promise<(ValidationResultErrorFinalResult)[]> { let validations = this.models.map((model): Promise<ValidationResultErrorFinalResult> => model.validate()); return Promise.all(validations) .then((errors: ValidationResultErrorFinalResult[]): ValidationResultErrorFinalResult[] => { return every(errors, isEmpty) ? [] : errors; }); } /** * Create a new model of this collection's model type. * * @param {Object} attributes * * @returns {Model} A new instance of this collection's model. */ createModel(attributes: Record<string, any>): Record<string, any> { return new (this.model())(attributes); } /** * Removes a model from the model registry. * * @param {Model} model */ removeModelFromRegistry(model: Model): void { unset(this._registry, model._uid); } /** * @return {Boolean} true if this collection has the model in its registry. */ hasModelInRegistry(model: Model): boolean { return has(this._registry, model._uid); } /** * Adds a model from the model registry. * * @param {Model} model */ addModelToRegistry(model: Model): void { set(this._registry, model._uid, 1); } /** * Called when a model has been added to this collection. * * @param {Model} model */ onAdd(model: Model): void { model.registerCollection(this); this.addModelToRegistry(model); this.emit('add', {model}); } /** * Adds a model to this collection. * * This method returns a single model if only one was given, but will return * an array of all added models if an array was given. * * @param {Model|Array|Object} model Adds a model instance or plain object, * or an array of either, to this collection. * A model instance will be created and * returned if passed a plain object. * * @returns {Model|Array} The added model or array of added models. */ add(model: Model[]): Model[]; add(model?: Model | Partial<Model> | Record<string, any>): Model; add(model?: Model | Model[] | Partial<Model> | Record<string, any>): Model | Model[] | Partial<Model> | Record<string, any> | void { // If given an array, assume an array of models and add them all. if (isArray(model)) { return filter(map(model as Model[], this.add)); } // Objects should be converted to model instances first, then added. if (isPlainObject(model)) { return this.add(this.createModel(model as Partial<Model> | Record<string, any>)); } // This is also just to catch a potential bug. All models should have // an auto id so this would indicate an unexpected state. if (!this.isModel(model)) { throw new Error('Expected a model, plain object, or array of either'); } // Make sure we don't add the same model twice. if (this.hasModelInRegistry(model as Model)) { return; } // Add the model instance to this collection. this.models.push(model as Model); this.onAdd(model as Model); // We're assuming that the collection is not loading once a model is added. Vue.set(this, 'loading', false); return model; } /** * Called when a model has been removed from this collection. * * @param {Model} model */ onRemove(model: Model): void { model.unregisterCollection(this); this.removeModelFromRegistry(model); this.emit('remove', {model}); } /** * Removes a model at a given index. * * @param {number} index * @returns {Model} The model that was removed, or `undefined` if invalid. * @throws {Error} If a model could not be found at the given index. */ _removeModelAtIndex(index: number): Model | undefined { if (index < 0) { return; } let model: Model = get(this.models, index); Vue.delete(this.models, index); this.onRemove(model); return model; } /** * Removes a `Model` from this collection. * * @param {Model} model * * @return {Model} */ _removeModel(model: Model): Model | undefined { return this._removeModelAtIndex(this.indexOf(model)); } /** * Removes the given model from this collection. * * @param {Model|Object|Array} model Model to remove, which can be a `Model` * instance, an object to filter by, * a function to filter by, or an array * of any of the above to remove multiple. * * @return {Model|Model[]} The deleted model or an array of models if a filter * or array type was given. * * @throws {Error} If the model is an invalid type. */ remove(model: Model): Model; remove(model: Model[] | Partial<Model> | ((model: Model) => boolean)): Model[]; remove(model: Model | Model[] | Partial<Model> | ((model: Model) => boolean)): Model | Model[] | undefined { if (!model) { throw new Error('Expected function, object, array, or model to remove'); } // Support using a predicate to remove all models it returns true for. // Alternatively support an object of values to filter by. if (isFunction(model) || isPlainObject(model)) { return this.remove(filter(this.models, model)); } // Support removing multiple models at the same time if an array was // given. A model would otherwise always be an object so this is safe. if (isArray(model)) { return filter(map<Model, Model>(model, this.remove)); } // This is just to catch a potential bug. All models should have // an auto id here so this would indicate an unexpected state. if (!this.isModel(model)) { throw new Error('Model to remove is not a valid model'); } return this._removeModel(model as Model); } /** * Determines whether a given value is an instance of a model. * * @param {*} candidate A model candidate * * @return {boolean} `true` if the given `model` is an instance of Model. */ isModel(candidate: any): boolean { return isObject(candidate) && has(candidate, '_attributes') && has(candidate, '_uid'); } /** * Returns the zero-based index of the given model in this collection. * * @see {@link https://lodash.com/docs/#findIndex} * * @return {number} the index of a model in this collection, or -1 if not found. */ indexOf(model: Model): number { let filter: Model | { _uid: string } = model; // Getting the index of a model instance can be optimised. if (this.isModel(filter)) { // Constant time check, if the registry doesn't have a record of // the model, we know it's not in the collection. if (!has(this._registry, model._uid)) { return -1; } // There is no need to filter on the entire object, because the // unique ID of the model is all we need to identify it. filter = {_uid: model._uid}; } return findIndex(this.models, filter); } /** * @param {string|function|Object} where * * @return {Model} The first model that matches the given criteria, or * `undefined` if none could be found. * * @see {@link https://lodash.com/docs/#find} */ find(where: Predicate): Model | undefined { return find<Model>(this.models, where); } /** * Creates a new collection of the same type that contains only the models * for which the given predicate returns `true` for, or matches by property. * * @see {@link where} * * Important: Even though this returns a new collection, the references to * each model are preserved, so changes will propagate to both. * * @param {function|Object|string} predicate Receives `model`. * * @returns {Collection} */ filter(predicate: Predicate): Collection { let result: Collection = this.clone(); result.models = filter(result.models, predicate) as Model[]; return result; } /** * Returns the models for which the given predicate returns `true` for, * or models that match attributes in an object. * * @see {@link https://lodash.com/docs/#filter} * * @param {function|Object|string} predicate Receives `model`. * * @returns {Model[]} */ where(predicate: Predicate): Model[] { return filter<Model>(this.models, predicate); } /** * Returns an array that contains the returned result after applying a * function to each model in this collection. * * @see {@link https://lodash.com/docs/#map} * * @param {function} callback Receives `model`. * * @return {Model[]} */ map<T = Model>(callback: string | ((model: Model) => T)): T[] { return map<Model, T>(this.models, callback as _.ArrayIterator<Model, T>); } // TODO: as (string | _.ArrayIterator<Model, T>) /** * Iterates through all models, calling a given callback for each one. * * @see {@link https://lodash.com/docs/#each} * * @param {function} callback Receives `model` and `index`. */ each(callback: (model: Model) => void): void { return each(this.models, callback) as unknown as void; } /** * Reduces this collection to a value which is the accumulated result of * running each model through `iteratee`, where each successive invocation * is supplied the return value of the previous. * * If `initial` is not given, the first model of the collection is used * as the initial value. * * @param {function} iteratee Invoked with three arguments: * (result, model, index) * * @param {*} [initial] The initial value to use for the `result`. * * @returns {*} The final value of result, after the last iteration. */ reduce<U = Model>(iteratee: (result: U | undefined, model: Model, index: number) => U, initial?: U): U | undefined { // Use the first model as the initial value if an initial was not given. if (arguments.length === 1) { initial = this.first() as (U | undefined); } return reduce(this.models, iteratee, initial); } /** * @param {function|string} iteratee Attribute name or callback to determine * which values to sum by. Invoked with a * single argument `model`. * * @returns {number} Sum of all models, accessed by attribute or callback. */ sum(iteratee: ((model: Model) => number) | string): number { return sumBy(this.models, iteratee); } /** * Returns an object composed of keys generated from the results of running * each model through `iteratee`. The corresponding value of each key is the * number of times the key was returned by iteratee. * * @see {@link https://lodash.com/docs/#countBy} * * @returns {Object} */ count(iteratee: (model: Model) => any): Record<string, number> { return countBy(this.models, iteratee); } /** * Sorts this collection's models using a comparator. This method performs * a stable sort (it preserves the original sort order of equal elements). * * @see {@link https://lodash.com/docs/#sortBy} * * @param {function|string} comparator Attribute name or attribute function, * invoked with a single arg `model`. */ sort(comparator: ((model: Model) => any) | string): void { Vue.set(this, 'models', sortBy(this.models, comparator)); } /** * @param {Model|Object} model * * @returns {boolean} `true` if this collection contains the given model, * `false` otherwise. */ has(model: Model): boolean { return this.indexOf(model) >= 0; } /** * @returns {Model|undefined} The first model of this collection. */ first(): Model | undefined { return first(this.models); } /** * @returns {Model|undefined} The last model of this collection. */ last(): Model | undefined { return last(this.models); } /** * Removes and returns the first model of this collection, if there was one. * * @returns {Model|undefined} Removed model or undefined if there were none. */ shift(): Model | undefined { if (!this.isEmpty()) { return this._removeModelAtIndex(0); } } /** * Removes and returns the last model of this collection, if there was one. * * @returns {Model|undefined} Removed model or undefined if there were none. */ pop(): Model | undefined { if (!this.isEmpty()) { return this._removeModelAtIndex(this.size() - 1); } } /** * Replaces all models in this collection with those provided. This is * effectively equivalent to `clear` and `add`, and will result in an empty * collection if no models were provided. * * @param {Model|Model[]} models Models to replace the current models with. */ replace(models: Model | Model[]): void { this.clearModels(); this.add(values(models)); } /** * Returns the query parameters that should be used when paginating. * * @return {Object} */ getPaginationQuery(): { page: number | null } { return { page: this._page, }; } /** * @inheritDoc */ getFetchQuery(): Record<string, any> { if (this.isPaginated()) { return this.getPaginationQuery(); } return super.getFetchQuery(); } /** * @param {Object} response * * @returns {Array|null} Models from the response. */ getModelsFromResponse(response: Response): any { let models: unknown = response.getData(); // An empty, non-array response indicates that we didn't intend to send // any models in the response. This means that the current models are // already up to date, as no changes are necessary. if (isNil(models) || models === '') { return null; } // We're making an assumption here that paginated models are returned // within the "data" field of the response. if (this.isPaginated()) { return get(models, 'data', models); } return models; } /** * Called when a save request was successful. * * @param {Object} response */ onSaveSuccess(response: Response): void { // Model data returned in the response. let saved: unknown = this.getModelsFromResponse(response); // All the models that are currently being saved. let saving: Model[] = this.getSavingModels(); // Empty response is similar to an empty response returned when saving // a model: assume that the attributes are the saved state, so sync. if (isNil(saved)) { each(saving, method('sync')); } else { // There is no sensible alternative to an array here, so anyting else // is considered an exception that indicates an unexpected state. if (!isArray(saved)) { throw this.createResponseError('Response data must be an array or empty', response); } // Check that the number of models returned in the response matches // the number of models that were saved. If these are not equal, it's // not possible to map saved data to the saving models. if (saved.length !== saving.length) { throw this.createResponseError('Expected the same number of models in the response', response); } // Update every model with its respective response data. // A strict requirement and assumption is that the models returned // in the response are in the same order as they are in the collection. each(saved, (data, index): void => { saving[index].onSaveSuccess(new ProxyResponse( 200, data, response.getHeaders() )); }); } Vue.set(this, 'saving', false); Vue.set(this, 'fatal', false); this.emit('save', {error: null}); } /** * @returns {Model[]} Models in this collection that are in a "saving" state. */ getSavingModels(): Model[] { return filter(this.models, 'saving'); } /** * @returns {Model[]} Models in this collection that are in a "deleting" state. */ getDeletingModels(): Model[] { return filter(this.models, 'deleting'); } /** * Applies an array of validation errors to this collection's models. * * @param {Array} errors * @param {integer} status Response status */ applyValidationErrorArray(errors: any[]): void { let models: Model[] = this.getSavingModels(); // To allow matching errors with models, it's a strict requirement and // assumption that the array of errors returned in the response must have // the same number of elements as there are models being saved. if (errors.length !== models.length) { throw this.createResponseError('Array of errors must equal the number of models'); } // Set every model's errors in a way that emulates how saving a model // would fail in the same way. // // A strict requirement and assumption is that the models returned // in the response are in the same order as they are in the collection. each(models, (model, index): void => { model.setErrors(errors[index]); Vue.set(model, 'saving', false); Vue.set(model, 'fatal', false); }); } /** * Applies an object of validation errors keyed by model identifiers. * * @param {Array} errors * @param {integer} status Response status */ applyValidationErrorObject(errors: Record<string, Record<string, string | string[]>>): void { let lookup: Record<string, Model> = keyBy(this.models, (model): string => model.identifier()); each(errors, (errors, identifier): void => { let model: Model = get(lookup, identifier); if (model) { model.setErrors(errors); } }); } /** * Sets validation errors on this collection's models. * * @param {Array|Object} errors Either an array of length equal to the number * of models in this collection, or an object * of errors keyed by model identifiers. */ setErrors(errors: any[] | Record<string, Record<string, string | string[]>>): void { // Support an array of errors, one for each model in the collection. if (isArray(errors)) { this.applyValidationErrorArray(errors); // Support an object of errors keyed by model identifiers. } else if (isPlainObject(errors)) { this.applyValidationErrorObject(errors); } } /** * @returns {Array} An array of this collection's validation errors. */ getErrors(): Record<string, string | string[]>[] { return map(this.models, 'errors'); } /** * Called when a save request resulted in a validation error. * * @param {Object} response */ onSaveValidationFailure(error: any): void { let response: any = error.getResponse(); let errors: any = response.getValidationErrors(); if (!isPlainObject(errors) && !isArray(errors)) { throw this.createResponseError('Validation errors must be an object or array', response); } this.setErrors(errors); Vue.set(this, 'fatal', false); Vue.set(this, 'saving', false); } /** * Called when a save request resulted in an unexpected error, * eg. an internal server error (500) * * @param {Error} error * @param {Object} response */ onFatalSaveFailure(error: any, response?: any): void { each(this.getSavingModels(), (model): void => { model.onFatalSaveFailure(error, response); }); Vue.set(this, 'fatal', true); Vue.set(this, 'saving', false); } /** * Called when a save request failed. * * @param {Error} error * @param {Object} response */ onSaveFailure(error: any): void { if (this.isBackendValidationError(error)) { this.onSaveValidationFailure(error); // Not a validation error, so something else went wrong. } else { this.onFatalSaveFailure(error); } this.emit('save', {error}); } /** * @returns {Array} The data to use for saving. */ getSaveData(): Record<string, any> { return map(this.getSavingModels(), method('getSaveData')); } /** * Sets the page on this collection, enabling pagination. To disable * pagination on this collection, pass page as `null` or `undefined`. * * @param {number|boolean} [page] Page number, or `null` to disable. * * @returns {Collection} This collection. */ page(page: number | boolean): this { // Disable pagination if a valid page wasn't provided. if (isNil(page)) { Vue.set(this, '_page', NO_PAGE); // Page was provided, so we should either set the page or disable // pagination entirely if the page is `false`. } else { Vue.set(this, '_page', max([1, toSafeInteger(page)])); } return this; } /** * @returns {integer|null} The page that this collection is on. */ getPage(): number | null { return this._page; } /** * @returns {boolean} Whether this collection is currently paginated. */ isPaginated(): boolean { return this._page !== NO_PAGE; } /** * @returns {boolean} Whether this collection is on the last page, * ie. there won't be more results that follow. */ isLastPage(): boolean { return this._page === LAST_PAGE; } /** * Responsible for adjusting the page and appending of models that were * received by a paginated fetch request. * * @param {Model[]} models */ applyPagination(models: Model[]): void { // If no models were returned in the response we can assume that // we're now on the last page, and we should not continue. if (isEmpty(models)) { Vue.set(this, '_page', LAST_PAGE); // Otherwise, there were at least one model, and we can safely // assume that we want to increment the page number. } else { Vue.set(this, '_page', (this._page as number) + 1); this.add(models); } } /** * Called when a fetch request was successful. * * @param {Object} response */ onFetchSuccess(response: Response): void { let models: any = this.getModelsFromResponse(response); // There is no sensible alternative to an array here, so anyting else // is considered an exception that indicates an unexpected state. if (!isArray(models)) { throw new ResponseError('Expected an array of models in fetch response'); } // Append via pagination. if (this.isPaginated()) { this.applyPagination(models); // Replace all current models with the fetched ones. } else { this.replace(models); } Vue.set(this, 'loading', false); Vue.set(this, 'fatal', false); this.emit('fetch', {error: null}); } /** * Called when a fetch request failed. * * @param {Error} error */ onFetchFailure(error: any): void { this.clearErrors(); Vue.set(this, 'fatal', true); Vue.set(this, 'loading', false); this.emit('fetch', {error}); } /** * Called before a fetch request is made. * * @returns {boolean|undefined} `false` if the request should not be made. */ onFetch(): Promise<RequestOperation> { return new Promise((resolve): void => { // Don't fetch if there are no more results to be fetched. if (this.isPaginated() && this.isLastPage()) { return resolve(Base.REQUEST_SKIP); } // Because we're fetching new data, we can assume that this collection // is now loading. This allows the template to indicate a loading state. Vue.set(this, 'loading', true); resolve(Base.REQUEST_CONTINUE); return; }); } /** * Called when a delete request was successful. * * @param {Object} response */ onDeleteSuccess(response: Response): void { Vue.set(this, 'deleting', false); Vue.set(this, 'fatal', false); each(this.getDeletingModels(), (model): void => { model.onDeleteSuccess(response); }); this.emit('delete', {error: null}); } /** * Called when a delete request resulted in a general error. * * @param {Error} error * @param {Object} response */ onDeleteFailure(error: any): void { Vue.set(this, 'fatal', true); Vue.set(this, 'deleting', false); each(this.getDeletingModels(), (model): void => { model.onDeleteFailure(error); }); this.emit('delete', {error}); } /** * Called before a save request is made. * * @returns {boolean} Either `true` or false` if the request should not be * made, where `true` indicates that the request should * be considered a "success" rather than a "cancel". * */ onSave(): Promise<RequestOperation> { // Don't save if we're already busy saving this collection. // This prevents things like accidental double clicks. if (this.saving) { return Promise.resolve(Base.REQUEST_SKIP); } let valid = true; let tasks: Promise<RequestOperation | void>[] = this.models.map((model): Promise<RequestOperation | void> => { return model.onSave().catch((error): void => { if (error instanceof ValidationError) { valid = false; } else { throw error; } }); }); // Call 'onSave' on each model so that the models can set their state // accordingly, and indicate whether a validation failure should occur. return Promise.all(tasks).then((): RequestOperation => { if (!valid) { throw new ValidationError(this.getErrors()); } Vue.set(this, 'saving', true); return Base.REQUEST_CONTINUE; }); } /** * Collect all model identifiers. * * @returns {Array} */ getIdentifiers(models: Model[]): string[] { return map(models, method('identifier')); } /** * @inheritDoc */ getDeleteBody(): string[] | {} { if (this.getOption('useDeleteBody')) { return this.getIdentifiers(this.getDeletingModels()); } return {}; } /** * @returns {string} The query parameter key to use for model identifiers. */ getDeleteQueryIdenitifierKey(): string { return 'id'; } /** * @inheritDoc */ getDeleteQuery(): Record<string, string> { // Don't use query parameters if we want send the request data in the body. if (this.getOption('useDeleteBody')) { return {}; } // Collect all the identifiers of the models being deleted. let models: Model[] = this.getDeletingModels(); let identifier: string = this.getDeleteQueryIdenitifierKey(); let identifiers: string[] = this.getIdentifiers(models); return {[identifier]: join(identifiers, ',')}; } /** * Called before a delete request is made. * * @returns {boolean} `false` if the request should not be made. */ onDelete(): Promise<RequestOperation> { if (this.deleting) { return Promise.resolve(Base.REQUEST_SKIP); } return Promise.all(this.models.map((m): Promise<RequestOperation> => m.onDelete())) .then((): RequestOperation => { // No need to do anything if no models should be deleted. if (isEmpty(this.getDeletingModels())) { return Base.REQUEST_REDUNDANT; } Vue.set(this, 'deleting', true); return Base.REQUEST_CONTINUE; }); } /** * Convert collection to Array. All models inside are converted to JSON * * @return {object[]} converted collection */ toArray(): Record<string, any>[] { return this.map((model): Record<string, any> => model.toJSON()); } } export default Collection; export type Predicate<T = boolean> = ((model: Model) => T) | string | Record<string, any> | Model | Partial<Model>;
the_stack
import {Class, AnyTiming, Timing} from "@swim/util"; import {MemberFastenerClass, Property} from "@swim/component"; import type {Length} from "@swim/math"; import {Trait, TraitRef} from "@swim/model"; import type {Color} from "@swim/style"; import type {GraphicsView} from "@swim/graphics"; import {Controller, TraitViewRef, TraitViewControllerSet} from "@swim/controller"; import type {DataPointView} from "./DataPointView"; import type {DataPointTrait} from "./DataPointTrait"; import {DataPointController} from "./DataPointController"; import {DataSetTrait} from "./DataSetTrait"; import type {DataSetControllerObserver} from "./DataSetControllerObserver"; /** @public */ export interface DataSetControllerDataPointExt<X = unknown, Y = unknown> { attachDataPointTrait(dataPointTrait: DataPointTrait<X, Y>, dataPointController: DataPointController<X, Y>): void; detachDataPointTrait(dataPointTrait: DataPointTrait<X, Y>, dataPointController: DataPointController<X, Y>): void; attachDataPointView(dataPointView: DataPointView<X, Y>, dataPointController: DataPointController<X, Y>): void; detachDataPointView(dataPointView: DataPointView<X, Y>, dataPointController: DataPointController<X, Y>): void; attachDataPointLabelView(labelView: GraphicsView, dataPointController: DataPointController<X, Y>): void; detachDataPointLabelView(labelView: GraphicsView, dataPointController: DataPointController<X, Y>): void; } /** @public */ export class DataSetController<X = unknown, Y = unknown> extends Controller { override readonly observerType?: Class<DataSetControllerObserver<X, Y>>; @TraitRef<DataSetController<X, Y>, DataSetTrait<X, Y>>({ type: DataSetTrait, observes: true, willAttachTrait(dataSetTrait: DataSetTrait<X, Y>): void { this.owner.callObservers("controllerWillAttachDataSetTrait", dataSetTrait, this.owner); }, didAttachTrait(dataSetTrait: DataSetTrait<X, Y>): void { const dataPointTraits = dataSetTrait.dataPoints.traits; for (const traitId in dataPointTraits) { const dataPointTrait = dataPointTraits[traitId]!; this.owner.dataPoints.addTraitController(dataPointTrait); } }, willDetachTrait(dataSetTrait: DataSetTrait<X, Y>): void { const dataPointTraits = dataSetTrait.dataPoints.traits; for (const traitId in dataPointTraits) { const dataPointTrait = dataPointTraits[traitId]!; this.owner.dataPoints.deleteTraitController(dataPointTrait); } }, didDetachTrait(dataSetTrait: DataSetTrait<X, Y>): void { this.owner.callObservers("controllerDidDetachDataSetTrait", dataSetTrait, this.owner); }, traitWillAttachDataPoint(dataPointTrait: DataPointTrait<X, Y>, targetTrait: Trait): void { this.owner.dataPoints.addTraitController(dataPointTrait, targetTrait); }, traitDidDetachDataPoint(dataPointTrait: DataPointTrait<X, Y>): void { this.owner.dataPoints.deleteTraitController(dataPointTrait); }, }) readonly dataSet!: TraitRef<this, DataSetTrait<X, Y>>; static readonly dataSet: MemberFastenerClass<DataSetController, "dataSet">; @Property({type: Timing, value: true}) readonly dataPointTiming!: Property<this, Timing | boolean | undefined, AnyTiming>; @TraitViewControllerSet<DataSetController<X, Y>, DataPointTrait<X, Y>, DataPointView<X, Y>, DataPointController<X, Y>, DataSetControllerDataPointExt<X, Y>>({ implements: true, type: DataPointController, binds: true, observes: true, getTraitViewRef(dataPointController: DataPointController<X, Y>): TraitViewRef<unknown, DataPointTrait<X, Y>, DataPointView<X, Y>> { return dataPointController.dataPoint; }, willAttachController(dataPointController: DataPointController<X, Y>): void { this.owner.callObservers("controllerWillAttachDataPoint", dataPointController, this.owner); }, didAttachController(dataPointController: DataPointController<X, Y>): void { const dataPointTrait = dataPointController.dataPoint.trait; if (dataPointTrait !== null) { this.attachDataPointTrait(dataPointTrait, dataPointController); } const dataPointView = dataPointController.dataPoint.view; if (dataPointView !== null) { this.attachDataPointView(dataPointView, dataPointController); } const parentView = this.parentView; if (parentView !== null) { dataPointController.dataPoint.insertView(parentView); } }, willDetachController(dataPointController: DataPointController<X, Y>): void { const dataPointView = dataPointController.dataPoint.view; if (dataPointView !== null) { this.detachDataPointView(dataPointView, dataPointController); } const dataPointTrait = dataPointController.dataPoint.trait; if (dataPointTrait !== null) { this.detachDataPointTrait(dataPointTrait, dataPointController); } }, didDetachController(dataPointController: DataPointController<X, Y>): void { this.owner.callObservers("controllerDidDetachDataPoint", dataPointController, this.owner); }, controllerWillAttachDataPointTrait(dataPointTrait: DataPointTrait<X, Y>, dataPointController: DataPointController<X, Y>): void { this.owner.callObservers("controllerWillAttachDataPointTrait", dataPointTrait, dataPointController, this.owner); this.attachDataPointTrait(dataPointTrait, dataPointController); }, controllerDidDetachDataPointTrait(dataPointTrait: DataPointTrait<X, Y>, dataPointController: DataPointController<X, Y>): void { this.detachDataPointTrait(dataPointTrait, dataPointController); this.owner.callObservers("controllerDidDetachDataPointTrait", dataPointTrait, dataPointController, this.owner); }, attachDataPointTrait(dataPointTrait: DataPointTrait<X, Y>, dataPointController: DataPointController<X, Y>): void { // hook }, detachDataPointTrait(dataPointTrait: DataPointTrait<X, Y>, dataPointController: DataPointController<X, Y>): void { // hook }, controllerWillAttachDataPointView(dataPointView: DataPointView<X, Y>, dataPointController: DataPointController<X, Y>): void { this.owner.callObservers("controllerWillAttachDataPointView", dataPointView, dataPointController, this.owner); this.attachDataPointView(dataPointView, dataPointController); }, controllerDidDetachDataPointView(dataPointView: DataPointView<X, Y>, dataPointController: DataPointController<X, Y>): void { this.detachDataPointView(dataPointView, dataPointController); this.owner.callObservers("controllerDidDetachDataPointView", dataPointView, dataPointController, this.owner); }, attachDataPointView(dataPointView: DataPointView<X, Y>, dataPointController: DataPointController<X, Y>): void { const labelView = dataPointView.label.view; if (labelView !== null) { this.attachDataPointLabelView(labelView, dataPointController); } }, detachDataPointView(dataPointView: DataPointView<X, Y>, dataPointController: DataPointController<X, Y>): void { const labelView = dataPointView.label.view; if (labelView !== null) { this.detachDataPointLabelView(labelView, dataPointController); } dataPointView.remove(); }, controllerWillSetDataPointX(newX: X | undefined, oldX: X | undefined, dataPointController: DataPointController<X, Y>): void { this.owner.callObservers("controllerWillSetDataPointX", newX, oldX, dataPointController, this.owner); }, controllerDidSetDataPointX(newX: X | undefined, oldX: X | undefined, dataPointController: DataPointController<X, Y>): void { this.owner.callObservers("controllerDidSetDataPointX", newX, oldX, dataPointController, this.owner); }, controllerWillSetDataPointY(newY: Y | undefined, oldY: Y | undefined, dataPointController: DataPointController<X, Y>): void { this.owner.callObservers("controllerWillSetDataPointY", newY, oldY, dataPointController, this.owner); }, controllerDidSetDataPointY(newY: Y | undefined, oldY: Y | undefined, dataPointController: DataPointController<X, Y>): void { this.owner.callObservers("controllerDidSetDataPointY", newY, oldY, dataPointController, this.owner); }, controllerWillSetDataPointY2(newY2: Y | undefined, oldY2: Y | undefined, dataPointController: DataPointController<X, Y>): void { this.owner.callObservers("controllerWillSetDataPointY2", newY2, oldY2, dataPointController, this.owner); }, controllerDidSetDataPointY2(newY2: Y | undefined, oldY2: Y | undefined, dataPointController: DataPointController<X, Y>): void { this.owner.callObservers("controllerDidSetDataPointY2", newY2, oldY2, dataPointController, this.owner); }, controllerWillSetDataPointRadius(newRadius: Length | null, oldRadius: Length | null, dataPointController: DataPointController<X, Y>): void { this.owner.callObservers("controllerWillSetDataPointRadius", newRadius, oldRadius, dataPointController, this.owner); }, controllerDidSetDataPointRadius(newRadius: Length | null, oldRadius: Length | null, dataPointController: DataPointController<X, Y>): void { this.owner.callObservers("controllerDidSetDataPointRadius", newRadius, oldRadius, dataPointController, this.owner); }, controllerWillSetDataPointColor(newColor: Color | null, oldColor: Color | null, dataPointController: DataPointController<X, Y>): void { this.owner.callObservers("controllerWillSetDataPointColor", newColor, oldColor, dataPointController, this.owner); }, controllerDidSetDataPointColor(newColor: Color | null, oldColor: Color | null, dataPointController: DataPointController<X, Y>): void { this.owner.callObservers("controllerDidSetDataPointColor", newColor, oldColor, dataPointController, this.owner); }, controllerWillSetDataPointOpacity(newOpacity: number | undefined, oldOpacity: number | undefined, dataPointController: DataPointController<X, Y>): void { this.owner.callObservers("controllerWillSetDataPointOpacity", newOpacity, oldOpacity, dataPointController, this.owner); }, controllerDidSetDataPointOpacity(newOpacity: number | undefined, oldOpacity: number | undefined, dataPointController: DataPointController<X, Y>): void { this.owner.callObservers("controllerDidSetDataPointOpacity", newOpacity, oldOpacity, dataPointController, this.owner); }, controllerWillAttachDataPointLabelView(labelView: GraphicsView, dataPointController: DataPointController<X, Y>): void { this.owner.callObservers("controllerWillAttachDataPointLabelView", labelView, dataPointController, this.owner); this.attachDataPointLabelView(labelView, dataPointController); }, controllerDidDetachDataPointLabelView(labelView: GraphicsView, dataPointController: DataPointController<X, Y>): void { this.detachDataPointLabelView(labelView, dataPointController); this.owner.callObservers("controllerDidDetachDataPointLabelView", labelView, dataPointController, this.owner); }, attachDataPointLabelView(labelView: GraphicsView, dataPointController: DataPointController<X, Y>): void { // hook }, detachDataPointLabelView(labelView: GraphicsView, dataPointController: DataPointController<X, Y>): void { // hook }, }) readonly dataPoints!: TraitViewControllerSet<this, DataPointTrait<X, Y>, DataPointView<X, Y>, DataPointController<X, Y>> & DataSetControllerDataPointExt<X, Y>; static readonly dataPoints: MemberFastenerClass<DataSetController, "dataPoints">; }
the_stack
import { Components, registerComponent } from '../lib/vulcan-lib'; import { withUpdate } from '../lib/crud/withUpdate'; import React, { PureComponent } from 'react'; import { Helmet } from 'react-helmet'; import classNames from 'classnames' import Intercom from 'react-intercom'; import moment from '../lib/moment-timezone'; import { withCookies } from 'react-cookie' import { withTheme } from '@material-ui/core/styles'; import { withLocation } from '../lib/routeUtil'; import { AnalyticsContext } from '../lib/analyticsEvents' import { UserContext } from './common/withUser'; import { TimezoneContext } from './common/withTimezone'; import { DialogManager } from './common/withDialog'; import { CommentBoxManager } from './common/withCommentBox'; import { TableOfContentsContext } from './posts/TableOfContents/TableOfContents'; import { ItemsReadContext } from './common/withRecordPostView'; import { pBodyStyle } from '../themes/stylePiping'; import { DatabasePublicSetting, googleTagManagerIdSetting } from '../lib/publicSettings'; import { forumTypeSetting } from '../lib/instanceSettings'; import { globalStyles } from '../themes/globalStyles/globalStyles'; import type { ToCData, ToCSection } from '../server/tableOfContents'; import { ForumOptions, forumSelect } from '../lib/forumTypeUtils'; const intercomAppIdSetting = new DatabasePublicSetting<string>('intercomAppId', 'wtb8z7sj') const petrovBeforeTime = new DatabasePublicSetting<number>('petrov.beforeTime', 1631226712000) const petrovAfterTime = new DatabasePublicSetting<number>('petrov.afterTime', 1641231428737) // These routes will have the standalone TabNavigationMenu (aka sidebar) // // Refer to routes.js for the route names. Or console log in the route you'd // like to include const standaloneNavMenuRouteNames: ForumOptions<string[]> = { 'LessWrong': [ 'home', 'allPosts', 'questions', 'sequencesHome', 'Shortform', 'Codex', 'bestoflesswrong', 'HPMOR', 'Rationality', 'Sequences', 'collections', 'nominations', 'reviews' ], 'AlignmentForum': ['alignment.home', 'sequencesHome', 'allPosts', 'questions', 'Shortform'], 'EAForum': ['home', 'allPosts', 'questions', 'Shortform', 'eaLibrary'], 'default': ['home', 'allPosts', 'questions', 'Community', 'Shortform',], } const styles = (theme: ThemeType): JssStyles => ({ main: { paddingTop: 50, paddingBottom: 15, marginLeft: "auto", marginRight: "auto", background: theme.palette.background.default, minHeight: `calc(100vh - 64px)`, //64px is approximately the height of the header gridArea: 'main', [theme.breakpoints.down('sm')]: { paddingTop: 0, paddingLeft: theme.spacing.unit/2, paddingRight: theme.spacing.unit/2, }, }, gridActivated: { '@supports (grid-template-areas: "title")': { display: 'grid', gridTemplateAreas: ` "navSidebar ... main ... sunshine" `, gridTemplateColumns: ` minmax(0, min-content) minmax(0, 1fr) minmax(0, min-content) minmax(0, 1.4fr) minmax(0, min-content) `, }, [theme.breakpoints.down('md')]: { display: 'block' } }, navSidebar: { gridArea: 'navSidebar' }, sunshine: { gridArea: 'sunshine' }, whiteBackground: { background: theme.palette.background.pageActiveAreaBackground, }, '@global': { ...globalStyles(theme), p: pBodyStyle(theme), '.mapboxgl-popup': { willChange: 'auto !important', zIndex: theme.zIndexes.styledMapPopup }, // Font fallback to ensure that all greek letters just directly render as Arial '@font-face': { fontFamily: "GreekFallback", src: "local('Arial')", unicodeRange: 'U+0370-03FF, U+1F00-1FFF' // Unicode range for greek characters }, // Hide the CKEditor table alignment menu '.ck-table-properties-form__alignment-row': { display: "none !important" }, ...(theme.palette.intercom ? { '.intercom-launcher': { backgroundColor: theme.palette.intercom.buttonBackground } } : null), }, searchResultsArea: { position: "absolute", zIndex: theme.zIndexes.layout, top: 0, width: "100%", }, }) interface ExternalProps { currentUser: UsersCurrent | null, messages: any, children?: React.ReactNode, } interface LayoutProps extends ExternalProps, WithLocationProps, WithStylesProps { cookies: any, theme: ThemeType, updateUser: any, } interface LayoutState { timezone: string, toc: {title: string|null, sections?: ToCSection[]}|null, postsRead: Record<string,boolean>, tagsRead: Record<string,boolean>, hideNavigationSidebar: boolean, } class Layout extends PureComponent<LayoutProps,LayoutState> { searchResultsAreaRef: React.RefObject<HTMLDivElement> constructor (props: LayoutProps) { super(props); const { cookies, currentUser } = this.props; const savedTimezone = cookies?.get('timezone'); this.state = { timezone: savedTimezone, toc: null, postsRead: {}, tagsRead: {}, hideNavigationSidebar: !!(currentUser?.hideNavigationSidebar), }; this.searchResultsAreaRef = React.createRef<HTMLDivElement>(); } setToC = (title: string|null, sectionData: ToCData|null) => { if (title) { this.setState({ toc: { title: title, sections: sectionData?.sections } }); } else { this.setState({ toc: null, }); } } toggleStandaloneNavigation = () => { const { updateUser, currentUser } = this.props this.setState(prevState => { if (currentUser) { void updateUser({ selector: {_id: currentUser._id}, data: { hideNavigationSidebar: !prevState.hideNavigationSidebar } }) } return { hideNavigationSidebar: !prevState.hideNavigationSidebar } }) } componentDidMount() { const { updateUser, currentUser, cookies } = this.props; const newTimezone = moment.tz.guess(); if(this.state.timezone !== newTimezone || (currentUser?.lastUsedTimezone !== newTimezone)) { cookies.set('timezone', newTimezone); if (currentUser) { void updateUser({ selector: {_id: currentUser._id}, data: { lastUsedTimezone: newTimezone, } }) } this.setState({ timezone: newTimezone }); } } render () { const {currentUser, location, children, classes, theme} = this.props; const {hideNavigationSidebar} = this.state const { NavigationStandalone, SunshineSidebar, ErrorBoundary, Footer, Header, FlashMessages, AnalyticsClient, AnalyticsPageInitializer, NavigationEventSender, PetrovDayWrapper, NewUserCompleteProfile, BannedNotice } = Components const showIntercom = (currentUser: UsersCurrent|null) => { if (currentUser && !currentUser.hideIntercom) { return <div id="intercome-outer-frame"> <ErrorBoundary> <Intercom appID={intercomAppIdSetting.get()} user_id={currentUser._id} email={currentUser.email} name={currentUser.displayName}/> </ErrorBoundary> </div> } else if (!currentUser) { return <div id="intercome-outer-frame"> <ErrorBoundary> <Intercom appID={intercomAppIdSetting.get()}/> </ErrorBoundary> </div> } else { return null } } // Check whether the current route is one which should have standalone // navigation on the side. If there is no current route (ie, a 404 page), // then it should. // FIXME: This is using route names, but it would be better if this was // a property on routes themselves. const currentRoute = location.currentRoute const standaloneNavigation = !currentRoute || forumSelect(standaloneNavMenuRouteNames) .includes(currentRoute?.name) const shouldUseGridLayout = standaloneNavigation const currentTime = new Date() const beforeTime = petrovBeforeTime.get() const afterTime = petrovAfterTime.get() const renderPetrovDay = currentRoute?.name === "home" && ['LessWrong', 'EAForum'].includes(forumTypeSetting.get()) && beforeTime < currentTime.valueOf() && currentTime.valueOf() < afterTime return ( <AnalyticsContext path={location.pathname}> <UserContext.Provider value={currentUser}> <TimezoneContext.Provider value={this.state.timezone}> <ItemsReadContext.Provider value={{ postsRead: this.state.postsRead, setPostRead: (postId: string, isRead: boolean): void => { this.setState({ postsRead: {...this.state.postsRead, [postId]: isRead} }) }, tagsRead: this.state.tagsRead, setTagRead: (tagId: string, isRead: boolean): void => { this.setState({ tagsRead: {...this.state.tagsRead, [tagId]: isRead} }) }, }}> <TableOfContentsContext.Provider value={this.setToC}> <div className={classNames("wrapper", classes.wrapper, {'alignment-forum': forumTypeSetting.get() === 'AlignmentForum'}) } id="wrapper"> <DialogManager> <CommentBoxManager> <Helmet> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/icon?family=Material+Icons"/> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/instantsearch.css@7.0.0/themes/reset-min.css"/> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500"/> { theme.typography.fontDownloads && theme.typography.fontDownloads.map( (url: string)=><link rel="stylesheet" key={`font-${url}`} href={url}/> ) } <meta httpEquiv="Accept-CH" content="DPR, Viewport-Width, Width"/> <link rel="stylesheet" href="https://use.typekit.net/jvr1gjm.css"/> </Helmet> <AnalyticsClient/> <AnalyticsPageInitializer/> <NavigationEventSender/> {/* Sign up user for Intercom, if they do not yet have an account */} {!currentRoute?.standalone && showIntercom(currentUser)} <noscript className="noscript-warning"> This website requires javascript to properly function. Consider activating javascript to get access to all site functionality. </noscript> {/* Google Tag Manager i-frame fallback */} <noscript><iframe src={`https://www.googletagmanager.com/ns.html?id=${googleTagManagerIdSetting.get()}`} height="0" width="0" style={{display:"none", visibility:"hidden"}}/></noscript> {!currentRoute?.standalone && <Header toc={this.state.toc} searchResultsArea={this.searchResultsAreaRef} standaloneNavigationPresent={standaloneNavigation} toggleStandaloneNavigation={this.toggleStandaloneNavigation} />} {renderPetrovDay && <PetrovDayWrapper/>} <div className={shouldUseGridLayout ? classes.gridActivated : null}> {standaloneNavigation && <div className={classes.navSidebar}> <NavigationStandalone sidebarHidden={hideNavigationSidebar}/> </div>} <div ref={this.searchResultsAreaRef} className={classes.searchResultsArea} /> <div className={classNames(classes.main, { [classes.whiteBackground]: currentRoute?.background === "white" })}> <ErrorBoundary> <FlashMessages /> </ErrorBoundary> <ErrorBoundary> {currentUser?.usernameUnset ? <NewUserCompleteProfile /> : children } </ErrorBoundary> <Footer /> </div> {currentRoute?.sunshineSidebar && <div className={classes.sunshine}> <SunshineSidebar/> </div> } </div> </CommentBoxManager> </DialogManager> </div> </TableOfContentsContext.Provider> </ItemsReadContext.Provider> </TimezoneContext.Provider> </UserContext.Provider> </AnalyticsContext> ) } } const LayoutComponent = registerComponent<ExternalProps>( 'Layout', Layout, { styles, hocs: [ withLocation, withCookies, withUpdate({ collectionName: "Users", fragmentName: 'UsersCurrent', }), withTheme() ]} ); declare global { interface ComponentTypes { Layout: typeof LayoutComponent } }
the_stack
import { app, BrowserWindow, ipcMain, Menu, globalShortcut, systemPreferences, } from 'electron'; import * as electronReferer from 'electron-referer'; import * as path from 'path'; import * as url from 'url'; import { DOWNLOAD, TRIGGER_HOTKEY, MODIFY_HOTKEY, DEFAULT_GLOBAL_SHORTCUT, GLOBAL_SHORTCUT, ENABLE_HOTKEY, UPDATE_BACKGROUND_IMAGE, ENABLE_BACKGROUND_IMAGE, BACKGROUND_IMAGE_URL, UPDATE_THEME, THEME_URL, DEFAULT_MEDIA_SHORTCUT, } from '../constants'; import { settings } from './db'; import { IModifyHotkeyArgs, IUploadBackgroundImage, IUpdateTheme, } from '../typings/message'; import { copyFile, genUniqueKey } from './utils'; import * as fs from 'fs'; electronReferer('https://www.ximalaya.com/'); const USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'; // tslint:disable-line let mainWindow: Electron.BrowserWindow | null; let forceQuit = false; const template = [ { label: '编辑', submenu: [ { label: '剪切', accelerator: 'CmdOrCtrl+X', role: 'cut', }, { label: '复制', accelerator: 'CmdOrCtrl+C', role: 'copy', }, { label: '粘贴', accelerator: 'CmdOrCtrl+V', role: 'paste', }, { label: '全选', accelerator: 'CmdOrCtrl+A', role: 'selectall', }, ], }, { label: '查看', submenu: [ { label: '重载', accelerator: 'CmdOrCtrl+R', click(item, focusedWindow) { if (focusedWindow) { if (focusedWindow.id === 1) { BrowserWindow.getAllWindows().forEach((win) => { if (win.id > 1) { win.close(); } }); } focusedWindow.reload(); } }, }, { label: '切换全屏', accelerator: (() => { if (process.platform === 'darwin') { return 'Ctrl+Command+F'; } else { return 'F11'; } })(), click(item, focusedWindow) { if (focusedWindow) { focusedWindow.setFullScreen(!focusedWindow.isFullScreen()); } }, }, { label: '切换开发者工具', accelerator: (() => { if (process.platform === 'darwin') { return 'Alt+Command+I'; } else { return 'Ctrl+Shift+I'; } })(), click(item, focusedWindow) { if (focusedWindow) { focusedWindow.toggleDevTools(); } }, }, ], }, { label: '窗口', role: 'window', submenu: [ { label: '最小化', accelerator: 'CmdOrCtrl+M', role: 'minimize', }, { label: '关闭', accelerator: 'CmdOrCtrl+W', role: 'close', }, { label: '退出', accelerator: 'Cmd+Q', role: 'quit', }, ], }, ]; if (process.platform === 'darwin') { template.unshift({ label: app.getName(), submenu: [ { label: `关于 ${app.getName()}`, role: 'about', accelerator: '', // click() { // dialog.showMessageBox(mainWindow, { message: 'hello world' }); // }, }, ], }); } const isMac = 'darwin' === process.platform; function createWindow() { const titleBarStyle = isMac ? 'hiddenInset' : 'default'; mainWindow = new BrowserWindow({ minHeight: 600, minWidth: 800, width: 1040, height: 715, backgroundColor: 'white', titleBarStyle, title: 'Mob', frame: !isMac, icon: path.join(__dirname, '../../build/icon.png'), show: true, acceptFirstMouse: true, webPreferences: { webSecurity: false, }, }); mainWindow.webContents.setUserAgent(USER_AGENT); if (process.env.NODE_ENV === 'development') { mainWindow.loadURL('http://localhost:6008/#/'); if (process.env.DEV_TOOLS) { mainWindow.webContents.openDevTools(); } } else { mainWindow.loadURL( url.format({ pathname: path.join(__dirname, './dist/renderer/index.html'), protocol: 'file:', slashes: true, }), ); } if (isMac) { setTimeout( () => systemPreferences.isTrustedAccessibilityClient(true), 1000, ); } mainWindow.once('ready-to-show', () => { mainWindow.show(); }); mainWindow.on('closed', () => { mainWindow = null; }); mainWindow.on('close', (e) => { if (forceQuit || !isMac) { app.quit(); } else { e.preventDefault(); mainWindow.hide(); } }); mainWindow.webContents.session.on('will-download', (e, item, webContents) => { const totalBytes = item.getTotalBytes(); // todo fix (here can't get path if download by browser) const filePath = item.getSavePath(); item.on('updated', () => { mainWindow.setProgressBar(item.getReceivedBytes() / totalBytes); }); item.once('done', (e, state) => { if (!mainWindow.isDestroyed()) { mainWindow.setProgressBar(-1); } if (state === 'interrupted') { mainWindow.webContents.send(DOWNLOAD, { type: 'error' }); } if (state === 'completed') { mainWindow.webContents.send(DOWNLOAD, { type: 'success', filePath }); app.dock.downloadFinished(filePath); } }); }); /** * hotkey */ const enableHotkey = settings.get(ENABLE_HOTKEY); if (enableHotkey) { const shortcuts = settings.get(GLOBAL_SHORTCUT); const curShortcuts = (shortcuts as typeof DEFAULT_GLOBAL_SHORTCUT) || DEFAULT_GLOBAL_SHORTCUT; registerHotkeys(curShortcuts); } } const registerHotkeys = (shortcuts, isRetry = false) => { // macOS. Loop check is trusted if (isMac) { const isTrusted = systemPreferences.isTrustedAccessibilityClient(false); if (!isTrusted) { setTimeout(() => registerHotkeys(shortcuts, true), 1000); // Don't repeat register shortcuts after retry failed if (isRetry) { return; } } } const newShortcuts = { ...DEFAULT_MEDIA_SHORTCUT, ...shortcuts }; globalShortcut.unregisterAll(); Object.keys(newShortcuts).forEach((key) => { globalShortcut.register(key, () => { mainWindow.webContents.send(TRIGGER_HOTKEY, newShortcuts[key]); }); }); }; const handleModifyHotkey = (event, args: IModifyHotkeyArgs) => { const { type, payload } = args; let shortcuts; if (type === 'switch') { settings.set(ENABLE_HOTKEY, payload); if (!payload) { globalShortcut.unregisterAll(); return; } shortcuts = settings.get(GLOBAL_SHORTCUT, DEFAULT_GLOBAL_SHORTCUT); } else { shortcuts = payload; settings.set(GLOBAL_SHORTCUT, shortcuts); } registerHotkeys(shortcuts); event.sender.send(MODIFY_HOTKEY, { type, status: 'success' }); }; ipcMain.on(MODIFY_HOTKEY, handleModifyHotkey); /** * background-image */ const handleUploadBackgroundImage = (event, args: IUploadBackgroundImage) => { const { type, payload } = args; try { if (type === 'switch') { const enable = payload; settings.set(ENABLE_BACKGROUND_IMAGE, enable); event.sender.send(UPDATE_BACKGROUND_IMAGE, { type, payload: { enable, url: '' }, status: 'success', }); } else { const src = payload as string; const extName = path.extname(src); const bgImageName = genUniqueKey(); const target = path.join(app.getPath('userData'), bgImageName + extName); copyFile(src, target); // get correct url const url = encodeURI(`file://${target}`); const prevImageUrl = settings.get(BACKGROUND_IMAGE_URL); if (prevImageUrl) { // get correct path const prevImagePath = decodeURI(prevImageUrl).slice(7); fs.unlink(prevImagePath, (err) => { if (err) { // tslint:disable-next-line:no-console console.error(err); return; } }); } settings.set(BACKGROUND_IMAGE_URL, url); event.sender.send(UPDATE_BACKGROUND_IMAGE, { type, payload: { enable: true, url }, status: 'success', }); } } catch (e) { event.sender.send(UPDATE_BACKGROUND_IMAGE, { type, status: 'error' }); // tslint:disable-next-line:no-console console.error('update background image error!'); } }; ipcMain.on(UPDATE_BACKGROUND_IMAGE, handleUploadBackgroundImage); /** * update theme */ const handleUpdateTheme = (event, args: IUpdateTheme) => { const { type, payload: { content, params: { curTheme, nextTheme }, }, } = args; const cssFilename = genUniqueKey() + '.css'; const output = path.join(app.getPath('userData'), cssFilename); const cc = {}; Object.keys(curTheme).forEach((colorName) => { cc[curTheme[colorName]] = nextTheme[colorName]; }); const reg = new RegExp(Object.keys(cc).join('|'), 'g'); const newContent = content.replace(reg, (matched) => { return cc[matched]; }); fs.writeFile(output, newContent, 'utf8', (error) => { if (error) { event.sender.send(UPDATE_THEME, { type, status: 'error', payload: { output }, }); return; } event.sender.send(UPDATE_THEME, { type, status: 'success', payload: { output, theme: nextTheme }, }); const prevThemeUrl = settings.get(THEME_URL); if (prevThemeUrl) { const prevThemePath = decodeURI(prevThemeUrl); fs.unlink(prevThemePath, (err) => { if (err) { // tslint:disable-next-line:no-console console.error(err); return; } }); } }); }; ipcMain.on(UPDATE_THEME, handleUpdateTheme); app.on('ready', () => { createWindow(); const menu = Menu.buildFromTemplate(template); Menu.setApplicationMenu(menu); }); app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', () => { if (!mainWindow.isVisible()) { mainWindow.show(); } }); app.on('before-quit', (e) => { forceQuit = true; mainWindow = null; });
the_stack
import { LogTypes, StorageTypes } from '@requestnetwork/types'; import Utils from '@requestnetwork/utils'; /** * Manages every info linked to the ethereum blocks (blockNumber, blockTimestamp, confirmations ... ) */ export default class EthereumBlocks { // 'web3-eth' object public eth: any; /** * Gets last block number * The return value of this function will be cached for `lastBlockNumberDelay` milliseconds * * @return blockNumber of the last block */ public getLastBlockNumber: () => Promise<number>; // The time to wait between query retries public retryDelay: number; // Maximum number of retries for a query public maxRetries: number; /** * Cache of the blockTimestamp indexed by blockNumber * to ask only once the timestamp of a block from a node * */ protected blockTimestamp: number[] = []; // All the block before this one are ignored // Basically, the block where the contract has been created private firstSignificantBlockNumber: number; // The minimum amount of time to wait between fetches of lastBlockNumber private getLastBlockNumberMinDelay: number; /** * Logger instance */ private logger: LogTypes.ILogger; /** * Constructor * @param eth eth object from web3 * @param firstSignificantBlockNumber all the block before this one will be ignored * @param getLastBlockNumberMinDelay the minimum delay to wait between fetches of lastBlockNumber */ public constructor( eth: any, firstSignificantBlockNumber: number, retryDelay: number, maxRetries: number, getLastBlockNumberMinDelay = 0, logger?: LogTypes.ILogger, ) { this.eth = eth; this.firstSignificantBlockNumber = firstSignificantBlockNumber; this.getLastBlockNumberMinDelay = getLastBlockNumberMinDelay; this.logger = logger || new Utils.SimpleLogger(); // Get retry parameter values from config this.retryDelay = retryDelay; this.maxRetries = maxRetries; // Setup the throttled and retriable getLastBlockNumber function this.getLastBlockNumber = Utils.cachedThrottle( () => Utils.retry( () => { this.logger.debug(`Getting last block number`, ['ethereum', 'ethereum-blocks']); return this.eth.getBlockNumber(); }, { maxRetries: this.maxRetries, retryDelay: this.retryDelay, }, )(), this.getLastBlockNumberMinDelay, ); } /** * Gets timestamp of a block * @param blockNumber number of the block * @return timestamp of a block */ public async getBlockTimestamp(blockNumber: number): Promise<number> { // If we already have it, give it if (this.blockTimestamp[blockNumber]) { return this.blockTimestamp[blockNumber]; } // if we don't know the information, let's get it // Use Utils.retry to rerun if getBlock fails const block = await Utils.retry((bn: number) => this.eth.getBlock(bn), { maxRetries: this.maxRetries, retryDelay: this.retryDelay, })(blockNumber); if (!block) { throw Error(`block ${blockNumber} not found`); } this.blockTimestamp[blockNumber] = block.timestamp; return this.blockTimestamp[blockNumber]; } /** * Gets the two block numbers surrounding a timestamp * if the timestamp match exactly a blockTimestamp, returns twice this block number * If the timestamp is before than the significant block return, returns twice this significant block number * * @param timestamp timestamp to search from * @return {blockBefore, blockAfter} or null if the timestamp is after the last ethereum block */ public async getBlockNumbersFromTimestamp( timestamp: number, ): Promise<StorageTypes.IBlockNumbersInterval> { // check if we have the blockTimestamp of the first significant block number if (!this.blockTimestamp[this.firstSignificantBlockNumber]) { // update the blockTimestamp cache with the first significant block await this.getBlockTimestamp(this.firstSignificantBlockNumber); } // update the second last block number in memory // we get the number of the second last block instead of the last block // because the information of the last block may not be retrieved by the web3 provider const secondLastBlockNumber: number = await this.getSecondLastBlockNumber(); // check if we have the blockTimestamp of the number of the second last block if (!this.blockTimestamp[secondLastBlockNumber]) { // update the blockTimestamp cache with the second last block await this.getBlockTimestamp(secondLastBlockNumber); } // if timestamp before first significant block, return the significant block if (timestamp <= this.blockTimestamp[this.firstSignificantBlockNumber]) { return { blockAfter: this.firstSignificantBlockNumber, blockBefore: this.firstSignificantBlockNumber, }; } // if timestamp after second last block, return secondLastBlockNumber if (timestamp > this.blockTimestamp[secondLastBlockNumber]) { return { blockAfter: secondLastBlockNumber, blockBefore: secondLastBlockNumber, }; } // Before doing the dichotomic search, we restrict the search to the two closest block we already know // the boundaries start with the first significant block and the last block const { result, lowBlockNumber, highBlockNumber } = this.getKnownBlockNumbersFromTimestamp( timestamp, secondLastBlockNumber, ); // if the result is not found on the known blocks, we search by dichotomy between the two closest known blocks return ( result || this.getBlockNumbersFromTimestampByDichotomy(timestamp, lowBlockNumber, highBlockNumber) ); } /** * Gets second last block number * @return blockNumber of the second last block */ public async getSecondLastBlockNumber(): Promise<number> { return (await this.getLastBlockNumber()) - 1; } /** * Gets the number of confirmation from a blockNumber * @return blockNumber of the last block */ public async getConfirmationNumber(blockNumber: number): Promise<number> { try { return (await this.getLastBlockNumber()) - blockNumber; } catch (e) { throw Error(`Error getting the confirmation number: ${e}`); } } /** * Get a block from ethereum * * @param blockNumber The block number * @returns An Ethereum block */ public async getBlock(blockNumber: number | string): Promise<any> { return Utils.retry(this.eth.getBlock, { context: this.eth, maxRetries: this.maxRetries, retryDelay: this.retryDelay, })(blockNumber); } /** * Gets the two known block numbers surrounding a timestamp * * @param timestamp timestamp to search from * @param lastBlockNumber last block number known * @returns */ private getKnownBlockNumbersFromTimestamp( timestamp: number, lastBlockNumber: number, ): { result: StorageTypes.IBlockNumbersInterval | null; lowBlockNumber: number; highBlockNumber: number; } { let lowBlockNumber = this.firstSignificantBlockNumber; let highBlockNumber = lastBlockNumber; let currentBlockNumber = this.firstSignificantBlockNumber; let currentBlockTimestamp; let result: StorageTypes.IBlockNumbersInterval | null = null; let foundKnownBoundaries = false; // We iterate on the known blocks from the first significant block until we found a blockTimestamp bigger than the timestamp while (!foundKnownBoundaries) { currentBlockTimestamp = this.blockTimestamp[currentBlockNumber]; // if the block is unknown yet, we skip it if (currentBlockTimestamp) { // if we are lucky a block we know has the exact same timestamp if (currentBlockTimestamp === timestamp) { result = { blockBefore: currentBlockNumber, blockAfter: currentBlockNumber }; foundKnownBoundaries = true; } else { // otherwise we restrict the boundaries lowBlockNumber = highBlockNumber; highBlockNumber = currentBlockNumber; // If the current timestamp is bigger than the one we research, // it means we have the best boundaries from what we already know if (currentBlockTimestamp > timestamp) { foundKnownBoundaries = true; } } } currentBlockNumber++; } return { result, lowBlockNumber, highBlockNumber }; } /** * Gets the two block numbers surrounding a timestamp * This is done by a dichotomic search between two blocks * * @param timestamp timestamp to search from * @param lowBlockNumber low boundary * @param highBlockNumber high boundary * @returns */ private async getBlockNumbersFromTimestampByDichotomy( timestamp: number, lowBlockNumber: number, highBlockNumber: number, ): Promise<StorageTypes.IBlockNumbersInterval> { let result: StorageTypes.IBlockNumbersInterval | null = null; // if blocks not found yet, we do a dichotomic search between the two closest known blocks while (!result) { // Picks the block in the middle of the two closest known blocks const currentBlockNumber = lowBlockNumber + Math.floor((highBlockNumber - lowBlockNumber) / 2); // Gets the timestamp of the block and stores it const currentBlockTimestamp = await this.getBlockTimestamp(currentBlockNumber); // Restricts the boundaries if (currentBlockTimestamp < timestamp) { lowBlockNumber = currentBlockNumber; } else if (currentBlockTimestamp > timestamp) { highBlockNumber = currentBlockNumber; } else { // If we are lucky, the timestamp is equal to the block timestamp result = { blockBefore: currentBlockNumber, blockAfter: currentBlockNumber }; break; } // If we are not lucky, we wait to have the two block surrounding the timestamp if (highBlockNumber === lowBlockNumber + 1) { result = { blockBefore: lowBlockNumber, blockAfter: highBlockNumber }; } } return result; } }
the_stack
import pull from "lodash.pull"; import { splitEasy } from "csv-split-easy"; import currency from "currency.js"; import findType from "./util/findType"; interface Res { res: string[][]; msgContent: null | string; msgType: null | string; } /** * Sorts double-entry bookkeeping CSV coming from internet banking */ function sort(input: string): Res { let msgContent = null; let msgType = null; // step 1. // =========================== // depends what was passed in, if (typeof input !== "string") { throw new TypeError( `csv-sort/csvSort(): [THROW_ID_01] The input is of a wrong type! We accept either string of array of arrays. We got instead: ${typeof input}, equal to:\n${JSON.stringify( input, null, 4 )}` ); } else if (!input.trim()) { return { res: [[""]], msgContent, msgType }; } let content = splitEasy(input); // step 2. // =========================== // - iterate from the bottom // - calculate schema as you go to save calculation rounds // - first row can have different amount of columns // - think about 2D trim feature let schema: (string | string[])[] = []; let stateHeaderRowPresent = false; let stateDataColumnRowLengthIsConsistent = true; const stateColumnsContainingSameValueEverywhere = []; // used for 2D trimming: let indexAtWhichEmptyCellsStart: number | null = null; for (let i = content.length - 1; i >= 0; i--) { console.log(`052 content[${i}] = ${content[i]}`); if (!schema.length) { // prevention against last blank row: /* istanbul ignore next */ if (content[i].length !== 1 || content[i][0] !== "") { for (let y = 0, len = content[i].length; y < len; y++) { schema.push(findType(content[i][y].trim())); if ( indexAtWhichEmptyCellsStart === null && findType(content[i][y].trim()) === "empty" ) { indexAtWhichEmptyCellsStart = y; } if ( indexAtWhichEmptyCellsStart !== null && findType(content[i][y].trim()) !== "empty" ) { indexAtWhichEmptyCellsStart = null; } } } } else { if (i === 0) { // Check is this header row. // Header rows should consist of only text content. // Let's iterate through all elements and find out. stateHeaderRowPresent = content[i].every( (el) => findType(el) === "text" || findType(el) === "empty" ); // if schema was calculated (this means there's header row and at least one content row), // find out if the column length in the header differs from schema's // if (stateHeaderRowPresent && (schema.length !== content[i].length)) { // } } /* istanbul ignore else */ if (!stateHeaderRowPresent && schema.length !== content[i].length) { stateDataColumnRowLengthIsConsistent = false; } let perRowIndexAtWhichEmptyCellsStart = null; for (let y = 0, len = content[i].length; y < len; y++) { // trim /* istanbul ignore else */ if ( perRowIndexAtWhichEmptyCellsStart === null && findType(content[i][y].trim()) === "empty" ) { perRowIndexAtWhichEmptyCellsStart = y; } /* istanbul ignore else */ if ( perRowIndexAtWhichEmptyCellsStart !== null && findType(content[i][y].trim()) !== "empty" ) { perRowIndexAtWhichEmptyCellsStart = null; } // checking schema /* istanbul ignore else */ if ( findType(content[i][y].trim()) !== schema[y] && !stateHeaderRowPresent ) { const toAdd = findType(content[i][y].trim()); /* istanbul ignore else */ if (Array.isArray(schema[y])) { if (!schema[y].includes(toAdd)) { (schema[y] as string[]).push(findType(content[i][y].trim())); } } else if (schema[y] !== toAdd) { const temp = schema[y]; schema[y] = []; (schema[y] as string[]).push(temp as string); (schema[y] as string[]).push(toAdd); } } } // when row has finished, get the perRowIndexAtWhichEmptyCellsStart // that's to cover cases where last row got schema calculated, but it // had more empty columns than the following rows: // // [8, 9, 0, 1, , ] // [4, 5, 6, 7, , ] <<< perRowIndexAtWhichEmptyCellsStart would be 3 (indexes start at zero) // [1, 2, 3, , , ] <<< indexAtWhichEmptyCellsStart would be here 2 (indexes start at zero) // // as a result, indexAtWhichEmptyCellsStart above would be assigned to 3, not 2 // // That's still an achievement, we "trimmed" CSV by two places. // I'm saying "trimmed", but we're not really trimming yet, we're only // setting inner variable which we will later use to limit the traversal, // so algorithm skips those empty columns. // /* istanbul ignore next */ if ( indexAtWhichEmptyCellsStart !== null && perRowIndexAtWhichEmptyCellsStart !== null && perRowIndexAtWhichEmptyCellsStart > indexAtWhichEmptyCellsStart && (!stateHeaderRowPresent || (stateHeaderRowPresent && i !== 0)) ) { indexAtWhichEmptyCellsStart = perRowIndexAtWhichEmptyCellsStart; } } } /* istanbul ignore else */ if (!indexAtWhichEmptyCellsStart) { indexAtWhichEmptyCellsStart = (schema as string[]).length; } // find out at which index non-empty columns start. This is effectively left-side trimming. let nonEmptyColsStartAt = 0; for (let i = 0, len = schema.length; i < len; i++) { if (schema[i] === "empty") { nonEmptyColsStartAt = i; } else { break; } } // if there are empty column in front, trim (via slice) both content and schema /* istanbul ignore else */ if (nonEmptyColsStartAt !== 0) { content = content.map((arr) => arr.slice(nonEmptyColsStartAt + 1, indexAtWhichEmptyCellsStart as number) ); schema = schema.slice(nonEmptyColsStartAt + 1, indexAtWhichEmptyCellsStart); } // step 3. // =========================== // CHALLENGE: without any assumptions, identify "current balance" and "debit", // "credit" columns by analysing their values. // // - double entry accounting rows will have the "current balance" which will // be strictly numeric, and will be present across all rows. These are the // two first signs of a "current balance" column. // - "current balance" should also match up with at least one field under it, // if subracted/added the value from one field in its row // swoop in traversing the schema array to get "numeric" columns: // ---------------- const numericSchemaColumns: number[] = []; let balanceColumnIndex; schema.forEach((colType, i) => { if (colType === "numeric") { numericSchemaColumns.push(i); } }); const traverseUpToThisIndexAtTheTop = stateHeaderRowPresent ? 1 : 0; if (numericSchemaColumns.length === 1) { // Bob's your uncle, the only numeric column is your Balance column balanceColumnIndex = numericSchemaColumns[0]; } else if (numericSchemaColumns.length === 0) { throw new Error( 'csv-sort/csvSort(): [THROW_ID_03] Your CSV file does not contain numeric-only columns and computer was not able to detect the "Balance" column!' ); } else { // So (numericSchemaColumns > 0) and we'll have to do some work. // Fine. // // Clone numericSchemaColumns array, remove columns that have the same value // among consecutive rows. // For example, accounting CSV's will have "Account number" repeated. // Balance is never the same on two rows, otherwise what's the point of // accounting if nothing happened? // Traverse the CSV vertically on each column from numericSchemaColumns and // find out `balanceColumnIndex`: // ---------------- let potentialBalanceColumnIndexesList = Array.from(numericSchemaColumns); // iterate through `potentialBalanceColumnIndexesList` const deleteFromPotentialBalanceColumnIndexesList = []; for ( let i = 0, len = potentialBalanceColumnIndexesList.length; i < len; i++ ) { // if any two rows are in sequence currently and they are equal, this column is out const suspectedBalanceColumnsIndexNumber = potentialBalanceColumnIndexesList[i]; // we traverse column suspected to be "Balance" with index `index` vertically, // from the top to bottom. Depending if there's heading row, we start at 0 or 1, // which is set by `traverseUpToThisIndexAtTheTop`. // We will look for two rows having the same value. If it's found that column is // not "Balance": // EASY ATTEMPT TO RULE-OUT NOT-BALANCE COLUMNS let previousValue; // to check if two consecutive are the same let lookForTwoEqualAndConsecutive = true; let firstValue; // to check if all are the same let lookForAllTheSame = true; for ( let rowNum = traverseUpToThisIndexAtTheTop, len2 = content.length; rowNum < len2; rowNum++ ) { // 1. check for two consecutive equal values /* istanbul ignore else */ if (lookForTwoEqualAndConsecutive) { // deliberate == to catch undefined and null if (previousValue == null) { previousValue = content[rowNum][suspectedBalanceColumnsIndexNumber]; } else if ( previousValue === content[rowNum][suspectedBalanceColumnsIndexNumber] ) { // potentialBalanceColumnIndexesList.splice(suspectedBalanceColumnsIndexNumber, 1) // don't mutate the `potentialBalanceColumnIndexesList`, do it later. // Let's compile TO-DELETE list instead: deleteFromPotentialBalanceColumnIndexesList.push( suspectedBalanceColumnsIndexNumber ); lookForTwoEqualAndConsecutive = false; } else { previousValue = content[rowNum][suspectedBalanceColumnsIndexNumber]; } } // 2. also, tell if ALL values are the same: /* istanbul ignore else */ if (lookForAllTheSame) { // deliberate == to catch undefined and null if (firstValue == null) { firstValue = content[rowNum][suspectedBalanceColumnsIndexNumber]; } else if ( content[rowNum][suspectedBalanceColumnsIndexNumber] !== firstValue ) { lookForAllTheSame = false; } } if (!lookForTwoEqualAndConsecutive) { break; } } /* istanbul ignore else */ if (lookForAllTheSame) { stateColumnsContainingSameValueEverywhere.push( suspectedBalanceColumnsIndexNumber ); } } // now mutate the `potentialBalanceColumnIndexesList` using // `deleteFromPotentialBalanceColumnIndexesList`: potentialBalanceColumnIndexesList = pull( potentialBalanceColumnIndexesList, ...deleteFromPotentialBalanceColumnIndexesList ); /* istanbul ignore else */ if (potentialBalanceColumnIndexesList.length === 1) { balanceColumnIndex = potentialBalanceColumnIndexesList[0]; } else if (potentialBalanceColumnIndexesList.length === 0) { throw new Error( 'csv-sort/csvSort(): [THROW_ID_04] The computer can\'t find the "Balance" column! It saw some numeric-only columns, but they all seem to have certain rows with the same values as rows right below/above them!' ); } else { // TODO - continue processing interpolating horizontally and vertically. // // // COMPLEX ATTEMPT TO RULE-OUT NOT-BALANCE COLUMNS // // // zzz } // at this point 99% of normal-size, real-life bank account CSV's should have // "Balance" column identified because there will be both "Credit" and "Debit" // transaction rows which will be not exclusively numeric, but ["empty", "numeric"] type. // Even Lloyds Business banking CSV's that output account numbers // will have "Balance" column identified this stage. } if (!balanceColumnIndex) { throw new Error( "csv-sort/csvSort(): [THROW_ID_05] Sadly computer couldn't find its way in this CSV and had to stop working on it." ); } // step 4. // =========================== // query the schema and find out potential Credit/Debit columns // take schema, filter all indexes that are equal to or are arrays and have // "numeric" among their values, then remove the index of "Balance" column: const potentialCreditDebitColumns = pull( Array.from( schema.reduce((result, el, index) => { if ( (typeof el === "string" && el === "numeric") || (Array.isArray(el) && el.includes("numeric")) ) { (result as any).push(index); } return result; }, []) ), balanceColumnIndex as any, ...stateColumnsContainingSameValueEverywhere ); // step 5. // =========================== const resContent = []; // Now that we know the `balanceColumnIndex`, traverse the CSV rows again, // assembling a new array // step 5.1. Put the last row into the new array. // --------------------------------------------------------------------------- // Worst case scenario, if it doesn't match with anything, we'll throw in the end. // For now, let's assume CSV is correct, only rows are mixed. resContent.push( content[content.length - 1].slice(0, indexAtWhichEmptyCellsStart) ); console.log( `378 after push ${`\u001b[${33}m${`resContent`}\u001b[${39}m`} = ${JSON.stringify( resContent, null, 4 )}` ); const usedUpRows: number[] = []; const bottom = stateHeaderRowPresent ? 1 : 0; for (let y = content.length - 2; y >= bottom; y--) { // for each row above the last-one (which is already in place), we'll traverse // all the rows above to find the match. // go through all the rows and pick the right row which matches to the above: console.log( `\n\u001b[${90}m${` S`}\u001b[${39}m`.repeat(15) ); console.log( `396 \u001b[${90}m${`████████████████ y = ${y} ████████████████`}\u001b[${39}m` ); for ( let suspectedRowsIndex = content.length - 2; suspectedRowsIndex >= bottom; suspectedRowsIndex-- ) { console.log(`\n\n\n\n\n ${`\u001b[${90}m${`██`}\u001b[${39}m`}`); console.log( `406 \u001b[${90}m${`=============== suspected row: ${JSON.stringify( content[suspectedRowsIndex], null, 0 )} (idx. ${suspectedRowsIndex}) ===============`}\u001b[${39}m` ); if (!usedUpRows.includes(suspectedRowsIndex)) { // go through each of the suspected Credit/Debit columns: let thisRowIsDone = false; for ( let suspectedColIndex = 0, len = potentialCreditDebitColumns.length; suspectedColIndex < len; suspectedColIndex++ ) { console.log( `423 \u001b[${90}m${`--------------- suspectedColIndex = ${suspectedColIndex} ---------------`}\u001b[${39}m` ); let diffVal = null; if ( content[suspectedRowsIndex][ potentialCreditDebitColumns[suspectedColIndex] ] !== "" ) { diffVal = currency( content[suspectedRowsIndex][ potentialCreditDebitColumns[suspectedColIndex] ] ); console.log( `437 SET ${`\u001b[${33}m${`diffVal`}\u001b[${39}m`} = ${JSON.stringify( diffVal, null, 4 )}` ); } let totalVal = null; /* istanbul ignore else */ if (content[suspectedRowsIndex][balanceColumnIndex] !== "") { totalVal = currency( content[suspectedRowsIndex][balanceColumnIndex] ); console.log( `452 SET ${`\u001b[${33}m${`totalVal`}\u001b[${39}m`} = ${JSON.stringify( totalVal, null, 4 )}` ); } let topmostResContentBalance = null; /* istanbul ignore else */ if (resContent[0][balanceColumnIndex] !== "") { topmostResContentBalance = currency( resContent[0][balanceColumnIndex] ).format(); console.log( `467 SET ${`\u001b[${33}m${`topmostResContentBalance`}\u001b[${39}m`} = ${JSON.stringify( topmostResContentBalance, null, 4 )}` ); } let currentRowsDiffVal = null; /* istanbul ignore else */ if ( resContent[resContent.length - 1][ potentialCreditDebitColumns[suspectedColIndex] ] !== "" ) { currentRowsDiffVal = currency( resContent[resContent.length - 1][ potentialCreditDebitColumns[suspectedColIndex] ] ).format(); console.log( `${`\u001b[${33}m${`currentRowsDiffVal`}\u001b[${39}m`} = ${JSON.stringify( currentRowsDiffVal, null, 4 )}` ); } let lastResContentRowsBalance = null; /* istanbul ignore else */ if (resContent[resContent.length - 1][balanceColumnIndex] !== "") { lastResContentRowsBalance = currency( resContent[resContent.length - 1][balanceColumnIndex] ); } console.log("\n\n\n\n\n"); console.log( `506 ${`\u001b[${33}m${`diffVal`}\u001b[${39}m`} = ${JSON.stringify( diffVal, null, 4 )}` ); console.log( `case 1 totalVal=${totalVal} + diffVal=${diffVal} === topmostResContentBalance=${topmostResContentBalance}` ); console.log( `case 2 totalVal=${totalVal} - diffVal=${diffVal} === topmostResContentBalance=${topmostResContentBalance}` ); console.log( `case 3 lastResContentRowsBalance=${lastResContentRowsBalance} + currentRowsDiffVal=${currentRowsDiffVal} === totalVal=${totalVal}` ); console.log( `case 4 lastResContentRowsBalance=${lastResContentRowsBalance} - currentRowsDiffVal=${currentRowsDiffVal} === totalVal=${totalVal}` ); /* istanbul ignore else */ if ( diffVal && (totalVal as currency).add(diffVal).format() === topmostResContentBalance ) { console.log(`532 ADD THIS ROW ABOVE EVERYTHING`); // ADD THIS ROW ABOVE EVERYTHING // add this row above the current HEAD in resContent lines array (index `0`) resContent.unshift( content[suspectedRowsIndex].slice(0, indexAtWhichEmptyCellsStart) ); usedUpRows.push(suspectedRowsIndex); thisRowIsDone = true; break; } else if ( diffVal && (totalVal as currency).subtract(diffVal).format() === topmostResContentBalance ) { // ADD THIS ROW ABOVE EVERYTHING resContent.unshift( content[suspectedRowsIndex].slice(0, indexAtWhichEmptyCellsStart) ); usedUpRows.push(suspectedRowsIndex); thisRowIsDone = true; break; } else if ( currentRowsDiffVal && (lastResContentRowsBalance as currency) .add(currentRowsDiffVal) .format() === (totalVal as currency).format() ) { // ADD THIS ROW BELOW EVERYTHING resContent.push( content[suspectedRowsIndex].slice(0, indexAtWhichEmptyCellsStart) ); usedUpRows.push(suspectedRowsIndex); thisRowIsDone = true; break; } else if ( currentRowsDiffVal && (lastResContentRowsBalance as currency) .subtract(currentRowsDiffVal) .format() === (totalVal as currency).format() ) { // ADD THIS ROW BELOW EVERYTHING resContent.push( content[suspectedRowsIndex].slice(0, indexAtWhichEmptyCellsStart) ); usedUpRows.push(suspectedRowsIndex); thisRowIsDone = true; break; } console.log("----------"); console.log( `583 ${`\u001b[${33}m${`thisRowIsDone`}\u001b[${39}m`} = ${JSON.stringify( thisRowIsDone, null, 4 )}` ); } /* istanbul ignore else */ if (thisRowIsDone) { thisRowIsDone = false; break; } } } console.log( `599 ${`\u001b[${32}m${`██`}\u001b[${39}m`} ENDING \u001b[${33}m${`resContent`}\u001b[${39}m = ${JSON.stringify( resContent, null, 4 )}` ); } // restore title row if present /* istanbul ignore else */ if (stateHeaderRowPresent) { // trim header row of trailing empty columns if they protrude outside of the (consistent row length) schema if ( stateDataColumnRowLengthIsConsistent && content[0].length > schema.length ) { content[0].length = schema.length; } // push header row on top of the results array: resContent.unshift(content[0].slice(0, indexAtWhichEmptyCellsStart)); } /* istanbul ignore else */ if (content.length - (stateHeaderRowPresent ? 2 : 1) !== usedUpRows.length) { msgContent = "Not all rows were recognised!"; msgType = "alert"; } return { res: resContent, msgContent, msgType, }; } export { sort };
the_stack
import { KeyboardEvent as ReactKeyboardEvent, MouseEvent as ReactMouseEvent, PointerEvent as ReactPointerEvent, WheelEvent as ReactWheelEvent, } from "react"; import { players, theme } from "../../default"; import Config from "utils/AUMT/Config"; import InputHandler from "utils/AUMT/InputHandler"; import Loading from "utils/AUMT/Scenes/Loading"; import { MOUSE_BUTTON } from "constants/mouse"; import MapScene from "utils/AUMT/Scenes/MapScene"; import MiraHQ from "utils/AUMT/Scenes/Maps/MiraHQ"; import SceneManager from "utils/AUMT/SceneManager"; import Vector from "utils/math/Vector"; describe("Scenes/Map tests", () => { let loading: Loading; let map: MapScene; let contextRestoreSpy: jest.SpyInstance; const mockFn = jest.fn(); beforeEach(() => { jest.clearAllMocks(); const canvas = document.createElement("canvas").getContext("2d"); if (canvas) { Config.setContext(canvas); contextRestoreSpy = jest.spyOn(Config.getContext(), "restore"); Config.setTheme(theme); Config.updatePlayers(players, 3, 5, 1); loading = new Loading(); Config.setLoaded(); loading.update(); map = new MapScene("MiraHQ", 1); } }); test("onEnter should set offset and scale", () => { map.onEnter(); expect(Config.getOffset()).toEqual({ x: 0, y: 0 }); expect(Config.getScale()).toEqual({ x: Infinity, y: Infinity }); }); test("onExit should set offset and scale to the current offset and scale in Config", () => { map.onExit(); expect(Config.getOffset()).toEqual({ x: 0, y: 0 }); expect(Config.getScale()).toEqual({ x: 1, y: 1 }); }); test("getMenuVisible should return false", () => { expect(map.getMenuVisible()).toBeFalsy(); }); test("render should have called context.restore 63 times", () => { map.render(); expect(contextRestoreSpy).toHaveBeenCalledTimes(63); }); test("updateText should set entities' text to maps.loading", () => { const mira = new MiraHQ(); mira.updateText(); mira .getTexts() .forEach((value, key) => expect(value.getText()).toEqual(`maps.${key}`)); }); describe("update() tests", () => { function pickValidColor(visible = true) { if (visible) map.setMenuVisible(true); const event = { preventDefault: () => mockFn(), clientX: 333.417391450761, clientY: 808.3973227262256, currentTarget: { width: 1920, height: 1080, getBoundingClientRect: () => { return { left: 0, top: 0, width: 1920, height: 1080, }; }, }, } as ReactPointerEvent<HTMLCanvasElement>; map.getMenu().setCenter(new Vector(355.1071646949839, 875.382203260517)); InputHandler.onPointerMove(event); } const mouseEvent = (button: MOUSE_BUTTON | string) => { return { button, preventDefault: () => mockFn(), currentTarget: { focus: () => mockFn(), }, } as ReactPointerEvent<HTMLCanvasElement>; }; const keyboardEvent = (key: string) => { return { preventDefault: () => mockFn(), key, } as ReactKeyboardEvent<HTMLCanvasElement>; }; const restoreStateSpy = jest.spyOn(InputHandler, "restoreState"); const screenToWorldSpy = jest.spyOn(Config, "screenToWorld"); beforeEach(() => { InputHandler.restoreState(); InputHandler.resetMouseButtons(); jest.clearAllMocks(); }); test("should do nothing if menu is invisible", () => { const event = { preventDefault: () => mockFn(), clientX: 600, clientY: 540, currentTarget: { width: 1920, height: 1080, getBoundingClientRect: () => { return { left: 0, top: 0, width: 1920, height: 1080, }; }, }, } as ReactPointerEvent<HTMLCanvasElement>; const restoreStateSpy = jest.spyOn(InputHandler, "restoreState"); InputHandler.onPointerMove(event); map.update(4); expect(restoreStateSpy).toHaveBeenCalledTimes(1); }); test("menu === visible, update with MOUSE_BUTTON.RIGHT === true", () => { // sets MOUSE_BUTTON.RIGHT === true InputHandler.onPointerDown(mouseEvent(MOUSE_BUTTON.RIGHT)); pickValidColor(); map.update(4); expect(restoreStateSpy).toHaveBeenCalledTimes(1); InputHandler.onPointerUp(mouseEvent(MOUSE_BUTTON.RIGHT)); }); test("menu === visible, MOUSE_BUTTON.LEFT === true, valid color", () => { pickValidColor(); // sets MOUSE_BUTTON.LEFT === true InputHandler.onPointerDown(mouseEvent(MOUSE_BUTTON.LEFT)); map.update(4); expect(screenToWorldSpy).toHaveBeenCalledTimes(4); expect(restoreStateSpy).toHaveBeenCalledTimes(1); }); test("menu !== visible, MOUSE_BUTTON.LEFT === true, valid color, wheel < 0", () => { const wheelEvent = { preventDefault: () => mockFn(), deltaY: -25, } as ReactWheelEvent<HTMLCanvasElement>; // sets MOUSE_BUTTON.LEFT === true InputHandler.onPointerDown(mouseEvent(MOUSE_BUTTON.LEFT)); pickValidColor(false); InputHandler.onWheel(wheelEvent); const screenToWorldSpy = jest.spyOn(Config, "screenToWorld"); map.update(4); expect(screenToWorldSpy).toHaveBeenCalledTimes(5); expect(map.getPanningPosition()).toStrictEqual( InputHandler.getMousePosition() ); }); test("menu !== visible, MOUSE_BUTTON.LEFT === true, valid color, wheel > 0", () => { const wheelEvent = { preventDefault: () => mockFn(), deltaY: 156, } as ReactWheelEvent<HTMLCanvasElement>; // sets MOUSE_BUTTON.LEFT === true InputHandler.onPointerDown(mouseEvent(MOUSE_BUTTON.LEFT)); pickValidColor(false); InputHandler.onWheel(wheelEvent); const screenToWorldSpy = jest.spyOn(Config, "screenToWorld"); map.update(4); expect(screenToWorldSpy).toHaveBeenCalledTimes(5); expect(map.getPanningPosition()).toStrictEqual( InputHandler.getMousePosition() ); // running update again // should check the if statement // (this.panning && InputHandler.getMouseButtons().LEFT) map.update(2); expect(map.getPanningPosition()).toStrictEqual( InputHandler.getMousePosition() ); }); test("menu !== visible, MOUSE_BUTTON.LEFT === true, mousePosition inside this.hub.entities[0] should set current scene to Menu", () => { // sets MOUSE_BUTTON.LEFT === true InputHandler.onPointerDown(mouseEvent(MOUSE_BUTTON.LEFT)); const event = { preventDefault: () => mockFn(), clientX: 1816.2036022263742, clientY: 82.72805414390622, currentTarget: { width: 1920, height: 1080, getBoundingClientRect: () => { return { left: 0, top: 0, width: 1920, height: 1080, }; }, }, } as ReactPointerEvent<HTMLCanvasElement>; InputHandler.onPointerMove(event); map.update(4); expect(SceneManager.getCurrentScene()).toEqual("Menu"); }); test("menu !== visible, doubleClicked === true, invalid color should set this.center to current mouse position", () => { // sets MOUSE_BUTTON.RIGHT === true InputHandler.onPointerDown(mouseEvent(MOUSE_BUTTON.RIGHT)); const event = { preventDefault: () => mockFn(), clientX: 1816.2036022263742, clientY: 82.72805414390622, currentTarget: { width: 1920, height: 1080, getBoundingClientRect: () => { return { left: 0, top: 0, width: 1920, height: 1080, }; }, }, } as ReactPointerEvent<HTMLCanvasElement>; InputHandler.onPointerMove(event); map.update(2); expect(InputHandler.getMousePosition()).toEqual( new Vector(1816.2036022263742, 82.72805414390622) ); }); test("menu !== visible, MOUSE_BUTTON.RIGHT === true, invalid color should set this.center to current mouse position", () => { // sets MOUSE_BUTTON.RIGHT === true InputHandler.onPointerDown(mouseEvent(MOUSE_BUTTON.RIGHT)); const event = { preventDefault: () => mockFn(), clientX: 1816.2036022263742, clientY: 82.72805414390622, currentTarget: { width: 1920, height: 1080, getBoundingClientRect: () => { return { left: 0, top: 0, width: 1920, height: 1080, }; }, }, } as ReactPointerEvent<HTMLCanvasElement>; InputHandler.onPointerMove(event); map.update(2); expect(InputHandler.getMousePosition()).toEqual( new Vector(1816.2036022263742, 82.72805414390622) ); }); test("menu === visible, doubleClicked === true should clear this.players", () => { // sets MOUSE_BUTTON.LEFT === true InputHandler.onPointerDown(mouseEvent(MOUSE_BUTTON.LEFT)); pickValidColor(); // adds player to this.players map.update(4); expect(map.getPlayers().entities).toHaveLength(1); InputHandler.onDoubleClick({ preventDefault: () => mockFn(), } as ReactMouseEvent<HTMLCanvasElement>); map.update(1); expect(map.getPlayers().entities).toHaveLength(0); }); test("hitting key 'M' or 'm' should change scene to 'Menu'", () => { SceneManager.changeScene("MiraHQ"); InputHandler.onKeyDown(keyboardEvent("M")); map.update(0); expect(SceneManager.getCurrentScene()).toEqual("Menu"); InputHandler.onKeyUp(keyboardEvent("M")); SceneManager.changeScene("MiraHQ"); InputHandler.onKeyDown(keyboardEvent("m")); map.update(2); expect(SceneManager.getCurrentScene()).toEqual("Menu"); InputHandler.onKeyUp(keyboardEvent("m")); }); test("hitting key 'C' should should clear this.players", () => { pickValidColor(); // adds player to this.players map.update(4); expect(map.getPlayers().entities).toHaveLength(1); InputHandler.onKeyDown(keyboardEvent("C")); map.update(1); expect(map.getPlayers().entities).toHaveLength(0); InputHandler.onKeyUp(keyboardEvent("C")); }); test("hitting key 'c' should should clear this.players", () => { pickValidColor(); // adds player to this.players map.update(0); expect(map.getPlayers().entities).toHaveLength(1); InputHandler.onKeyDown(keyboardEvent("c")); map.update(1); expect(map.getPlayers().entities).toHaveLength(0); InputHandler.onKeyUp(keyboardEvent("c")); }); }); });
the_stack
import { ActionType, CardElement, Container, SerializationContext, ShowCardAction, ToggleVisibilityAction } from "./card-elements"; import * as Enums from "./enums"; import { NumProperty, property, PropertyBag, SerializableObjectSchema, Versions } from "./serialization"; import { GlobalRegistry, ElementSingletonBehavior } from "./registry"; import { TypeErrorType, ValidationEvent } from "./enums"; import { Strings } from "./strings"; import { Swiper, A11y, Autoplay, History, Keyboard, Navigation, Pagination, Scrollbar, SwiperOptions } from "swiper"; import * as Utils from "./utils"; import { GlobalSettings } from "./shared"; // Note: to function correctly, consumers need to have CSS from swiper/css, swiper/css/pagination, and // swiper/css/navigation export class CarouselPage extends Container { //#region Schema protected populateSchema(schema: SerializableObjectSchema) { super.populateSchema(schema); // `style`, `bleed`, `isVisible` are not supported in CarouselPage schema.remove(Container.styleProperty); schema.remove(Container.bleedProperty); schema.remove(Container.isVisibleProperty); } //#endregion protected internalRender(): HTMLElement | undefined { const carouselSlide: HTMLElement = document.createElement("div"); carouselSlide.className = this.hostConfig.makeCssClassName("swiper-slide"); // `isRtl()` will set the correct value of rtl by reading the value from the parents this.rtl = this.isRtl(); const renderedElement = super.internalRender(); Utils.appendChild(carouselSlide, renderedElement); return carouselSlide; } getForbiddenActionTypes(): ActionType[] { return [ShowCardAction, ToggleVisibilityAction]; } protected internalParse(source: any, context: SerializationContext) { super.internalParse(source, context); this.setShouldFallback(false); } protected shouldSerialize(_context: SerializationContext): boolean { return true; } getJsonTypeName(): string { return "CarouselPage"; } get isStandalone(): boolean { return false; } } export class Carousel extends Container { //#region Schema protected populateSchema(schema: SerializableObjectSchema) { super.populateSchema(schema); // `style`, `bleed`, `isVisible` are not supported in Carousel schema.remove(Container.styleProperty); schema.remove(Container.bleedProperty); schema.remove(Container.isVisibleProperty); } static readonly timerProperty = new NumProperty(Versions.v1_6, "timer", undefined); @property(Carousel.timerProperty) get timer(): number | undefined { let timer = this.getValue(Carousel.timerProperty); if (timer && timer < this.hostConfig.carousel.minAutoplayDelay) { console.warn(Strings.errors.tooLittleTimeDelay); timer = this.hostConfig.carousel.minAutoplayDelay; } return timer; } set timer(value: number | undefined) { if (value && value < this.hostConfig.carousel.minAutoplayDelay) { console.warn(Strings.errors.tooLittleTimeDelay); this.timer = this.hostConfig.carousel.minAutoplayDelay; } else { this.timer = value; } } //#endregion private _pages: CarouselPage[] = []; private _renderedPages: CarouselPage[]; protected forbiddenChildElements(): string[] { return [ ToggleVisibilityAction.JsonTypeName, ShowCardAction.JsonTypeName, "Media", "ActionSet", "Input.Text", "Input.Date", "Input.Time", "Input.Number", "Input.ChoiceSet", "Input.Toggle", ...super.forbiddenChildElements() ]; } getJsonTypeName(): string { return "Carousel"; } getItemCount(): number { return this._pages.length; } getItemAt(index: number): CardElement { return this._pages[index]; } removeItem(item: CardElement): boolean { if (item instanceof CarouselPage) { const itemIndex = this._pages.indexOf(item); if (itemIndex >= 0) { this._pages.splice(itemIndex, 1); item.setParent(undefined); this.updateLayout(); return true; } } return false; } getFirstVisibleRenderedItem(): CardElement | undefined { if (this.renderedElement && this._renderedPages?.length > 0) { return this._renderedPages[0]; } else { return undefined; } } getLastVisibleRenderedItem(): CardElement | undefined { if (this.renderedElement && this._renderedPages?.length > 0) { return this._renderedPages[this._renderedPages.length - 1]; } else { return undefined; } } get currentPageId(): string | undefined { if (this._carousel?.slides?.length) { const activeSlide = this._carousel.slides[this._carousel.activeIndex] as HTMLElement; return activeSlide.id; } return undefined; } protected internalParse(source: any, context: SerializationContext) { super.internalParse(source, context); this._pages = []; this._renderedPages = []; const jsonPages = source["pages"]; if (Array.isArray(jsonPages)) { for (const item of jsonPages) { const page = this.createCarouselPageInstance(item, context); if (page) { this._pages.push(page); } } } } protected internalToJSON(target: PropertyBag, context: SerializationContext) { super.internalToJSON(target, context); context.serializeArray(target, "pages", this._pages); } protected internalRender(): HTMLElement | undefined { this._renderedPages = []; if (this._pages.length <= 0) { return undefined; } const cardLevelContainer: HTMLElement = document.createElement("div"); const carouselContainer: HTMLElement = document.createElement("div"); carouselContainer.className = this.hostConfig.makeCssClassName("swiper", "ac-carousel"); const containerForAdorners: HTMLElement = document.createElement("div"); containerForAdorners.className = this.hostConfig.makeCssClassName("ac-carousel-container"); cardLevelContainer.appendChild(containerForAdorners); const carouselWrapper: HTMLElement = document.createElement("div"); carouselWrapper.className = this.hostConfig.makeCssClassName( "swiper-wrapper", "ac-carousel-card-container" ); carouselWrapper.style.display = "flex"; switch (this.getEffectiveVerticalContentAlignment()) { case Enums.VerticalAlignment.Top: carouselWrapper.style.alignItems = "flex-start"; break; case Enums.VerticalAlignment.Bottom: carouselWrapper.style.alignItems = "flex-end"; break; default: carouselWrapper.style.alignItems = "center"; break; } if (GlobalSettings.useAdvancedCardBottomTruncation) { // Forces the container to be at least as tall as its content. // // Fixes a quirk in Chrome where, for nested flex elements, the // inner element's height would never exceed the outer element's // height. This caused overflow truncation to break -- containers // would always be measured as not overflowing, since their heights // were constrained by their parents as opposed to truly reflecting // the height of their content. // // See the "Browser Rendering Notes" section of this answer: // https://stackoverflow.com/questions/36247140/why-doesnt-flex-item-shrink-past-content-size carouselWrapper.style.minHeight = "-webkit-min-content"; } const prevElementDiv: HTMLElement = document.createElement("div"); prevElementDiv.className = this.hostConfig.makeCssClassName( "swiper-button-prev", "ac-carousel-left" ); containerForAdorners.appendChild(prevElementDiv); const nextElementDiv: HTMLElement = document.createElement("div"); nextElementDiv.className = this.hostConfig.makeCssClassName( "swiper-button-next", "ac-carousel-right" ); containerForAdorners.appendChild(nextElementDiv); const pagination: HTMLElement = document.createElement("div"); pagination.className = this.hostConfig.makeCssClassName( "swiper-pagination", "ac-carousel-pagination" ); containerForAdorners.appendChild(pagination); const requestedNumberOfPages: number = Math.min( this._pages.length, this.hostConfig.carousel.maxCarouselPages ); if (this._pages.length > this.hostConfig.carousel.maxCarouselPages) { console.warn(Strings.errors.tooManyCarouselPages); } if (this._pages.length > 0) { for (let i = 0; i < requestedNumberOfPages; i++) { const page = this._pages[i]; const renderedItem = this.isElementAllowed(page) ? page.render() : undefined; renderedItem?.classList.add("ac-carousel-page"); renderedItem?.children[0]?.classList.add("ac-carousel-page-container"); if (renderedItem) { Utils.appendChild(carouselWrapper, renderedItem); this._renderedPages.push(page); } } } carouselContainer.appendChild(carouselWrapper); carouselContainer.tabIndex = 0; containerForAdorners.appendChild(carouselContainer); // `isRtl()` will set the correct value of rtl by reading the value from the parents this.rtl = this.isRtl(); this.applyRTL(carouselContainer); this.initializeCarouselControl( carouselContainer, nextElementDiv, prevElementDiv, pagination, this.rtl ); cardLevelContainer.addEventListener( "keydown", (_event) => { // we don't need to check which key was pressed, we only need to reinit swiper once, then remove this event listener const activeIndex = this._carousel?.activeIndex; this.initializeCarouselControl( carouselContainer, nextElementDiv, prevElementDiv, pagination, this.rtl ); if (activeIndex) { this._carousel?.slideTo(activeIndex); } }, { once: true } ); return this._renderedPages.length > 0 ? cardLevelContainer : undefined; } private _carousel?: Swiper; private initializeCarouselControl( carouselContainer: HTMLElement, nextElement: HTMLElement, prevElement: HTMLElement, paginationElement: HTMLElement, rtl: boolean | undefined ): void { const swiperOptions: SwiperOptions = { loop: true, modules: [Navigation, Pagination, Scrollbar, A11y, History, Keyboard], pagination: { el: paginationElement, clickable: true }, navigation: { prevEl: rtl === undefined || !rtl ? prevElement : nextElement, nextEl: rtl === undefined || !rtl ? nextElement : prevElement }, a11y: { enabled: true }, keyboard: { enabled: true, onlyInViewport: true } }; if (this.timer && !this.isDesignMode()) { swiperOptions.modules?.push(Autoplay); swiperOptions.autoplay = { delay: this.timer, pauseOnMouseEnter: true }; } const carousel: Swiper = new Swiper(carouselContainer, swiperOptions); // While the 'pauseOnMouseEnter' option should resume autoplay on // mouse exit it doesn't do it, so adding custom events to handle it carouselContainer.addEventListener("mouseenter", function (_event) { carousel.autoplay?.stop(); }); carouselContainer.addEventListener("mouseleave", function (_event) { carousel.autoplay?.start(); }); this._carousel = carousel; } private createCarouselPageInstance( source: any, context: SerializationContext ): CarouselPage | undefined { return context.parseCardObject<CarouselPage>( this, source, this.forbiddenChildElements(), !this.isDesignMode(), (typeName: string) => { return !typeName || typeName === "CarouselPage" ? new CarouselPage() : undefined; }, (typeName: string, _errorType: TypeErrorType) => { context.logParseEvent( undefined, ValidationEvent.ElementTypeNotAllowed, Strings.errors.elementTypeNotAllowed(typeName) ); } ); } } GlobalRegistry.defaultElements.register( "Carousel", Carousel, Versions.v1_6, ElementSingletonBehavior.Only );
the_stack
/* * Copyright(c) 2017 Microsoft Corporation. All rights reserved. * * This code is licensed under the MIT License (MIT). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /// <reference path="../../Common/typings/MicrosoftMaps/Microsoft.Maps.d.ts"/> interface IBasicTile { id: string; tileInfo: Microsoft.Maps.PyramidTileId; img: HTMLImageElement; } /** * A reusable class for overlaying HTML elements as pushpins on the map. */ class BasicTileLayer extends Microsoft.Maps.CustomOverlay { /********************** * Private Properties ***********************/ /** A variable to store the viewchange event handler id. */ private _viewChangeEventHandler: Microsoft.Maps.IHandlerId = null; /** A variable to store the viewchangeend event handler id. */ private _viewChangeEndEventHandler: Microsoft.Maps.IHandlerId = null; /** A variable to store the map resize event handler id. */ private _mapResizeEventHandler: Microsoft.Maps.IHandlerId = null; /** A variable to store a reference to the container for the HTML pushpins. */ private _container: HTMLElement = null; private _tileLayerOptions: Microsoft.Maps.ITileLayerOptions = { visible: true, mercator: null, opacity: 1, zIndex: 0, downloadTimeout: 10000 }; private _mapWidth: number; private _mapHeight: number; /********************** * Constructor ***********************/ /** * @constructor */ constructor(options: Microsoft.Maps.ITileLayerOptions) { super(); if (!options) { throw 'A tile layer options must be specified in a BasicTileLayer.'; } else if (!options.mercator) { throw 'A tile source must be specified in a BasicTileLayer.'; } this.setOptions(options); } /********************** * Overridden functions ***********************/ /** * Layer added to map. Setup rendering container. */ public onAdd(): void { //Create a div that will hold the pushpins. this._container = document.createElement('div'); this._container.style.position = 'absolute'; this._container.style.left = '0px'; this._container.style.top = '0px'; this.setHtmlElement(this._container); } /** * Layer loaded, add map events for updating position of data. */ public onLoad(): void { var map = this.getMap(); this._mapWidth = map.getWidth(); this._mapHeight = map.getHeight(); //Update the position of the pushpin when the view changes. Hide the layer if map changed to streetside. this._viewChangeEventHandler = Microsoft.Maps.Events.addHandler(map, 'viewchange', (e) => { this._viewChange(); }); this._viewChangeEndEventHandler = Microsoft.Maps.Events.addHandler(map, 'viewchangeend', (e) => { this._viewChanged(e); }); //Update the position of the overlay when the map is resized. this._mapResizeEventHandler = Microsoft.Maps.Events.addHandler(map, 'mapresize', (e) => { this._viewChanged(e); }); this.setOptions(this._tileLayerOptions); } /** * Layer removed from map. Release resources. */ public onRemove(): void { this.setHtmlElement(null); //Remove the event handler that is attached to the map. Microsoft.Maps.Events.removeHandler(this._viewChangeEventHandler); Microsoft.Maps.Events.removeHandler(this._viewChangeEndEventHandler); Microsoft.Maps.Events.removeHandler(this._mapResizeEventHandler); for (var i = 0; i < this._tiles.length; i++) { if (this._tiles[i]) { this._tiles[i] = null; this._tileIds[i] = null; } } this._tiles = null; this._tileIds = null; } /********************** * Public Functions ***********************/ /** * Retrieves the opacity of the layer. * @returns The opacity of the layer. */ public getOpacity(): number { return this._tileLayerOptions.opacity; } /** * Retrieves the tile source of the layer. * @returnsTthe tile source of the layer. */ public getTileSource(): Microsoft.Maps.TileSource { return this._tileLayerOptions.mercator; } /** * Retrieves the visibility of the layer. * @returns The visibility of the layer. */ public getVisible(): boolean { return this._tileLayerOptions.visible; } /** * Retrieves the ZIndex of the layer. * @returns The ZIndex of the layer. */ public getZIndex(): number { return this._tileLayerOptions.zIndex; } /** * Sets the opacity of the layer. * @param show The opacity of the layer. */ public setOpacity(opacity: number): void { this._tileLayerOptions.opacity = opacity; this._container.style.opacity = opacity.toString(); } /** * Sets the options of the layer. * @param opt The options of the layer. */ public setOptions(opt: Microsoft.Maps.ITileLayerOptions): void { if (opt) { if (typeof opt.opacity === 'number') { this.setOpacity(opt.opacity); } if (typeof opt.visible === 'boolean') { this.setVisible(opt.visible); } if (typeof opt.zIndex === 'number') { this.setZIndex(opt.zIndex); } if (opt.mercator) { this._tileLayerOptions.mercator = new Microsoft.Maps.TileSource({ bounds: opt.mercator.getBounds() || new Microsoft.Maps.LocationRect(new Microsoft.Maps.Location(0,0), 360, 180), maxZoom: opt.mercator.getMaxZoom() || 21, minZoom: opt.mercator.getMinZoom() || 1, uriConstructor: opt.mercator.getUriConstructor() }); this._reloadTiles(); } } } /** * Sets the visibility of the layer. * @param show The visibility of the layer. */ public setVisible(show: boolean): void { this._tileLayerOptions.visible = show; if (show) { this._container.style.display = ''; } else { this._container.style.display = 'none'; } } /** * Sets the zIndex of the layer. * @param idx The zIndex of the layer. */ public setZIndex(idx: number) { this._tileLayerOptions.zIndex = idx; this._container.style.zIndex = idx.toString(); } /********************** * Private Functions ***********************/ private _viewChange() { //Hide tile layer when moving the map for now. var zoom = this._map.getZoom(); var self = this; setTimeout(() => { if (self._currentZoom !== zoom) { var scale = Math.pow(2, zoom - self._currentZoom); self._container.style.transform = 'scale(' + scale + ')'; self._container.style.transformOrigin = (self._mapWidth / 2) + 'px ' + (self._mapHeight / 2) + 'px'; self._updatePositions(false); } else { self._container.style.transform = ''; self._updatePositions(false); } }, 0); } private _viewChanged(e) { this._mapWidth = this._map.getWidth(); this._mapHeight = this._map.getHeight(); this._container.style.transformOrigin = (this._mapWidth / 2) + 'px ' + (this._mapHeight/2) + 'px'; var mapType = this._map.getMapTypeId(); if (mapType !== Microsoft.Maps.MapTypeId.streetside && mapType !== Microsoft.Maps.MapTypeId.birdseye && this._tileLayerOptions.visible) { var self = this; setTimeout(() => { self._reloadTiles(); self._container.style.display = ''; }, 0); } } private _tiles: IBasicTile[] = []; private _tileIds: string[] = []; private _currentZoom: number; private _currentCenter: Microsoft.Maps.Location; private _mapSize: number; private _tileDownloadTimer: number; /** * Reloads all tiles on the layer. */ private _reloadTiles(): void { if (!this._container || !this._map) { return; } this._container.style.transform = ''; var center = this._map.getCenter(); var zoom = this._map.getZoom(); if (zoom >= this._tileLayerOptions.mercator.getMinZoom() && zoom <= this._tileLayerOptions.mercator.getMaxZoom()) { var dx = Math.ceil(this._mapWidth / 512) + 1; var dy = Math.ceil(this._mapHeight / 512) + 1; var cpx = Microsoft.Maps.SpatialMath.Tiles.locationToGlobalPixel(center, zoom); var topLeftGlobalPixel = new Microsoft.Maps.Point(cpx.x - this._mapWidth / 2, cpx.y - this._mapHeight / 2); this._mapSize = Microsoft.Maps.SpatialMath.Tiles.mapSize(zoom)/256-1; var centerTile = Microsoft.Maps.SpatialMath.Tiles.locationToTile(center, zoom); this._createTile(centerTile.x, centerTile.y, zoom, topLeftGlobalPixel); var minX = Math.max(0, centerTile.x - dx); var maxX = Math.min(centerTile.x + dx, this._mapSize-1); var minY = Math.max(0, centerTile.y - dy); var maxY = Math.min(centerTile.y + dy, this._mapSize - 1); //for (var x = minX; x <= maxX; x++) { // for (var y = minY; y <= maxY; y++) { // this._createTile(x, y, zoom, topLeftGlobalPixel); // } //} var midX = Math.floor((maxX + minX)/2); var midY = Math.floor((maxY + minY)/2); //Load tiles from the middle out. for (var x = 0; x <= maxX - midX; x++) { for (var y = 0; y <= maxY - midY; y++) { if (midX - x >= minX) { if (midY - y >= minY) { this._createTile(midX - x, midY - y, zoom, topLeftGlobalPixel); } if (midY + y <= maxY) { this._createTile(midX - x, midY + y, zoom, topLeftGlobalPixel); } } if (midX + x <= maxX) { if (midY - y >= minY) { this._createTile(midX + x, midY - y, zoom, topLeftGlobalPixel); } if (midY + y <= maxY) { this._createTile(midX + x, midY + y, zoom, topLeftGlobalPixel); } } // this._createTile(x, y, zoom, topLeftGlobalPixel); } } } this._updatePositions(true); if (typeof this._tileDownloadTimer === 'number') { clearTimeout(this._tileDownloadTimer); } this._tileDownloadTimer = setTimeout(() => { this._removeOldTiles() }, this._tileLayerOptions.downloadTimeout); this._currentZoom = zoom; this._currentCenter = center; } private _createTile(tileX: number, tileY: number, zoom: number, topLeftGlobalPixel: Microsoft.Maps.Point): void { var tileId = tileX + '_' + tileY + '_' + zoom; var tileIdx = this._tileIds.indexOf(tileId); var tile = null; if (tileIdx > -1) { tile = this._tiles[tileIdx]; } if (!tile) { var self = this; var tileInfo = new Microsoft.Maps.PyramidTileId(tileX, tileY, zoom); var bounds = Microsoft.Maps.SpatialMath.Tiles.tileToLocationRect(tileInfo); if (this._tileLayerOptions.mercator.getBounds().intersects(bounds)) { tileIdx = self._tileIds.length; self._tileIds.push(tileId); self._tiles[tileIdx] = { id: tileId, tileInfo: tileInfo, img: null }; var tileUrl = ''; var urlCon = this._tileLayerOptions.mercator.getUriConstructor(); if (typeof urlCon === "function") { tileUrl = urlCon(tileInfo); } else { tileUrl = urlCon.replace(/{quadkey}/gi, tileInfo.quadKey).replace(/{x}/gi, tileInfo.x.toString()).replace(/{y}/gi, tileInfo.y.toString()).replace(/{zoom}/gi, tileInfo.zoom.toString()) .replace(/{bbox}/gi, bounds.getWest() + ',' + bounds.getSouth() + ',' + bounds.getEast() + ',' + bounds.getNorth()); } var img = new Image(256, 256); img.style.position = 'absolute'; img.style.pointerEvents = 'none'; img.onload = (image) => { if (self._tiles[tileIdx]) { //Set position. img.style.top = (self._tiles[tileIdx].tileInfo.y * 256 - topLeftGlobalPixel.y) + 'px'; img.style.left = (self._tiles[tileIdx].tileInfo.x * 256 - topLeftGlobalPixel.x) + 'px'; self._container.appendChild(img); self._tiles[tileIdx].img = img; } }; img.onerror = () => { self._tiles[tileIdx] = null; }; if (tileUrl !== '') { img.src = tileUrl; } } } else if (tile.img) { //Tile already exists, update its position. tile.img.style.top = (tileY * 256 - topLeftGlobalPixel.y) + 'px'; tile.img.style.left = (tileX * 256 - topLeftGlobalPixel.x) + 'px'; } } /** * Updates the positions of all tiles in the layer. */ private _updatePositions(removeTiles: boolean): void { var center = this._map.getCenter(); var zoom = this._map.getZoom(); var cpx = Microsoft.Maps.SpatialMath.Tiles.locationToGlobalPixel(center, zoom); var topLeftGlobalPixel = new Microsoft.Maps.Point(cpx.x - this._mapWidth / 2, cpx.y - this._mapHeight / 2); for (var i = 0; i < this._tiles.length; i++) { if (this._tiles[i]) { if (removeTiles && this._tiles[i].tileInfo.zoom !== zoom) { if (this._tiles[i].img) { this._container.removeChild(this._tiles[i].img); } this._tiles[i] = null; this._tileIds[i] = null; } else if (this._tiles[i].img) { this._tiles[i].img.style.top = (this._tiles[i].tileInfo.y * 256 - topLeftGlobalPixel.y) + 'px'; this._tiles[i].img.style.left = (this._tiles[i].tileInfo.x * 256 - topLeftGlobalPixel.x) + 'px'; } } } } private _removeOldTiles(): void { var currentTiles = []; var currentTileIdx = []; for (var i = 0; i< this._tiles.length; i++) { if (this._tiles[i]) { currentTiles.push(this._tiles[i]); currentTileIdx.push(this._tiles[i].id); } } this._tiles = currentTiles; this._tileIds = currentTileIdx; } } //Load dependancy module. Microsoft.Maps.loadModule('Microsoft.Maps.SpatialMath', () => { //Call the module loaded function. Microsoft.Maps.moduleLoaded('BasicTileLayerModule'); });
the_stack
import { Cancelable, CancelableSource, CancelSignal } from "@esfx/cancelable"; import { Disposable } from "@esfx/disposable"; import { LinkedList } from "./list"; import { isMissing, isBoolean, isFunction, isIterable, isInstance } from "./utils"; type CancellationState = "open" | "cancellationRequested" | "closed"; /** * Signals a CancellationToken that it should be canceled. */ export class CancellationTokenSource implements CancelableSource { private _state: CancellationState = "open"; private _token: CancellationToken | undefined = undefined; private _registrations: LinkedList<CancellationTokenRegistration> | undefined = undefined; private _linkingRegistrations: CancellationTokenRegistration[] | undefined = undefined; /** * Initializes a new instance of a CancellationTokenSource. * * @param linkedTokens An optional iterable of tokens to which to link this source. */ constructor(linkedTokens?: Iterable<CancellationToken | Cancelable>) { if (!isIterable(linkedTokens, /*optional*/ true)) throw new TypeError("Object not iterable: linkedTokens."); if (linkedTokens) { for (const linkedToken of linkedTokens) { if (!Cancelable.hasInstance(linkedToken)) { throw new TypeError("CancellationToken expected."); } const token = CancellationToken.from(linkedToken); if (token.cancellationRequested) { this._state = "cancellationRequested"; this._unlink(); break; } else if (token.canBeCanceled) { if (this._linkingRegistrations === undefined) { this._linkingRegistrations = []; } this._linkingRegistrations.push(token.register(() => this.cancel())) } } } } /** * Gets a CancellationToken linked to this source. */ public get token(): CancellationToken { if (this._token === undefined) { this._token = new CancellationToken(this); } return this._token; } /*@internal*/ get _currentState(): CancellationState { if (this._state === "open" && this._linkingRegistrations && this._linkingRegistrations.length > 0) { for (const registration of this._linkingRegistrations) { if (registration._cancellationSource && registration._cancellationSource._currentState === "cancellationRequested") { return "cancellationRequested"; } } } return this._state; } /** * Gets a value indicating whether cancellation has been requested. */ /*@internal*/ get _cancellationRequested(): boolean { return this._currentState === "cancellationRequested"; } /** * Gets a value indicating whether the source can be canceled. */ /*@internal*/ get _canBeCanceled(): boolean { return this._currentState !== "closed"; } /** * Cancels the source, evaluating any registered callbacks. If any callback raises an exception, * the exception is propagated to a host specific unhanedle exception mechanism. */ public cancel(): void { if (this._state !== "open") { return; } this._state = "cancellationRequested"; this._unlink(); const registrations = this._registrations; this._registrations = undefined; if (registrations && registrations.size > 0) { for (const registration of registrations) { if (registration._cancellationTarget) { this._executeCallback(registration._cancellationTarget); } } } } /** * Closes the source, preventing the possibility of future cancellation. */ public close(): void { if (this._state !== "open") { return; } this._state = "closed"; this._unlink(); const callbacks = this._registrations; this._registrations = undefined; if (callbacks !== undefined) { // The registration for each callback holds onto the node, the node holds onto the // list, and the list holds all other nodes and callbacks. By clearing the list, the // GC can collect any otherwise unreachable nodes. callbacks.clear(); } } /** * Registers a callback to execute when cancellation has been requested. If cancellation has * already been requested, the callback is executed immediately. * * @param callback The callback to register. */ /*@internal*/ _register(callback: () => void): CancellationTokenRegistration { if (!isFunction(callback)) throw new TypeError("Function expected: callback."); if (this._state === "cancellationRequested") { this._executeCallback(callback); return emptyRegistration; } if (this._state === "closed") { return emptyRegistration; } if (this._registrations === undefined) { this._registrations = new LinkedList<CancellationTokenRegistration>(); } function unregister(this: CancellationTokenRegistration): void { if (this._cancellationSource === undefined) return; if (this._cancellationSource._registrations) { this._cancellationSource._registrations.deleteNode(node); } this._cancellationSource = undefined; this._cancellationTarget = undefined; } const node = this._registrations.push({ _cancellationSource: this, _cancellationTarget: callback, unregister, [Disposable.dispose]: unregister, }); return node.value!; } /** * Executes the provided callback. * * @param callback The callback to execute. */ private _executeCallback(callback: () => void): void { try { callback(); } catch (e) { // HostReportError(e) setTimeout(() => { throw e; }, 0); } } /** * Unlinks the source from any linked tokens. */ private _unlink(): void { const linkingRegistrations = this._linkingRegistrations; this._linkingRegistrations = undefined; if (linkingRegistrations !== undefined) { for (const linkingRegistration of linkingRegistrations) { linkingRegistration.unregister(); } } } // #region Cancelable [Cancelable.cancelSignal]() { return this.token[Cancelable.cancelSignal](); } // #endregion Cancelable // #region CancelableSource [CancelableSource.cancel]() { this.cancel(); } // #endregion CancelableSource } // A source that cannot be canceled. const closedSource = new CancellationTokenSource(); closedSource.close(); // A source that is already canceled. const canceledSource = new CancellationTokenSource(); canceledSource.cancel(); const weakCancelableToToken = typeof WeakMap === "function" ? new WeakMap<Cancelable, CancellationToken>() : undefined; const weakTokenToCancelable = typeof WeakMap === "function" ? new WeakMap<CancellationToken, Cancelable & CancelSignal>() : undefined; /** * Propagates notifications that operations should be canceled. */ export class CancellationToken implements Cancelable { /** * A token which will never be canceled. */ public static readonly none = new CancellationToken(/*canceled*/ false); /** * A token that is already canceled. */ public static readonly canceled = new CancellationToken(/*canceled*/ true); private _source: CancellationTokenSource; /*@internal*/ constructor(canceled?: boolean); /*@internal*/ constructor(source: CancellationTokenSource); constructor(source?: CancellationTokenSource | boolean) { if (isMissing(source)) { this._source = closedSource; } else if (isBoolean(source)) { this._source = source ? canceledSource : closedSource; } else { if (!isInstance(source, CancellationTokenSource)) throw new TypeError("CancellationTokenSource expected: source."); this._source = source; } Object.freeze(this); } /** * Gets a value indicating whether cancellation has been requested. */ public get cancellationRequested(): boolean { return this._source._cancellationRequested; } /** * Gets a value indicating whether the underlying source can be canceled. */ public get canBeCanceled(): boolean { return this._source._canBeCanceled; } /** * Adapts a CancellationToken-like primitive from a different library. */ public static from(cancelable: CancellationToken | VSCodeCancellationTokenLike | AbortSignalLike | Cancelable) { if (cancelable instanceof CancellationToken) { return cancelable; } if (Cancelable.hasInstance(cancelable)) { const signal = cancelable[Cancelable.cancelSignal](); if (signal.signaled) return CancellationToken.canceled; let token = weakCancelableToToken && weakCancelableToToken.get(cancelable); if (!token) { const source = new CancellationTokenSource(); signal.subscribe(() => source.cancel()); token = source.token; if (weakCancelableToToken) weakCancelableToToken.set(cancelable, token); } return token; } if (isVSCodeCancellationTokenLike(cancelable)) { if (cancelable.isCancellationRequested) return CancellationToken.canceled; const source = new CancellationTokenSource(); cancelable.onCancellationRequested(() => source.cancel()); return source.token; } if (isAbortSignalLike(cancelable)) { if (cancelable.aborted) return CancellationToken.canceled; const source = new CancellationTokenSource(); cancelable.addEventListener("abort", () => source.cancel()); return source.token; } throw new TypeError("Invalid token."); } /** * Returns a CancellationToken that becomes canceled when **any** of the provided tokens are canceled. * @param tokens An iterable of CancellationToken objects. */ public static race(tokens: Iterable<CancellationToken | Cancelable>) { if (!isIterable(tokens)) throw new TypeError("Object not iterable: iterable."); const tokensArray = Array.isArray(tokens) ? tokens : [...tokens]; return tokensArray.length > 0 ? new CancellationTokenSource(tokensArray).token : CancellationToken.none; } /** * Returns a CancellationToken that becomes canceled when **all** of the provided tokens are canceled. * @param tokens An iterable of CancellationToken objects. */ public static all(tokens: Iterable<CancellationToken | Cancelable>) { if (!isIterable(tokens)) throw new TypeError("Object not iterable: iterable."); const tokensArray = Array.isArray(tokens) ? tokens : [...tokens]; return tokensArray.length > 0 ? new CancellationTokenCountdown(tokensArray).token : CancellationToken.none; } /** * Throws a CancelError if cancellation has been requested. */ public throwIfCancellationRequested(): void { if (this.cancellationRequested) { throw new CancelError(); } } /** * Registers a callback to execute when cancellation is requested. * * @param callback The callback to register. */ public register(callback: () => void): CancellationTokenRegistration { return this._source._register(callback); } // #region Cancelable [Cancelable.cancelSignal]() { let signal = weakTokenToCancelable?.get(this); if (!signal) { const token = this; signal = { get signaled() { return token.cancellationRequested; }, subscribe(onCancellationRequested) { const registration = token.register(onCancellationRequested); return { unsubscribe() { registration.unregister(); }, [Disposable.dispose]() { this.unsubscribe(); } }; }, [Cancelable.cancelSignal]() { return this; } }; weakTokenToCancelable?.set(this, signal); } return signal; } // #endregion Cancelable } /** * An error thrown when an operation is canceled. */ export class CancelError extends Error { constructor(message?: string) { super(message || "Operation was canceled"); } } CancelError.prototype.name = "CancelError"; /** * An object used to unregister a callback registered to a CancellationToken. */ export interface CancellationTokenRegistration extends Disposable { /*@internal*/ _cancellationSource: CancellationTokenSource | undefined; /*@internal*/ _cancellationTarget: (() => void) | undefined; /** * Unregisters the callback */ unregister(): void; } const emptyRegistration: CancellationTokenRegistration = Object.create({ unregister() { } }); /** * Describes a foreign cancellation primitive similar to the one provided by `vscode` for extensions. */ export interface VSCodeCancellationTokenLike { readonly isCancellationRequested: boolean; onCancellationRequested(listener: () => any): { dispose(): any; }; } /** * Describes a foreign cancellation primitive similar to the one used by the DOM. */ export interface AbortSignalLike { readonly aborted: boolean; addEventListener(type: "abort", callback: () => any): any; } function isVSCodeCancellationTokenLike(token: any): token is VSCodeCancellationTokenLike { return typeof token === "object" && token !== null && isBoolean(token.isCancellationRequested) && isFunction(token.onCancellationRequested); } function isAbortSignalLike(token: any): token is AbortSignalLike { return typeof token === "object" && token !== null && isBoolean(token.aborted) && isFunction(token.addEventListener); } /** * An object that provides a CancellationToken that becomes cancelled when **all** of its * containing tokens are canceled. This is similar to `CancellationToken.all`, except that you are * able to add additional tokens. */ export class CancellationTokenCountdown { private _addedCount = 0; private _signaledCount = 0; private _canBeSignaled = false; private _source = new CancellationTokenSource(); private _registrations: CancellationTokenRegistration[] = []; constructor(iterable?: Iterable<CancellationToken | Cancelable>) { if (!isIterable(iterable, /*optional*/ true)) throw new TypeError("Object not iterable: iterable."); if (iterable) { for (const token of iterable) { this.add(token); } } this._canBeSignaled = true; this._checkSignalState(); } /** * Gets the number of tokens added to the countdown. */ public get addedCount() { return this._addedCount; } /** * Gets the number of tokens that have not yet been canceled. */ public get remainingCount() { return this._addedCount - this._signaledCount; } /** * Gets the CancellationToken for the countdown. */ public get token() { return this._source.token; } /** * Adds a CancellationToken to the countdown. */ add(token: CancellationToken | Cancelable) { if (!Cancelable.hasInstance(token)) throw new TypeError("CancellationToken or Cancelable expected."); const ct = CancellationToken.from(token); if (this._source._currentState !== "open") return this; if (ct.cancellationRequested) { this._addedCount++; this._signaledCount++; this._checkSignalState(); } else if (ct.canBeCanceled) { this._addedCount++; this._registrations.push(ct.register(() => { this._signaledCount++; this._checkSignalState(); })); } return this; } private _checkSignalState() { if (!this._canBeSignaled || this._signaledCount < this._addedCount) return; this._canBeSignaled = false; if (this._addedCount > 0) { try { for (const registration of this._registrations) { registration.unregister(); } } finally { this._registrations.length = 0; this._source.cancel(); } } } }
the_stack
import { ErrorHandler, Injectable } from '@angular/core'; import { fakeAsync, TestBed, tick } from '@angular/core/testing'; import { Observable, of, Subject, throwError } from 'rxjs'; import { delay, map, tap } from 'rxjs/operators'; import { Actions } from '../src/actions-stream'; import { Action } from '../src/decorators/action'; import { State } from '../src/decorators/state'; import { NgxsModule } from '../src/module'; import { ofAction, ofActionCanceled, ofActionCompleted, ofActionDispatched, ofActionErrored, ofActionSuccessful } from '../src/operators/of-action'; import { Store } from '../src/store'; import { META_KEY, StateContext } from '../src/symbols'; import { NoopErrorHandler } from './helpers/utils'; describe('Action', () => { class Action1 { static type = 'ACTION 1'; } class Action2 { static type = 'ACTION 2'; } class ErrorAction { static type = 'ErrorAction'; } class CancelingAction { static type = 'CancelingAction'; constructor(public readonly id: number) {} } @State({ name: 'bar' }) @Injectable() class BarStore { @Action([Action1, Action2]) foo() {} @Action(ErrorAction) onError() { return throwError(new Error('this is a test error')); } @Action({ type: 'OBJECT_LITERAL' }) onObjectLiteral() { return of({}); } @Action(CancelingAction, { cancelUncompleted: true }) barGetsCanceled() { return of({}).pipe(delay(0)); } } describe('', () => { function setup() { TestBed.configureTestingModule({ imports: [NgxsModule.forRoot([BarStore])], providers: [{ provide: ErrorHandler, useClass: NoopErrorHandler }] }); const store = TestBed.inject(Store); const actions = TestBed.inject(Actions); return { store, actions }; } it('supports multiple actions', () => { // Arrange setup(); // Act const meta = (<any>BarStore)[META_KEY]; // Assert expect(meta.actions[Action1.type]).toBeDefined(); expect(meta.actions[Action2.type]).toBeDefined(); }); it('calls actions on dispatch and on complete', fakeAsync(() => { // Arrange const { store, actions } = setup(); const callbacksCalled: string[] = []; actions.pipe(ofAction(Action1)).subscribe(() => { callbacksCalled.push('ofAction'); }); actions.pipe(ofActionDispatched(Action1)).subscribe(() => { callbacksCalled.push('ofActionDispatched'); }); actions.pipe(ofActionSuccessful(Action1)).subscribe(() => { callbacksCalled.push('ofActionSuccessful'); expect(callbacksCalled).toEqual([ 'ofAction', 'ofActionDispatched', 'ofAction', 'ofActionSuccessful' ]); }); actions.pipe(ofActionCompleted(Action1)).subscribe(({ result }) => { callbacksCalled.push('ofActionCompleted'); expect(result).toEqual({ canceled: false, error: undefined, successful: true }); }); // Act store.dispatch(new Action1()).subscribe(() => { expect(callbacksCalled).toEqual([ 'ofAction', 'ofActionDispatched', 'ofAction', 'ofActionSuccessful', 'ofActionCompleted' ]); }); tick(1); expect(callbacksCalled).toEqual([ 'ofAction', 'ofActionDispatched', 'ofAction', 'ofActionSuccessful', 'ofActionCompleted' ]); })); it('calls only the dispatched and error action', fakeAsync(() => { // Arrange const { store, actions } = setup(); const callbacksCalled: string[] = []; actions.pipe(ofAction(Action1)).subscribe(() => { callbacksCalled.push('ofAction[Action1]'); }); actions.pipe(ofAction(ErrorAction)).subscribe(() => { callbacksCalled.push('ofAction'); }); actions.pipe(ofActionDispatched(ErrorAction)).subscribe(() => { callbacksCalled.push('ofActionDispatched'); }); actions.pipe(ofActionSuccessful(ErrorAction)).subscribe(() => { callbacksCalled.push('ofActionSuccessful'); }); actions.pipe(ofActionErrored(ErrorAction)).subscribe(() => { callbacksCalled.push('ofActionErrored'); expect(callbacksCalled).toEqual([ 'ofAction', 'ofActionDispatched', 'ofAction', 'ofActionErrored' ]); }); actions.pipe(ofActionCompleted(ErrorAction)).subscribe(({ result }) => { callbacksCalled.push('ofActionCompleted'); expect(result).toEqual({ canceled: false, error: Error('this is a test error'), successful: false }); }); // Act store.dispatch(new ErrorAction()).subscribe({ error: () => expect(callbacksCalled).toEqual([ 'ofAction', 'ofActionDispatched', 'ofAction', 'ofActionErrored', 'ofActionCompleted' ]) }); tick(1); expect(callbacksCalled).toEqual([ 'ofAction', 'ofActionDispatched', 'ofAction', 'ofActionErrored', 'ofActionCompleted' ]); })); it('calls only the dispatched and canceled action', fakeAsync(() => { // Arrange const { store, actions } = setup(); const callbacksCalled: string[] = []; actions.pipe(ofAction(CancelingAction)).subscribe(({ id }: CancelingAction) => { callbacksCalled.push('ofAction ' + id); }); actions .pipe(ofActionDispatched(CancelingAction)) .subscribe(({ id }: CancelingAction) => { callbacksCalled.push('ofActionDispatched ' + id); }); actions.pipe(ofActionErrored(CancelingAction)).subscribe(({ id }: CancelingAction) => { callbacksCalled.push('ofActionErrored ' + id); }); actions .pipe(ofActionSuccessful(CancelingAction)) .subscribe(({ id }: CancelingAction) => { callbacksCalled.push('ofActionSuccessful ' + id); expect(callbacksCalled).toEqual([ 'ofAction 1', 'ofActionDispatched 1', 'ofAction 2', 'ofActionDispatched 2', 'ofAction 1', 'ofActionCanceled 1', 'ofAction 2', 'ofActionSuccessful 2' ]); }); actions.pipe(ofActionCanceled(CancelingAction)).subscribe(({ id }: CancelingAction) => { callbacksCalled.push('ofActionCanceled ' + id); expect(callbacksCalled).toEqual([ 'ofAction 1', 'ofActionDispatched 1', 'ofAction 2', 'ofActionDispatched 2', 'ofAction 1', 'ofActionCanceled 1' ]); }); // Act store.dispatch([new CancelingAction(1), new CancelingAction(2)]).subscribe({ complete: () => { expect(callbacksCalled).toEqual([ 'ofAction 1', 'ofActionDispatched 1', 'ofAction 2', 'ofActionDispatched 2', 'ofAction 1', 'ofActionCanceled 1' ]); } }); tick(1); // Assert expect(callbacksCalled).toEqual([ 'ofAction 1', 'ofActionDispatched 1', 'ofAction 2', 'ofActionDispatched 2', 'ofAction 1', 'ofActionCanceled 1', 'ofAction 2', 'ofActionSuccessful 2' ]); })); it('should allow the user to dispatch an object literal', () => { // Arrange const { store, actions } = setup(); const callbacksCalled: string[] = []; actions.pipe(ofActionCompleted({ type: 'OBJECT_LITERAL' })).subscribe(() => { callbacksCalled.push('onObjectLiteral'); }); // Act store.dispatch({ type: 'OBJECT_LITERAL' }); // Assert expect(callbacksCalled).toEqual(['onObjectLiteral']); }); }); describe('Async Action Scenario', () => { class PromiseThatReturnsObs { static type = 'PromiseThatReturnsObs'; } class PromiseThatReturnsPromise { static type = 'PromiseThatReturnsPromise'; } class ObservableAction { static type = 'ObservableAction'; } class ObsThatReturnsPromise { static type = 'ObsThatReturnsPromise'; } class ObsThatReturnsObservable { static type = 'ObsThatReturnsObservable'; } class PromiseAction { static type = 'PromiseAction'; } function setup() { const recorder: string[] = []; const record = (message: string) => recorder.push(message); const observable = new Subject(); const completeObservableFn = () => { record('(completeObservableFn) - next'); observable?.next(); record('(completeObservableFn) - complete'); observable?.complete(); record('(completeObservableFn) - end'); }; let resolveFn: (value: unknown) => void; const promise = new Promise(resolve => { resolveFn = resolve; }).then(() => record('promise resolved')); const promiseResolveFn = () => { record('(promiseResolveFn) called'); resolveFn?.(null); }; @State({ name: 'async_state' }) @Injectable() class AsyncState { @Action(PromiseThatReturnsObs) async promiseThatReturnsObs(ctx: StateContext<any>) { record('promiseThatReturnsObs - start'); await promise; record('promiseThatReturnsObs - after promise'); return ctx .dispatch(ObservableAction) .pipe(tap(() => record('promiseThatReturnsObs - observable tap'))); } @Action(PromiseThatReturnsPromise) async promiseThatReturnsPromise(ctx: StateContext<any>) { record('promiseThatReturnsPromise - start'); await promise; record('promiseThatReturnsPromise - after promise'); return ctx .dispatch(ObservableAction) .toPromise() .then(() => record('promiseThatReturnsPromise - promise resolving')); } @Action(ObsThatReturnsPromise) obsThatReturnsPromise() { record('obsThatReturnsPromise - start'); return observable.pipe( tap(() => record('obsThatReturnsPromise - observable tap')), map(async () => { return await promise; }) ); } @Action(ObsThatReturnsObservable) obsThatReturnsObservable(ctx: StateContext<any>) { record('obsThatReturnsObservable - start'); return observable.pipe( tap(() => record('obsThatReturnsObservable - observable tap')), map(() => { return ctx .dispatch(new PromiseAction()) .pipe(tap(() => record('obsThatReturnsObservable - inner observable tap'))); }) ); } @Action(ObservableAction) observableAction() { record('observableAction - start'); return observable.pipe(tap(() => record('observableAction - observable tap'))); } @Action(PromiseAction) promiseAction() { record('promiseAction - start'); return promise.then(() => record('promiseAction - after promise')); } } TestBed.configureTestingModule({ imports: [NgxsModule.forRoot([AsyncState])], providers: [{ provide: ErrorHandler, useClass: NoopErrorHandler }] }); const store = TestBed.inject(Store); const actions = TestBed.inject(Actions); return { store, actions, completeObservableFn, promiseResolveFn, promise, recorder, record }; } describe('Promise that returns an observable', () => { it('completes when observable is resolved', fakeAsync(() => { // Arrange const { store, actions, promiseResolveFn, completeObservableFn, recorder, record } = setup(); actions.pipe(ofActionCompleted(ObservableAction)).subscribe(() => { record('ObservableAction [Completed]'); }); actions.pipe(ofActionCompleted(PromiseThatReturnsObs)).subscribe(() => { record('PromiseThatReturnsObs [Completed]'); }); // Act store .dispatch(new PromiseThatReturnsObs()) .subscribe(() => record('dispatch(PromiseThatReturnsObs) - Completed')); promiseResolveFn(); tick(); // Assert expect(recorder).toEqual([ 'promiseThatReturnsObs - start', '(promiseResolveFn) called', 'promise resolved', 'promiseThatReturnsObs - after promise', 'observableAction - start' ]); completeObservableFn(); tick(); expect(recorder).toEqual([ 'promiseThatReturnsObs - start', '(promiseResolveFn) called', 'promise resolved', 'promiseThatReturnsObs - after promise', 'observableAction - start', '(completeObservableFn) - next', 'observableAction - observable tap', '(completeObservableFn) - complete', 'ObservableAction [Completed]', 'promiseThatReturnsObs - observable tap', 'PromiseThatReturnsObs [Completed]', 'dispatch(PromiseThatReturnsObs) - Completed', '(completeObservableFn) - end' ]); })); }); describe('Promise that returns a promise', () => { it('completes when inner promise is resolved', fakeAsync(() => { // Arrange const { store, actions, promiseResolveFn, completeObservableFn, recorder, record } = setup(); actions.pipe(ofActionCompleted(ObservableAction)).subscribe(() => { record('ObservableAction [Completed]'); }); actions.pipe(ofActionCompleted(PromiseThatReturnsPromise)).subscribe(() => { record('PromiseThatReturnsPromise [Completed]'); }); // Act store .dispatch(new PromiseThatReturnsPromise()) .subscribe(() => record('dispatch(PromiseThatReturnsPromise) - Completed')); promiseResolveFn(); tick(); // Assert expect(recorder).toEqual([ 'promiseThatReturnsPromise - start', '(promiseResolveFn) called', 'promise resolved', 'promiseThatReturnsPromise - after promise', 'observableAction - start' ]); completeObservableFn(); tick(); expect(recorder).toEqual([ 'promiseThatReturnsPromise - start', '(promiseResolveFn) called', 'promise resolved', 'promiseThatReturnsPromise - after promise', 'observableAction - start', '(completeObservableFn) - next', 'observableAction - observable tap', '(completeObservableFn) - complete', 'ObservableAction [Completed]', '(completeObservableFn) - end', 'promiseThatReturnsPromise - promise resolving', 'PromiseThatReturnsPromise [Completed]', 'dispatch(PromiseThatReturnsPromise) - Completed' ]); })); }); describe('Observable that returns a promise', () => { it('completes when promise is completed', fakeAsync(() => { // Arrange const { store, actions, promiseResolveFn, completeObservableFn, promise, recorder, record } = setup(); promise.then(() => { record('promise [resolved]'); }); actions.pipe(ofActionCompleted(ObsThatReturnsPromise)).subscribe(() => { record('ObsThatReturnsPromise [Completed]'); }); // Act store .dispatch(new ObsThatReturnsPromise()) .subscribe(() => record('dispatch(ObsThatReturnsPromise) - Completed')); completeObservableFn(); // Assert expect(recorder).toEqual([ 'obsThatReturnsPromise - start', '(completeObservableFn) - next', 'obsThatReturnsPromise - observable tap', '(completeObservableFn) - complete', '(completeObservableFn) - end' ]); promiseResolveFn(); tick(); expect(recorder).toEqual([ 'obsThatReturnsPromise - start', '(completeObservableFn) - next', 'obsThatReturnsPromise - observable tap', '(completeObservableFn) - complete', '(completeObservableFn) - end', '(promiseResolveFn) called', 'promise resolved', 'promise [resolved]', 'ObsThatReturnsPromise [Completed]', 'dispatch(ObsThatReturnsPromise) - Completed' ]); })); }); describe('Observable that returns an inner observable', () => { it('completes when inner observable is completed', fakeAsync(() => { // Arrange const { store, actions, promiseResolveFn, completeObservableFn, promise, recorder, record } = setup(); promise.then(() => { record('promise [resolved]'); }); actions.pipe(ofActionCompleted(ObsThatReturnsObservable)).subscribe(() => { record('ObsThatReturnsObservable [Completed]'); }); // Act store .dispatch(new ObsThatReturnsObservable()) .subscribe(() => record('dispatch(ObsThatReturnsObservable) - Completed')); completeObservableFn(); // Assert expect(recorder).toEqual([ 'obsThatReturnsObservable - start', '(completeObservableFn) - next', 'obsThatReturnsObservable - observable tap', 'promiseAction - start', '(completeObservableFn) - complete', '(completeObservableFn) - end' ]); promiseResolveFn(); tick(); expect(recorder).toEqual([ 'obsThatReturnsObservable - start', '(completeObservableFn) - next', 'obsThatReturnsObservable - observable tap', 'promiseAction - start', '(completeObservableFn) - complete', '(completeObservableFn) - end', '(promiseResolveFn) called', 'promise resolved', 'promise [resolved]', 'promiseAction - after promise', 'obsThatReturnsObservable - inner observable tap', 'ObsThatReturnsObservable [Completed]', 'dispatch(ObsThatReturnsObservable) - Completed' ]); })); }); }); describe('Cancellable Action Scenario', () => { class CancellableAction { static type = 'Cancellable'; constructor( public readonly id: number, public readonly observable: Observable<string> ) {} } function setup() { const recorder: string[] = []; const record = (message: string) => recorder.push(message); @State({ name: 'cancellable_action_state' }) @Injectable() class AsyncState { @Action(CancellableAction, { cancelUncompleted: true }) cancellableAction(_: StateContext<any>, action: CancellableAction) { record(`cancellableAction(${action.id}) - start`); return action.observable.pipe( tap(() => record(`cancellableAction(${action.id}) - observable tap`)) ); } } TestBed.configureTestingModule({ imports: [NgxsModule.forRoot([AsyncState])], providers: [{ provide: ErrorHandler, useClass: NoopErrorHandler }] }); const store = TestBed.inject(Store); const actions = TestBed.inject(Actions); return { store, actions, recorder, record }; } function recordStream<TValue>(record: (phase: string, value?: TValue) => void) { return function(source: Observable<TValue>): Observable<TValue> { return new Observable(subscriber => { record('subscribe'); const subscription = source.subscribe({ next(value) { record('next', value); subscriber.next(value); }, error(error) { record('next', error); subscriber.error(error); }, complete() { record('complete'); subscriber.complete(); } }); return () => { record('unsubscribe'); subscription.unsubscribe(); }; }); }; } function recordedObservable( observable1: Subject<string>, prefix: string, record: (message: string) => number ): Observable<string> { return observable1.pipe( recordStream((phase, value) => record(prefix + ' - ' + phase + (value ? ' ' + value : '')) ) ); } describe('Sequential dispatch', () => { it('unsubscribes to first action observable before starting second action', fakeAsync(() => { // Arrange const { store, recorder, record } = setup(); const observable1 = new Subject<string>(); const action1 = new CancellableAction( 1, recordedObservable(observable1, 'action1 obs', record) ); const observable2 = new Subject<string>(); const action2 = new CancellableAction( 2, recordedObservable(observable2, 'action2 obs', record) ); record('Action 1 - dispatching'); store.dispatch(action1).subscribe(() => record('Action 1 - dispatch complete')); // Act record('Action 2 - dispatching'); store.dispatch(action2).subscribe(() => record('Action 2 - dispatch complete')); // Assert expect(recorder).toEqual([ 'Action 1 - dispatching', 'cancellableAction(1) - start', 'action1 obs - subscribe', 'Action 2 - dispatching', 'action1 obs - unsubscribe', 'cancellableAction(2) - start', 'action2 obs - subscribe' ]); })); it('sequencing of completions should come back inline with zones strategy', fakeAsync(() => { // Arrange const { store, recorder, record } = setup(); const observable1 = new Subject<string>(); const action1 = new CancellableAction( 1, recordedObservable(observable1, 'action1 obs', record) ); const observable2 = new Subject<string>(); const action2 = new CancellableAction( 2, recordedObservable(observable2, 'action2 obs', record) ); // Act record('Action 1 - dispatching'); store.dispatch(action1).subscribe({ next: () => record('Action 1 - dispatch next'), complete: () => record('Action 1 - dispatch complete') }); record('Action 2 - dispatching'); store.dispatch(action2).subscribe({ next: () => record('Action 2 - dispatch next'), complete: () => record('Action 2 - dispatch complete') }); observable1.next('Value1'); observable2.next('Value2'); record('complete 2'); observable2.complete(); record('complete 1'); observable1.complete(); // Assert expect(recorder).toEqual([ 'Action 1 - dispatching', 'cancellableAction(1) - start', 'action1 obs - subscribe', 'Action 2 - dispatching', 'Action 1 - dispatch complete', 'action1 obs - unsubscribe', 'cancellableAction(2) - start', 'action2 obs - subscribe', 'action2 obs - next Value2', 'cancellableAction(2) - observable tap', 'complete 2', 'action2 obs - complete', 'Action 2 - dispatch next', 'Action 2 - dispatch complete', 'action2 obs - unsubscribe', 'complete 1' ]); })); }); describe('Dual dispatch', () => { it('dual dispatch should unsubscribe first action and keep second action', fakeAsync(() => { // Arrange const { store, recorder, record } = setup(); const observable1 = new Subject<string>(); const action1 = new CancellableAction( 1, recordedObservable(observable1, 'action1 obs', record) ); const observable2 = new Subject<string>(); const action2 = new CancellableAction( 2, recordedObservable(observable2, 'action2 obs', record) ); // Act record('Action 1 & 2 - dispatching'); store .dispatch([action1, action2]) .subscribe(() => record('Action 1 & 2 - dispatch complete')); // Assert expect(recorder).toEqual([ 'Action 1 & 2 - dispatching', 'cancellableAction(1) - start', 'action1 obs - subscribe', 'action1 obs - unsubscribe', 'cancellableAction(2) - start', 'action2 obs - subscribe' ]); })); it('dual dispatch should complete when first action is cancelled - unclear requirement!! Bug maybe', fakeAsync(() => { // Arrange const { store, recorder, record } = setup(); const observable1 = new Subject<string>(); const action1 = new CancellableAction( 1, recordedObservable(observable1, 'action1 obs', record) ); const observable2 = new Subject<string>(); const action2 = new CancellableAction( 2, recordedObservable(observable2, 'action2 obs', record) ); record('Action 1 & 2 - dispatching'); store.dispatch([action1, action2]).subscribe({ next: () => record('Action 1 & 2 - dispatch next'), complete: () => record('Action 1 & 2 - dispatch complete') }); // Act observable1.next('Value1'); observable2.next('Value2'); record('complete 2'); observable2.complete(); record('complete 1'); observable1.complete(); // Assert expect(recorder).toEqual([ 'Action 1 & 2 - dispatching', 'cancellableAction(1) - start', 'action1 obs - subscribe', 'action1 obs - unsubscribe', 'cancellableAction(2) - start', 'action2 obs - subscribe', 'Action 1 & 2 - dispatch complete', 'action2 obs - next Value2', 'cancellableAction(2) - observable tap', 'complete 2', 'action2 obs - complete', 'action2 obs - unsubscribe', 'complete 1' ]); })); }); }); });
the_stack
import { Answerable, AnswersQuestions, Expectation, List, LogicError, MetaQuestion, Question, UsesAbilities } from '@serenity-js/core'; import { formatted } from '@serenity-js/core/lib/io'; import type { Element, ElementArray } from 'webdriverio'; import { ElementArrayListAdapter } from './lists'; import { Locator } from './locators'; import { NestedTargetBuilder } from './NestedTargetBuilder'; import { TargetBuilder } from './TargetBuilder'; /** * @desc * A type alias representing a {@link @serenity-js/core/lib/screenplay/questions~List} of WebdriverIO Web elements. * * @public * * @see {@link @serenity-js/core/lib/screenplay/questions~List} * * @typedef {List<ElementArrayListAdapter, Promise<Element<'async'>>, Promise<ElementArray>>} TargetList */ export type TargetList = List<ElementArrayListAdapter, Promise<Element<'async'>>, Promise<ElementArray>>; /** * @desc * Provides a convenient way to retrieve a single web element or multiple web elements, * so that they can be used with Serenity/JS {@link @serenity-js/core/lib/screenplay~Interaction}s. * * Check out the examples below, as well as the unit tests demonstrating the usage. * * @example <caption>Imaginary website under test</caption> * <body> * <ul id="basket"> * <li><a href="#">Apple</a></li> * <li><a href="#">Banana</a></li> * <li><a href="#">Coconut</a></li> * <li><a href="#" class="has-discount">Date</a></li> * </ul> * <div id="summary"> * <strong class="out-of-stock">Coconut</strong> is not available * </div> * <button type="submit">Proceed to Checkout</button> * </body> * * @example <caption>Locating a single element</caption> * import { by, Target, TargetElement } from '@serenity-js/webdriverio'; * * const proceedToCheckoutButton: TargetElement = * Target.the('Proceed to Checkout button').located(by.css(`button[type='submit']`)); * * @example <caption>Locating multiple elements</caption> * import { by, Target, TargetElements } from '@serenity-js/webdriverio'; * * const basketItems: TargetElements = * Target.all('items in the basket').located(by.css('ul#basket li')); * * @example <caption>Locating element relative to another element</caption> * import { by, Target, TargetElement } from '@serenity-js/webdriverio'; * * const summary: TargetElement = * Target.the('summary').located(by.id('message')); * * const outOfStockItem: TargetElement = * Target.the('out of stock item').of(summary).located(by.css('.out-of-stock')) * * @example <caption>Filtering elements matched by a locator</caption> * import { by, Target, Text } from '@serenity-js/webdriverio'; * import { endsWith } from '@serenity-js/assertions'; * * const basketItems = * Target.all('items in the basket').located(by.css('ul#basket li')) * .where(Text, endsWith('e')); // Apple, Date * * @example <caption>Counting items matched by a locator</caption> * import { endsWith } from '@serenity-js/assertions'; * import { Question } from '@serenity-js/core'; * import { by, Target, Text } from '@serenity-js/webdriverio'; * * const basketItemsCount: Question<Promise<number>> = * Target.all('items in the basket').located(by.css('ul#basket li')) * .count() // 4 * * @example <caption>Getting first item matched by a locator</caption> * import { Question } from '@serenity-js/core'; * import { by, Target } from '@serenity-js/webdriverio'; * import { Element } from 'webdriverio'; * * const apple: Question<Promise<Element<'async'>>> = * Target.all('items in the basket').located(by.css('ul#basket li')) * .first() * * @example <caption>Getting last item matched by a locator</caption> * import { Question } from '@serenity-js/core'; * import { by, Target } from '@serenity-js/webdriverio'; * import { endsWith } from '@serenity-js/assertions'; * import { Element } from 'webdriverio'; * * const date: Question<Promise<Element<'async'>>> = * Target.all('items in the basket').located(by.css('ul#basket li')) * .last() * * @example <caption>Getting nth item matched by a locator</caption> * import { Question } from '@serenity-js/core'; * import { by, Target } from '@serenity-js/webdriverio'; * import { Element } from 'webdriverio'; * * const banana: Question<Promise<Element<'async'>>> = * Target.all('items in the basket').located(by.css('ul#basket li')) * .get(1) * * @example <caption>Using multiple filters and nested targets</caption> * import { Question } from '@serenity-js/core'; * import { contain, endsWith } from '@serenity-js/assertions'; * import { by, CSSClasses, Target, Text } from '@serenity-js/webdriverio'; * import { Element } from 'webdriverio'; * * class Basket { * static component = Target.the('basket').located(by.id('basket')); * * static items = Target.all('items').located(by.css('li')) * .of(Basket.component); * * static link = Target.the('link').located(by.css('a')); * } * * const date: Question<Promise<Element<'async'>>> = * Basket.items * .where(Text, endsWith('e')) * .where(CSSClasses.of(Basket.link), contain('has-discount')) * .first() * * @example <caption>Clicking on an element</caption> * import { actorCalled } from '@serenity-js/core'; * import { BrowseTheWeb, Click } from '@serenity-js/webdriverio'; * * actorCalled('Jane') * .whoCan(BrowseTheWeb.using(browser)) * .attemptsTo( * Click.on(proceedToCheckoutButton), * ); * * @example <caption>Retrieving text of multiple elements and performing an assertion</caption> * import { Ensure, contain } from '@serenity-js/assertions'; * import { actorCalled } from '@serenity-js/core'; * import { BrowseTheWeb, Text } from '@serenity-js/webdriverio'; * * const basketItemNames = Text.ofAll(basketItems); * * actorCalled('Jane') * .whoCan(BrowseTheWeb.using(browser)) * .attemptsTo( * Ensure.that(basketItemNames, contain('Apple')) * ); * * @example <caption>Waiting on an element</caption> * import { actorCalled } from '@serenity-js/core'; * import { BrowseTheWeb, Wait, isClickable } from '@serenity-js/webdriverio'; * * actorCalled('Jane') * .whoCan(BrowseTheWeb.using(browser)) * .attemptsTo( * Wait.until(proceedToCheckoutButton, isClickable()), * ); */ export class Target { /** * @desc * Locates a single Web element * * @param {string} description * A human-readable name of the element, which will be used in the report * * @returns {TargetBuilder<TargetElement> & NestedTargetBuilder<TargetNestedElement>} */ static the(description: string): TargetBuilder<TargetElement> & NestedTargetBuilder<TargetNestedElement> { return { located(locator: Locator): TargetElement { return new TargetElement(`the ${ description }`, locator); }, of(parent: Answerable<Element<'async'>>) { return { located(locator: Locator): TargetNestedElement { return new TargetNestedElement(parent, new TargetElement(description, locator)); } } } } } /** * @desc * Locates a group of Web elements * * @param {string} description * A human-readable name of the group of elements, which will be used in the report * * @returns {TargetBuilder<TargetElements> & NestedTargetBuilder<TargetNestedElements>} */ static all(description: string): TargetBuilder<TargetElements> & NestedTargetBuilder<TargetNestedElements> { return { located(locator: Locator): TargetElements { return new TargetElements(description, locator); }, of(parent: Answerable<Element<'async'>>) { return { located(locator: Locator): TargetNestedElements { return new TargetNestedElements(parent, new TargetElements(description, locator)); } } } } } } /** * @desc * You probably don't want to use this class directly. See {@link Target} instead. * * @extends {@serenity-js/core/lib/screenplay~Question} * @implements {@serenity-js/core/lib/screenplay/questions~MetaQuestion} * * @see {@link Target} */ export class TargetElements extends Question<Promise<ElementArray>> implements MetaQuestion<Answerable<Element<'async'>>, Promise<ElementArray>> { private readonly list: List<ElementArrayListAdapter, Promise<Element<'async'>>, Promise<ElementArray>>; constructor( description: string, private readonly locator: Locator, ) { super(description); this.list = new List(new ElementArrayListAdapter(this)); } of(parent: Answerable<Element<'async'>>): TargetNestedElements { return new TargetNestedElements(parent, this); } count(): Question<Promise<number>> { return this.list.count(); } first(): Question<Promise<Element<'async'>>> { return this.list.first() } last(): Question<Promise<Element<'async'>>> { return this.list.last() } get(index: number): Question<Promise<Element<'async'>>> { return this.list.get(index); } where<Answer_Type>( question: MetaQuestion<Answerable<Element<'async'>>, Promise<Answer_Type> | Answer_Type>, expectation: Expectation<any, Answer_Type>, ): TargetList { return this.list.where(question, expectation); } answeredBy(actor: AnswersQuestions & UsesAbilities): Promise<ElementArray> { return this.locator.allMatching() .describedAs(this.subject) .answeredBy(actor); } } /** * @desc * You probably don't want to use this class directly. See {@link Target} instead. * * @extends {@serenity-js/core/lib/screenplay~Question} * @implements {@serenity-js/core/lib/screenplay/questions~MetaQuestion} * * @see {@link Target} */ export class TargetNestedElements extends Question<Promise<ElementArray>> implements MetaQuestion<Answerable<Element<'async'>>, Promise<ElementArray>> { private readonly list: List<ElementArrayListAdapter, Promise<Element<'async'>>, Promise<ElementArray>>; constructor( private readonly parent: Answerable<Element<'async'>>, private readonly children: Answerable<ElementArray>, ) { super(`${ children } of ${ parent }`); this.list = new List(new ElementArrayListAdapter(this)); } of(parent: Answerable<Element<'async'>>): Question<Promise<ElementArray>> { return new TargetNestedElements(parent, this); } count(): Question<Promise<number>> { return this.list.count(); } first(): Question<Promise<Element<'async'>>> { return this.list.first() } last(): Question<Promise<Element<'async'>>> { return this.list.last() } get(index: number): Question<Promise<Element<'async'>>> { return this.list.get(index); } where<Answer_Type>( question: MetaQuestion<Answerable<Element<'async'>>, Promise<Answer_Type> | Answer_Type>, expectation: Expectation<any, Answer_Type>, ): TargetList { return this.list.where(question, expectation); } async answeredBy(actor: AnswersQuestions & UsesAbilities): Promise<ElementArray> { const parent = await actor.answer(this.parent); const children = await actor.answer(this.children); if (! parent) { throw new LogicError(formatted `Couldn't find ${ this.parent }`); } return parent.$$(children.selector); } } /** * @desc * You probably don't want to use this class directly. See {@link Target} instead. * * @extends {@serenity-js/core/lib/screenplay~Question} * @implements {@serenity-js/core/lib/screenplay/questions~MetaQuestion} * * @see {@link Target} */ export class TargetElement extends Question<Promise<Element<'async'>>> implements MetaQuestion<Answerable<Element<'async'>>, Promise<Element<'async'>>> { constructor( description: string, private readonly locator: Locator, ) { super(description); } of(parent: Answerable<Element<'async'>>): Question<Promise<Element<'async'>>> { return new TargetNestedElement(parent, this); } answeredBy(actor: AnswersQuestions & UsesAbilities): Promise<Element<'async'>> { return this.locator.firstMatching() .describedAs(this.subject) .answeredBy(actor); } } /** * @desc * You probably don't want to use this class directly. See {@link Target} instead. * * @extends {@serenity-js/core/lib/screenplay~Question} * @implements {@serenity-js/core/lib/screenplay/questions~MetaQuestion} * * @see {@link Target} */ export class TargetNestedElement extends Question<Promise<Element<'async'>>> implements MetaQuestion<Answerable<Element<'async'>>, Promise<Element<'async'>>> { constructor( private readonly parent: Answerable<Element<'async'>>, private readonly child: Answerable<Element<'async'>>, ) { super(`${ child } of ${ parent }`); } of(parent: Answerable<Element<'async'>>): Question<Promise<Element<'async'>>> { return new TargetNestedElement(parent, this); } async answeredBy(actor: AnswersQuestions & UsesAbilities): Promise<Element<'async'>> { const parent = await actor.answer(this.parent); const child = await actor.answer(this.child); if (! parent) { throw new LogicError(formatted `Couldn't find ${ this.parent }`); } return parent.$(child.selector); } }
the_stack
module CorsicaTests { "use strict"; var timeoutMax = 33 * 2; // expected duration for use with timeout() or timeout(0), 33ms was not always reliable var AsyncWorkQueue = function () { this._queue = []; this._token = 0; }; function errorHandler(msg) { try { LiveUnit.Assert.fail('There was an unhandled error in your test: ' + msg); } catch (ex) { } } AsyncWorkQueue.prototype = { cancel: function (token) { for (var i = 0, len = this._queue.length; i < len; i++) { if (this._queue[i].token === token) { this._queue[i].canceled = true; return true; } } return false; }, clear: function () { this._queue = [], this._token = 0; }, drain: function () { while (this._queue.length > 0) { this.process(); } }, getItem: function (pos) { return this._queue[pos]; }, process: function () { var len = this._queue.length; for (var i = 0; i < len; i++) { var item = this._queue[i]; if (item.canceled) { continue; } item.code(); } this._queue.splice(0, len); }, processN: function (cnt) { var len = Math.min(cnt || 0, this._queue.length); for (var i = 0; cnt > 0 && i < len; i++) { var item = this._queue[i]; if (item.canceled) { continue; } item.code(); cnt--; } this._queue.splice(0, len); }, schedule: function (item) { var token = ++this._token; this._queue.push({ code: item, token: token }); return token; } }; var q = new AsyncWorkQueue(); function asyncAdd(x, y): WinJS.Promise<number> { return new WinJS.Promise(function (complete) { q.schedule(function () { complete(x + y); }, 0); }); } function asyncAddWithCancellation(x, y, onCancel?) { var token; return new WinJS.Promise( function (complete) { token = q.schedule(function () { complete(x + y); }, 0); }, function () { q.cancel(token); if (onCancel) { onCancel(); } } ); } function asyncAddWithProgress(x, y) { return new WinJS.Promise(function (complete, error, progress) { q.schedule( function () { progress("almost!"); q.schedule( function () { progress("really!"); q.schedule( function () { complete(x + y); }, 0 ); }, 0 ); }, 0 ); }); } function asyncAddWithError(x, y) { return new WinJS.Promise(function (complete, error) { q.schedule(function () { error("I refuse to do math!"); }, 0); }); } // This is how one would be able to protected a Promise from a cancelation request. // var NoncancelablePromise = function (promise) { return new WinJS.Promise(function (c, e, p) { promise.then(c, e, p); }); } function addAsyncNoQueue(l, r, options?): WinJS.Promise<number> { // if options not passed in, define it as an empty object so we can just check if members are present options = options || {}; return new WinJS.Promise( function (complete, error) { try { if (options.throwException) { throw "addAsyncNoQueue throwing requested exception"; } var sum = l + r; complete(sum); } catch (e) { error(e); } } ); } export class Promise { testInitializationError = function () { q.clear(); var p = new WinJS.Promise(function () { throw "Error initializing"; }); var hitCompleteCount = 0, hitErrorCount = 0; p.then( function () { hitCompleteCount++; }, function (e) { hitErrorCount++; LiveUnit.Assert.areEqual("Error initializing", e); } ); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); } testCallingCompleteMultipleTimes = function () { q.clear(); var p = new WinJS.Promise(function (c) { q.schedule(function () { c(1); c(2); }); }); var hitCompleteCount = 0, hitErrorCount = 0; p.then(function (v) { hitCompleteCount++; LiveUnit.Assert.areEqual(1, v); }, function () { hitErrorCount++; }); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); } testCallingErrorMultipleTimes = function () { q.clear(); var p = new WinJS.Promise(function (c, e) { q.schedule(function () { e(1); e(2); }); }); var hitCompleteCount = 0, hitErrorCount = 0; p.then( function (v) { hitCompleteCount++; }, function (e) { hitErrorCount++; LiveUnit.Assert.areEqual(e, 1); } ); q.drain(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); } testCallingCompleteAndThenError = function () { q.clear(); var p = new WinJS.Promise(function (c, e) { q.schedule(function () { c(1); e(2); }); }); var hitCompleteCount = 0, hitErrorCount = 0; p.then(function (v) { hitCompleteCount++; LiveUnit.Assert.areEqual(1, v); }).then(null, function (e) { hitErrorCount++; }); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); } testCallingErrorAndThenComplete = function () { q.clear(); var p = new WinJS.Promise(function (c, e) { q.schedule(function () { e(2); c(1); }); }); var hitCompleteCount = 0, hitErrorCount = 0; p. then(function (v) { hitCompleteCount++; }). then(null, function (e) { hitErrorCount++; LiveUnit.Assert.areEqual(2, e); }); q.drain(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); } testCallingCompleteAfterProgress = function () { q.clear(); var p = new WinJS.Promise(function (c, e, p) { q.schedule(function () { p(0); p(1); c(2); }); }); var hitCompleteCount = 0, hitErrorCount = 0, hitProgressCount = 0; p. then( function (v) { hitCompleteCount++; LiveUnit.Assert.areEqual(2, v); }, function () { hitErrorCount++; }, function () { hitProgressCount++; } ); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); LiveUnit.Assert.areEqual(2, hitProgressCount); } testCallingProgressAfterComplete = function () { q.clear(); var p = new WinJS.Promise(function (c, e, p) { q.schedule(function () { p(0); c(2); p(1); }); }); var hitCompleteCount = 0, hitErrorCount = 0, hitProgressCount = 0; p. then( function (v) { hitCompleteCount++; LiveUnit.Assert.areEqual(2, v); }, function () { hitErrorCount++; }, function (v) { hitProgressCount++; LiveUnit.Assert.areEqual(0, v); } ); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); LiveUnit.Assert.areEqual(1, hitProgressCount); } testCallingErrorAfterProgress = function () { q.clear(); var p = new WinJS.Promise(function (c, e, p) { q.schedule(function () { p(0); p(1); e(2); }); }); var hitCompleteCount = 0, hitErrorCount = 0, hitProgressCount = 0; p. then( function () { hitCompleteCount++; }, function (e) { hitErrorCount++; LiveUnit.Assert.areEqual(2, e); }, function () { hitProgressCount++; } ); q.drain(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); LiveUnit.Assert.areEqual(2, hitProgressCount); } testCallingProgressAfterError = function () { q.clear(); var p = new WinJS.Promise(function (c, e, p) { q.schedule(function () { p(0); e(2); p(1); }); }); var hitCompleteCount = 0, hitErrorCount = 0, hitProgressCount = 0; p. then( function () { hitCompleteCount++; }, function (e) { hitErrorCount++; LiveUnit.Assert.areEqual(2, e); }, function (v) { hitProgressCount++; LiveUnit.Assert.areEqual(0, v); } ); q.drain(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); LiveUnit.Assert.areEqual(1, hitProgressCount); } testThenPartialRegistration1 = function () { q.clear(); var hitCompleteCount = 0, hitErrorCount = 0, hitProgressCount = 0; asyncAddWithProgress(1, 2). then(function () { hitCompleteCount++; }). then(null, function (e) { hitErrorCount++; throw e; }). then(null, null, function () { hitProgressCount++; }); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); // Because the progress handler is registered after a complete or // error handler it doesn't see the progress. // LiveUnit.Assert.areEqual(0, hitProgressCount); } testThenPartialRegistration2 = function () { q.clear(); var hitCompleteCount = 0, hitErrorCount = 0, hitProgressCount = 0; asyncAddWithProgress(1, 2). then(null, null, function () { hitProgressCount++; }). then(null, function (e) { hitErrorCount++; throw e; }). then(function () { hitCompleteCount++; }); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); LiveUnit.Assert.areEqual(2, hitProgressCount); } testThenPartialRegistration3 = function () { q.clear(); var hitCompleteCount = 0, hitErrorCount = 0, hitProgressCount = 0; asyncAddWithError(1, 2). then(null, function (e) { hitErrorCount++; throw e; }). then(null, null, function () { hitProgressCount++; }). then(function () { hitCompleteCount++; }). then(null, function () { }); q.drain(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); LiveUnit.Assert.areEqual(0, hitProgressCount); } testThenPartialRegistration4 = function () { q.clear(); var hitCompleteCount = 0, hitErrorCount = 0, hitProgressCount = 0; asyncAddWithError(1, 2). then(null, null, function () { hitProgressCount++; }). then(function () { hitCompleteCount++; }). then(null, function (e) { hitErrorCount++; throw e; }). then(null, function () { }); q.drain(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); LiveUnit.Assert.areEqual(0, hitProgressCount); } testThenPartialRegistration5 = function () { q.clear(); var hitCompleteCount = 0, hitErrorCount = 0, hitProgressCount = 0; asyncAddWithProgress(1, 2). then(null, function (e) { hitErrorCount++; throw e; }). then(null, null, function () { hitProgressCount++; }). then(function () { hitCompleteCount++; }); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); // Because the progress handler is registered after a complete or // error handler it doesn't see the progress. // LiveUnit.Assert.areEqual(0, hitProgressCount); } testProgressIsNotBuffered = function () { q.clear(); var p = new WinJS.Promise(function (c, e, p) { q.schedule(function () { p(1); }); q.schedule(function () { p(2); }); q.schedule(function () { c(3); }); }); var hitCompleteCount = 0, hitErrorCount = 0, hitProgressCount = 0; q.processN(1); p.then( function () { hitCompleteCount++; }, function () { hitErrorCount++; }, function (v) { hitProgressCount++; LiveUnit.Assert.areEqual(2, v); } ); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); LiveUnit.Assert.areEqual(0, hitProgressCount); q.processN(1); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); LiveUnit.Assert.areEqual(1, hitProgressCount); q.processN(1); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); LiveUnit.Assert.areEqual(1, hitProgressCount); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); LiveUnit.Assert.areEqual(1, hitProgressCount); } testProgressWaterfall = function () { q.clear(); var p = new WinJS.Promise(function (c, e, p) { q.schedule(function () { p(1); }); q.schedule(function () { c(2); }); }); var hitProgress1Count = 0, hitProgress2Count = 0, hitProgress3Count = 0, hitProgress4Count = 0, hitCompleteCount = 0; p.then(null, null, function (v) { hitProgress1Count++; LiveUnit.Assert.areEqual(1, v); }).then(null, null, function (v) { hitProgress2Count++; LiveUnit.Assert.areEqual(1, v); }).then(function (v) { hitCompleteCount++; LiveUnit.Assert.areEqual(2, v); }, null, function (v) { hitProgress3Count++; LiveUnit.Assert.areEqual(1, v); }).then(null, null, function (v) { hitProgress4Count++; }); q.drain(); LiveUnit.Assert.areEqual(1, hitProgress1Count); LiveUnit.Assert.areEqual(1, hitProgress2Count); LiveUnit.Assert.areEqual(1, hitProgress3Count); LiveUnit.Assert.areEqual(0, hitProgress4Count); LiveUnit.Assert.areEqual(1, hitCompleteCount); } testCancellationOfConstantPromise = function () { q.clear(); var hitCompleteCount = 0, hitErrorCount = 0; WinJS.Promise.as(1). then(function (value) { return asyncAddWithCancellation(value, 1); }). then(function (value) { hitCompleteCount++; }, function (error) { hitErrorCount++; }). cancel(); q.drain(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); }; testCancellationOfInFlightPromise = function () { q.clear(); var hitCompleteCount = 0, hitErrorCount = 0; asyncAddWithCancellation(1, 1). then(function (value) { return asyncAdd(value, 1); }). then(function (value) { hitCompleteCount++; }, function (error) { hitErrorCount++; }). cancel(); LiveUnit.Assert.isTrue(q.getItem(0).canceled); q.drain(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); }; testCancellationOfTree = function () { q.clear(); var cancelCount = 0; var onCancel = function () { cancelCount++; }; var p1 = asyncAddWithCancellation(1, 1, onCancel); q.drain(); LiveUnit.Assert.areEqual(0, cancelCount); p1 = p1.then(function (value) { return asyncAddWithCancellation(value, 3, onCancel); }); var p2 = asyncAddWithCancellation(1, 2, onCancel); var p3 = WinJS.Promise.join({ p1: p1, p2: p2 }). then(function (values) { return asyncAddWithCancellation(values, 4, onCancel); }); p3.cancel(); q.drain(); LiveUnit.Assert.areEqual(2, cancelCount); }; testPromiseDeadlock = function () { q.clear(); var hitCompleteCount = 0; var a, b; var c = asyncAdd(1, 2); a = c.then(function (v) { hitCompleteCount++; return b; }). then(function (v) { hitCompleteCount++; }); b = c.then(function (v) { hitCompleteCount++; return a; }). then(function (v) { hitCompleteCount++; }); q.drain(); // These promises deadlock on each other and never make forward progress. LiveUnit.Assert.areEqual(2, hitCompleteCount); }; testPromiseDeadlockCancellation = function () { q.clear(); var hitCompleteCount = 0, hitFirstErrorCount = 0, hitSecondErrorCount = 0; var c: any = asyncAdd(1, 2); var a0: any = c.then( function (v) { hitCompleteCount++; return b; }, function () { hitFirstErrorCount++; } ); var a: any = a0.then( function () { hitCompleteCount++; }, function (e) { hitSecondErrorCount++; LiveUnit.Assert.areEqual("Canceled", e.message); throw e; } ); var b0: any = c.then( function (v) { hitCompleteCount++; return a; }, function () { hitFirstErrorCount++; } ) var b: any = b0.then( function () { hitCompleteCount++; }, function (e) { hitSecondErrorCount++; LiveUnit.Assert.areEqual("Canceled", e.message); throw e; } ); c.name = "c"; a0.name = "a0"; a.name = "a"; b0.name = "b0"; b.name = "b"; q.drain(); // These promises deadlock on each other and never make forward progress. LiveUnit.Assert.areEqual(2, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitFirstErrorCount); LiveUnit.Assert.areEqual(0, hitSecondErrorCount); // Should cancel both. b.cancel(); LiveUnit.Assert.areEqual(2, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitFirstErrorCount); LiveUnit.Assert.areEqual(2, hitSecondErrorCount); }; testBlockingOfCancelation = function () { q.clear(); var hitCancelCount = 0, hitProtectedCompleteCount = 0, hitCompleteCount = 0, hitErrorCount = 0; var a = NoncancelablePromise( asyncAddWithCancellation(1, 2, function () { hitCancelCount++; }). then(function () { hitProtectedCompleteCount++; }) ).then( function () { hitCompleteCount++; }, function (e) { hitErrorCount++; LiveUnit.Assert.areEqual("Canceled", e.message); } ); a.cancel(); q.drain(); LiveUnit.Assert.areEqual(0, hitCancelCount); LiveUnit.Assert.areEqual(1, hitProtectedCompleteCount); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); } testCancellationOnJoinOfSamePromise = function () { q.clear(); var hitCancelCount = 0, hitCompleteCount = 0, hitErrorCount = 0; var p = asyncAddWithCancellation(1, 2, function () { hitCancelCount++; }). then(function () { hitCompleteCount++; }, function () { hitErrorCount++; }); WinJS.Promise.join([p, p, p]).cancel(); q.drain(); LiveUnit.Assert.areEqual(1, hitCancelCount); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); }; testCycle = function () { q.clear(); var hitCompleteCount = 0, hitErrorCount = 0; var p = asyncAdd(1, 2); p. then( function (v) { hitCompleteCount++; LiveUnit.Assert.areEqual(3, v); return p; }, function () { hitErrorCount++; } ). then( function (v) { hitCompleteCount++; LiveUnit.Assert.areEqual(3, v); return p; }, function () { hitErrorCount++; } ). then( function (v) { hitCompleteCount++; LiveUnit.Assert.areEqual(3, v); }, function () { hitErrorCount++; } ); q.drain(); LiveUnit.Assert.areEqual(3, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); }; testChainedAdds = function () { q.clear(); var hitCompleteCount = 0; WinJS.Promise.as(1). then(function (value) { hitCompleteCount++; return asyncAdd(value, 1); }). then(function (value) { hitCompleteCount++; LiveUnit.Assert.areEqual(2, value); return asyncAdd(value, 2); }). then(function (value) { hitCompleteCount++; LiveUnit.Assert.areEqual(4, value); return asyncAdd(value, 3); }). then(function (value) { hitCompleteCount++; LiveUnit.Assert.areEqual(7, value); }); q.drain(); LiveUnit.Assert.areEqual(4, hitCompleteCount); }; testError = function () { q.clear(); var hitCompleteCount = 0, hitErrorCount = 0; WinJS.Promise.as(1). then(function (value) { return asyncAddWithError(value, 1); }). then(function () { hitCompleteCount++; }, function () { hitErrorCount++; throw 1; }). then(function () { hitCompleteCount++; }, function () { hitErrorCount++; }); q.drain(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(2, hitErrorCount); }; testErrorRecovery = function () { q.clear(); var hitCompleteCount = 0, hitErrorCount = 0; WinJS.Promise.as(1). then(function (value) { return asyncAddWithError(value, 1); }). then(function () { hitCompleteCount++; }, function () { hitErrorCount++; return 10; }). then(function (value) { hitCompleteCount++; LiveUnit.Assert.areEqual(10, value); }, function () { hitErrorCount++; }); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); }; testErrorWithFork = function () { q.clear(); var hitCompleteCount = 0, hitErrorCount = 0; var p = WinJS.Promise.as(1). then(function (value) { return asyncAddWithError(value, 1); }); p.then(function () { hitCompleteCount++; }, function () { hitErrorCount++; }); p.then(function () { hitCompleteCount++; }, function () { hitErrorCount++; }); q.drain(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(2, hitErrorCount); }; testExceptionFromCompleteHandler = function () { q.clear(); var hit1stCompleteCount = 0, hit1stErrorCount = 0, hit2ndCompleteCount = 0, hit2ndErrorCount = 0; asyncAdd(1, 2). then( function () { hit1stCompleteCount++; throw 1; }, function () { hit1stErrorCount++; } ). then( function () { hit2ndCompleteCount++; }, function () { hit2ndErrorCount++; } ); q.drain(); LiveUnit.Assert.areEqual(1, hit1stCompleteCount); LiveUnit.Assert.areEqual(0, hit1stErrorCount); LiveUnit.Assert.areEqual(0, hit2ndCompleteCount); LiveUnit.Assert.areEqual(1, hit2ndErrorCount); }; testFallthroughComplete = function () { q.clear(); var hitCompleteCount = 0; WinJS.Promise.as(1). then(function (value) { return asyncAdd(value, 1); }). then(function (value) { LiveUnit.Assert.areEqual(2, value); hitCompleteCount++; return value; }). then(function (value) { LiveUnit.Assert.areEqual(2, value); hitCompleteCount++; return value; }). then(function (value) { LiveUnit.Assert.areEqual(2, value); hitCompleteCount++; return value; }); q.drain(); LiveUnit.Assert.areEqual(3, hitCompleteCount); }; testProgess = function () { q.clear(); var hitProgressCount = 0, hitCompleteCount = 0, hitErrorCount = 0; WinJS.Promise.as(1). then(function (value) { return asyncAddWithProgress(value, 1); }). then(function () { hitCompleteCount++; }, function () { hitErrorCount++; }, function () { hitProgressCount++; }); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); LiveUnit.Assert.areEqual(2, hitProgressCount); }; testProgressExceptionIsIgnored = function () { q.clear(); var hitProgressCount = 0, hitCompleteCount = 0, hitErrorCount = 0; WinJS.Promise.as(1). then(function (value) { return asyncAddWithProgress(value, 1); }). then(function () { hitCompleteCount++; }, function () { hitErrorCount++; }, function () { hitProgressCount++; throw 1; }); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); LiveUnit.Assert.areEqual(2, hitProgressCount); } testPromise_As = function () { q.clear(); var p = asyncAdd(1, 2); LiveUnit.Assert.isTrue(p instanceof WinJS.Promise); LiveUnit.Assert.areEqual(p, WinJS.Promise.as(p)); var o = { a: 1 }; var p1 = WinJS.Promise.as(o); LiveUnit.Assert.areNotEqual(o, p1); var hitCompleteCount = 0; var p1Value; // This will run synchronously because it is already complete. p1.then(function (value) { hitCompleteCount++; p1Value = value; }); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.isTrue(o === p1Value); // The contract we look for in 'as' is the same as 'is', you must have // a function which is named 'then'. var o2 = { then: function () { } }; LiveUnit.Assert.isTrue(o2 === WinJS.Promise.as(o2)); }; testPromise_Any = function () { q.clear(); var hitCompleteCount = 0; var input = [ asyncAdd(1, 2), asyncAdd(3, 4) ]; WinJS.Promise.any(input). then(function (item) { hitCompleteCount++; LiveUnit.Assert.areEqual(input[0], item.value); LiveUnit.Assert.areNotEqual(input[1], item.value); }); q.processN(1); LiveUnit.Assert.areEqual(1, hitCompleteCount); q.drain(); }; testPromise_AnyWithNonPromiseInput = function () { q.clear(); var hitCompleteCount = 0; var input: any[] = [ asyncAdd(1, 2), asyncAdd(3, 4), 5 ]; WinJS.Promise.any(input). then(function (item) { hitCompleteCount++; LiveUnit.Assert.areEqual(5, item.value); LiveUnit.Assert.areEqual(input[2], item.value); LiveUnit.Assert.areNotEqual(input[0], item.value); LiveUnit.Assert.areNotEqual(input[1], item.value); }); LiveUnit.Assert.areEqual(1, hitCompleteCount); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); }; testPromise_AnyWithAllNonPromiseInput = function () { q.clear(); var hitCompleteCount = 0; var input: any[] = [ 3, 7, 5 ]; WinJS.Promise.any(input). then(function (item) { hitCompleteCount++; LiveUnit.Assert.areEqual(3, item.value); LiveUnit.Assert.areEqual(input[0], item.value); LiveUnit.Assert.areNotEqual(input[1], item.value); LiveUnit.Assert.areNotEqual(input[2], item.value); }); LiveUnit.Assert.areEqual(1, hitCompleteCount); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); }; testPromise_AnyWithError = function () { q.clear(); var hitCompleteCount = 0, hitErrorCount = 0; var input = [ asyncAddWithError(1, 2), asyncAdd(3, 4) ]; WinJS.Promise.any(input). then( function () { hitCompleteCount++; }, function (item) { hitErrorCount++; LiveUnit.Assert.areEqual(input[0], item.value); // One promise is fulfilled, remove it from the array, and block until // the other one is fulfilled input.splice(input.indexOf(item.value), 1); return WinJS.Promise.any(input); } ). then( function (item) { hitCompleteCount++; LiveUnit.Assert.areEqual(input[0], item.value); }, function () { hitErrorCount++; } ); q.processN(1); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); }; testPromise_AnyWithError2 = function () { q.clear(); var hitCompleteCount = 0, hitErrorCount = 0; var p0 = asyncAddWithError(1, 2); var p1 = asyncAdd(3, 4); // Make sure the later element in the array completes earlier. // var input = [p1, p0]; WinJS.Promise.any(input). then( function () { hitCompleteCount++; }, function (item) { hitErrorCount++; LiveUnit.Assert.areEqual(input[1], item.value); // One promise is fulfilled, remove it from the array, and block until // the other one is fulfilled input.splice(input.indexOf(item.value), 1); return WinJS.Promise.any(input); } ). then( function (item) { hitCompleteCount++; LiveUnit.Assert.areEqual(input[0], item.value); }, function () { hitErrorCount++; } ); q.processN(1); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); }; testPromise_AnyCancellation = function () { q.clear(); var hitCancelCount = 0, hitCompleteCount = 0, hitErrorCount = 0; var p0 = asyncAddWithCancellation(1, 2, function () { hitCancelCount++; }); var p1 = asyncAddWithCancellation(1, 2, function () { hitCancelCount++; }); var a = WinJS.Promise.any([p0, p1]). then( function () { hitCompleteCount++; }, function (e) { hitErrorCount++; LiveUnit.Assert.areEqual("Canceled", e.message); } ); a.cancel(); LiveUnit.Assert.areEqual(2, hitCancelCount); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); q.drain(); WinJS.Promise.any([p0, p1]). then( function () { hitCompleteCount++; }, function (e) { hitErrorCount++; LiveUnit.Assert.areEqual("Canceled", e.message); } ); LiveUnit.Assert.areEqual(2, hitCancelCount); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(2, hitErrorCount); q.drain(); LiveUnit.Assert.areEqual(2, hitCancelCount); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(2, hitErrorCount); }; testPromise_AnyWithRecord = function () { q.clear(); var hitCompleteCount = 0; var input = { first: asyncAdd(1, 2), second: asyncAdd(3, 4) }; WinJS.Promise.any(input). then(function (item) { hitCompleteCount++; LiveUnit.Assert.areEqual("first", item.key); LiveUnit.Assert.areEqual(input.first, item.value); LiveUnit.Assert.areNotEqual(input.second, item.value); }); q.processN(1); LiveUnit.Assert.areEqual(1, hitCompleteCount); q.drain(); } testPromise_Is = function () { LiveUnit.Assert.isTrue(WinJS.Promise.is(WinJS.Promise.wrap(12))); LiveUnit.Assert.isFalse(WinJS.Promise.is(12)); LiveUnit.Assert.isTrue(WinJS.Promise.is({ then: function () { return 1; } })); LiveUnit.Assert.isFalse(WinJS.Promise.is({ then: 1 })); }; testPromise_wrapCancellation = function () { var hitCompleteCount = 0; var a = WinJS.Promise.wrap(1); a.cancel(); a.then(function () { hitCompleteCount++; }); LiveUnit.Assert.areEqual(1, hitCompleteCount); }; testPromise_wrapErrorCancellation = function () { var hitCompleteCount = 0, hitErrorCount = 0; var a = WinJS.Promise.wrapError(1); a.cancel(); a.then( function () { hitCompleteCount++; }, function (e) { hitErrorCount++; LiveUnit.Assert.areEqual(1, e); } ); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); }; testPromise_Join = function () { q.clear(); var hitCompleteCount = 0; var result; WinJS.Promise.join({ first: asyncAdd(1, 2), second: asyncAdd(3, 4) }). then(function (value) { hitCompleteCount++; result = value.first + value.second; }); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(10, result); }; testPromise_JoinProgress = function () { q.clear(); var hitCompleteCount = 0, hitProgressCount = 0; var result; var input = { first: asyncAddWithProgress(1, 2), second: asyncAddWithProgress(3, 4), third: asyncAddWithProgress(6, 7) }; WinJS.Promise.join(input). then( function (value) { hitCompleteCount++; result = value.first + value.second + value.third; }, null, function (value) { LiveUnit.Assert.areEqual(Object.keys(input)[hitProgressCount], value.Key); hitProgressCount++; } ); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); // We don't get a progress callback for the last item to complete. // LiveUnit.Assert.areEqual(2, hitProgressCount); LiveUnit.Assert.areEqual(23, result); }; testPromise_JoinWithArray = function () { q.clear(); var hitCompleteCount = 0; var result; WinJS.Promise.join([ asyncAdd(1, 2), asyncAdd(3, 4) ]). then(function (value) { hitCompleteCount++; result = value[0] + value[1]; }); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(10, result); }; testPromise_JoinWithError = function () { q.clear(); var hitCompleteCount = 0, hitErrorCount = 0; WinJS.Promise.join({ first: asyncAdd(1, 2), second: asyncAddWithError(3, 4) }). then(function (value) { hitCompleteCount++; return 12; }). then(null, function (error) { hitErrorCount++; LiveUnit.Assert.isTrue(error.second !== undefined); LiveUnit.Assert.isTrue(error.first === undefined); }); q.drain(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); }; testPromise_JoinWithNonPromiseInput = function () { q.clear(); var hitCompleteCount = 0; var result; WinJS.Promise.join({ first: asyncAdd(1, 2), second: asyncAdd(3, 4), third: 24 }). then(function (value) { hitCompleteCount++; result = value.first + value.second + value.third; }); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(34, result); }; testPromise_JoinWithAllNonPromiseInput = function () { q.clear(); var hitCompleteCount = 0; var result; WinJS.Promise.join({ first: 3, second: 7, third: 24 }). then(function (value) { hitCompleteCount++; result = value.first + value.second + value.third; }); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(34, result); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(34, result); }; testPromise_Then = function () { q.clear(); var hitCompleteCount = 0; var p = WinJS.Promise.as(1); p = WinJS.Promise.then(p, function (value) { hitCompleteCount++; return asyncAdd(value, 1); }); p = WinJS.Promise.then(p, function (value) { hitCompleteCount++; LiveUnit.Assert.areEqual(2, value); return asyncAdd(value, 2); }); p = WinJS.Promise.then(p, function (value) { hitCompleteCount++; LiveUnit.Assert.areEqual(4, value); return asyncAdd(value, 3); }); p = WinJS.Promise.then(p, function (value) { hitCompleteCount++; LiveUnit.Assert.areEqual(7, value); }); q.drain(); LiveUnit.Assert.areEqual(4, hitCompleteCount); }; // @TODO, how do we do this? Include jQuery or dojo in the test tree? testInterop = function () { }; testTimeoutNoWait = function (complete) { var i = 0; var hit1 = false, hit2 = false; WinJS.Utilities._setImmediate(function () { hit1 = true; }); // calling timeout() without a parameter results in calling WinJS.Utilities._setImmediate() which will // execute immediately after the browser has processed outstanding work. WinJS.Promise.timeout().then(function () { i++; LiveUnit.Assert.areEqual(1, i); LiveUnit.Assert.isTrue(hit1, "expected to run after the above explicit WinJS.Utilities._setImmediate"); LiveUnit.Assert.isFalse(hit2, "expected to run before the below explicit WinJS.Utilities._setImmediate"); }). then(null, errorHandler). then(complete); LiveUnit.Assert.areEqual(0, i); WinJS.Utilities._setImmediate(function () { hit2 = true; }); }; testTimeoutOfPromises = function (complete) { var p = new WinJS.Promise(function () { }); var hitCompleteCount = 0, hitErrorCount = 0; p.then( function () { hitCompleteCount++; LiveUnit.Assert.fail("Should not complete"); }, function (e) { hitErrorCount++; LiveUnit.Assert.areEqual("Canceled", e.name); }); WinJS.Promise.timeout(0, p). then( function () { hitCompleteCount++; LiveUnit.Assert.fail("Should not complete"); }, function (e) { hitErrorCount++; LiveUnit.Assert.areEqual("Canceled", e.name); } ). then(function () { LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(2, hitErrorCount); }). then(null, errorHandler). then(complete); }; testTimeoutOfPromisesWhichComplete = function (complete) { var completeP; var p = new WinJS.Promise(function (c) { completeP = c; }); var hitCompleteCount = 0, hitErrorCount = 0; p.then( function (v) { hitCompleteCount++; LiveUnit.Assert.areEqual(1, v); }, function () { hitErrorCount++; LiveUnit.Assert.fail("should not error"); }); WinJS.Promise.timeout(0, p). then( function (v) { hitCompleteCount++; LiveUnit.Assert.areEqual(1, v); }, function () { hitErrorCount++; LiveUnit.Assert.fail("should not errror"); } ). then(function () { LiveUnit.Assert.areEqual(2, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); }). then(null, errorHandler). then(complete); completeP(1); }; testTimeoutZeroWait = function (complete) { var i = 0; var start = new Date(); // We were seeing some occaisional failures when expecting delay < 33ms so using larger value now // to increase test reliability. WinJS.Promise.timeout(0).then(function () { i++; LiveUnit.Assert.areEqual(1, i); var delay = new Date().valueOf() - start.valueOf(); LiveUnit.Assert.isTrue(delay < timeoutMax, "expected timeout < " + timeoutMax + ", got=" + delay); }). then(null, errorHandler). then(complete); LiveUnit.Assert.areEqual(0, i); }; testTimeoutWait = function (complete) { var timeoutDuration = 100; var i = 0; var start = new Date(); // expecting this timeout to fire within 50% of requested time out at the earliest WinJS.Promise.timeout(timeoutDuration).then(function () { i++; LiveUnit.Assert.areEqual(1, i); var delay = new Date().valueOf() - start.valueOf(); LiveUnit.Assert.isTrue(delay >= timeoutDuration / 2, "expected delay to be at least " + timeoutDuration / 2 + "; got actual delay=" + delay); }). then(null, errorHandler). then(complete); LiveUnit.Assert.areEqual(0, i); }; testTimeoutNoWaitCancel = function (complete) { var i = 0; var a = WinJS.Promise.timeout().then(function () { i++; LiveUnit.Assert.fail("this should never get called!"); }); WinJS.Promise.timeout(35).then(function () { i++; LiveUnit.Assert.areEqual(1, i); }). then(null, errorHandler). then(complete); a.cancel(); LiveUnit.Assert.areEqual(0, i); }; testTimeoutWaitCancel = function (complete) { var i = 0; var a = WinJS.Promise.timeout(25).then(function () { i++; LiveUnit.Assert.fail("this should never get called!"); }); WinJS.Promise.timeout(35).then(function () { i++; LiveUnit.Assert.areEqual(1, i); }). then(null, errorHandler). then(complete); a.cancel(); LiveUnit.Assert.areEqual(0, i); }; testThenEach = function (complete) { q.clear(); WinJS.Promise.thenEach([asyncAdd(1, 2), asyncAdd(3, 4), asyncAdd(5, 6)], function (value) { LiveUnit.Assert.areEqual("number", typeof value); return value; }). then(function (values) { LiveUnit.Assert.areEqual(3, values[0]); LiveUnit.Assert.areEqual(7, values[1]); LiveUnit.Assert.areEqual(11, values[2]); }). then(null, errorHandler). then(complete); q.drain(); } testCompletePromise = function () { var hitCompleteCount = 0, hitErrorCount = 0, hitProgressCount = 0; var c = new (<any>WinJS.Promise).wrap(1); var r1 = c.then( function (v) { hitCompleteCount++; LiveUnit.Assert.areEqual(1, v); }, function () { hitErrorCount++; }, function () { hitProgressCount++; } ); var r2 = r1.then( function () { hitCompleteCount++; } ); LiveUnit.Assert.isTrue(r1 === r2, "Because of our optimization in the sync completion path we should not allocate a new promise unless there is a new return value"); LiveUnit.Assert.areEqual(2, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); LiveUnit.Assert.areEqual(0, hitProgressCount); } testErrorPromise = function () { var hitCompleteCount = 0, hitErrorCount = 0, hitProgressCount = 0; var c = new (<any>WinJS.Promise).wrapError(1); c.then( function () { hitCompleteCount++; }, function (e) { hitErrorCount++; LiveUnit.Assert.areEqual(1, e); }, function () { hitProgressCount++; } ); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); LiveUnit.Assert.areEqual(0, hitProgressCount); } testOnErrorHandler = function () { q.clear(); var hitCount = 0; WinJS.Promise.onerror = function (evt) { LiveUnit.Assert.isTrue(!!evt.detail.error); hitCount++; }; var errorPromise = WinJS.Promise.wrapError(1); LiveUnit.Assert.areEqual(1, hitCount); var p = new WinJS.Promise(function (c, e) { q.schedule(function () { e(1); }); }); LiveUnit.Assert.areEqual(1, hitCount); q.drain(); LiveUnit.Assert.areEqual(2, hitCount); var hitComplete = false; p.then(null, function (value) { return 7; }).then(function (value) { hitComplete = true; LiveUnit.Assert.areEqual(7, value); }); LiveUnit.Assert.isTrue(hitComplete); LiveUnit.Assert.areEqual(3, hitCount); } testOnErrorDoesNotSeeCancelation = function () { q.clear(); var hitCount = 0; WinJS.Promise.onerror = function (evt) { LiveUnit.Assert.isTrue(!!evt.detail.error); hitCount++; }; try { LiveUnit.Assert.areEqual(0, hitCount); var p = new WinJS.Promise(function (c, e) { q.schedule(function () { e(1); }); }); LiveUnit.Assert.areEqual(0, hitCount); var completedHitCount = 0; var canceledHitCount = 0; p.then( function () { completedHitCount++; }, function (e) { if (e.name === "Canceled") { canceledHitCount++; } } ); p.cancel(); LiveUnit.Assert.areEqual(0, hitCount); LiveUnit.Assert.areEqual(1, canceledHitCount); LiveUnit.Assert.areEqual(0, completedHitCount); q.drain(); LiveUnit.Assert.areEqual(0, hitCount); LiveUnit.Assert.areEqual(1, canceledHitCount); LiveUnit.Assert.areEqual(0, completedHitCount); } finally { WinJS.Promise.onerror = undefined; } } testOnErrorHandlerPolicyWithHandledError = function (complete) { var onerrorCallbackCount = 0; var unhandledAfterPostCount = 0; var unhandledErrors = []; WinJS.Promise.onerror = function (evt) { onerrorCallbackCount++; var details = evt.detail; var id = details.id; if (!details.parent) { unhandledErrors[id] = details; WinJS.Promise.timeout().then(function () { var error = unhandledErrors[id]; if (error) { // // in real code here we would either log or rethrow the exception // unhandledAfterPostCount++; delete unhandledErrors[id] } }); } else if (details.handler) { delete unhandledErrors[id]; } }; var p: any = new WinJS.Promise(function (c, e) { e("This promise is broken"); }); LiveUnit.Assert.areEqual(1, onerrorCallbackCount); LiveUnit.Assert.areEqual(1, Object.keys(unhandledErrors).length); LiveUnit.Assert.areEqual(0, unhandledAfterPostCount); var hitCompleteCount = 0; var hitErrorCount = 0; var p = p. then(function (v) { /* never get here */ hitCompleteCount++; }). then(function (v) { /* never get here either */ hitCompleteCount++; }); // since we optimize the case where a promise has already been completed in error and // no error handler was specified we will only see a single onerrorCallbackCount LiveUnit.Assert.areEqual(1, onerrorCallbackCount); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); LiveUnit.Assert.areEqual(1, Object.keys(unhandledErrors).length); LiveUnit.Assert.areEqual(0, unhandledAfterPostCount); p. then(null, function (v) { hitErrorCount++; return 1; }). then(function (v) { hitCompleteCount++; LiveUnit.Assert.areEqual(1, v); }); LiveUnit.Assert.areEqual(2, onerrorCallbackCount); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); LiveUnit.Assert.areEqual(0, Object.keys(unhandledErrors).length); LiveUnit.Assert.areEqual(0, unhandledAfterPostCount); WinJS.Promise.timeout().then(function () { LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); LiveUnit.Assert.areEqual(0, Object.keys(unhandledErrors).length); LiveUnit.Assert.areEqual(0, unhandledAfterPostCount); WinJS.Promise.onerror = undefined; complete(); }); } testOnErrorHandlerPolicyWithUnhandledError = function (complete) { var unhandledAfterPostCount = 0; var unhandledErrors = []; WinJS.Promise.onerror = function (evt) { var details = evt.detail; var id = details.id; if (!details.parent) { unhandledErrors[id] = details; WinJS.Promise.timeout().then(function () { var error = unhandledErrors[id]; if (error) { // // in real code here we would either log or rethrow the exception // unhandledAfterPostCount++; delete unhandledErrors[id] } }); } else if (details.handler) { delete unhandledErrors[id]; } }; var p = new WinJS.Promise<void>(function (c, e) { e("This promise is broken"); }); var hitCompleteCount = 0; var hitErrorCount = 0; var p = p. then(function (v) { /* never get here */ hitCompleteCount++; }). then(function (v) { /* never get here either */ hitCompleteCount++; }); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); LiveUnit.Assert.areEqual(1, Object.keys(unhandledErrors).length); LiveUnit.Assert.areEqual(0, unhandledAfterPostCount); var errorHandler = function () { return true; } WinJS.Application.addEventListener("error", errorHandler); WinJS.Promise.timeout().then(function () { LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); // After hitting the unhandled handler it cleared out the unhandled error LiveUnit.Assert.areEqual(0, Object.keys(unhandledErrors).length); LiveUnit.Assert.areEqual(1, unhandledAfterPostCount); p. then(null, function (v) { hitErrorCount++; return 1; }). then(function (v) { hitCompleteCount++; LiveUnit.Assert.areEqual(1, v); }); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); LiveUnit.Assert.areEqual(0, Object.keys(unhandledErrors).length); LiveUnit.Assert.areEqual(1, unhandledAfterPostCount); WinJS.Promise.timeout().then(function () { LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); LiveUnit.Assert.areEqual(0, Object.keys(unhandledErrors).length); LiveUnit.Assert.areEqual(1, unhandledAfterPostCount); WinJS.Promise.onerror = undefined; WinJS.Application.removeEventListener("error", errorHandler); complete(); }); }); } // Testing basic error functionality and throwing an error inside complete testBasicOnErrorFunctionality = function () { var errorHitCount = 0, completeHitCount = 0; var onErrorHitCount = 0; try { WinJS.Promise.onerror = function (evt) { onErrorHitCount++; var detail = evt.detail; if (!!detail.parent) LiveUnit.Assert.isTrue(!!detail.handler); LiveUnit.Assert.isTrue(!!detail.id); LiveUnit.Assert.isTrue(!!detail.exception); LiveUnit.Assert.isTrue(!detail.error); } var p = new WinJS.Promise(function () { throw "exception inside function"; }). then(function () { completeHitCount++; }, function () { errorHitCount++; }). then( function () { LiveUnit.Assert.areEqual(1, errorHitCount); LiveUnit.Assert.areEqual(0, completeHitCount); LiveUnit.Assert.areEqual(2, onErrorHitCount); } ); } finally { WinJS.Promise.onerror = undefined; } } // Test removing the onerror handler before an error takes place and make sure that onerror will not be called testUnRegisterHandlerBeforeCallingPromise = function () { var handlerHitCount = 0; var errroHandler = function () { return true; } WinJS.Application.addEventListener("error", errorHandler); WinJS.Promise.onerror = function (evt) { var detail = evt.detail; handlerHitCount++; } try { WinJS.Promise.onerror = undefined; var p = new WinJS.Promise(function () { throw "exception inside function"; }, function () { }). then(function () { LiveUnit.Assert.areEqual(0, handlerHitCount); }); } finally { WinJS.Application.removeEventListener("error", errorHandler); WinJS.Promise.onerror = undefined; } } // Making sure that the errorID is the same for all the promise tree testVerifySameErrorId = function () { var handlerHitCount = 0; var id = undefined; WinJS.Promise.onerror = function (evt) { var detail = evt.detail; id = id || detail.id; LiveUnit.Assert.areEqual(id, detail.id); handlerHitCount++; } try { var p = new WinJS.Promise(function () { throw "error"; }). then(function () { }, function () { }). then(function () { LiveUnit.Assert.areEqual(2, handlerHitCount); }); } finally { WinJS.Promise.onerror = undefined; } } testThrowingUndefined = function () { WinJS.Promise.onerror = function (evt) { var detail = evt.detail; LiveUnit.Assert.isTrue(!detail.exception); LiveUnit.Assert.areEqual("undefined", typeof detail.exception); } try { var p = new WinJS.Promise(function () { throw undefined; }); } finally { WinJS.Promise.onerror = undefined; } } testThrowingNull = function () { WinJS.Promise.onerror = function (evt) { var detail = evt.detail; LiveUnit.Assert.areEqual(null, detail.exception); LiveUnit.Assert.areEqual("object", typeof detail.exception); } try { var p = new WinJS.Promise(function () { throw null; }); } finally { WinJS.Promise.onerror = undefined; } } testThrowingNumber = function () { WinJS.Promise.onerror = function (evt) { var detail = evt.detail; LiveUnit.Assert.areEqual(1, detail.exception); LiveUnit.Assert.areEqual("number", typeof detail.exception); } try { var p = new WinJS.Promise(function () { throw 1; }); } finally { WinJS.Promise.onerror = undefined; } } testThrowingObject = function () { WinJS.Promise.onerror = function (evt) { var detail = evt.detail; var temp = detail.exception; var type = typeof temp; LiveUnit.Assert.areEqual("object", type); LiveUnit.Assert.areEqual(10, temp.x); } try { var p = new WinJS.Promise(function () { throw { x: 10 }; }); } finally { WinJS.Promise.onerror = undefined; } } // Making sure that different IDs are generated for errors produced by different promise trees testDifferentIdsForDifferentPromises = function () { var handlerHitCount = 0; var id = undefined; WinJS.Promise.onerror = function (evt) { var detail = evt.detail; handlerHitCount++; if (!detail.parent) { if (id) LiveUnit.Assert.areNotEqual(id, detail.id); else id = detail.id; } } try { var p1 = new WinJS.Promise(function () { throw "exception inside function"; }). then(function () { }, function () { }). then(function () { }); var p2 = new WinJS.Promise(function () { }). then(function () { LiveUnit.Assert.areEqual(4, handlerHitCount) }); //To make sure that the onerror is called 4 times; } finally { WinJS.Promise.onerror = undefined; } } // Making sure that same object is passed to onerror for an error on the same promise tree testVerifySameObjectInMultipleErrorHandlers = function () { function Equal(evt1, evt2) { for (var i in evt1) { if (typeof evt1[i] === "object") return Equal(evt1[i], evt2[i]); else if (typeof evt1[i] !== "object" && evt1[i] !== evt2[i]) return false; } return true; } function eventHandler1(evt) { detail1 = evt.detail; handlerHitCount++; } function eventHandler2(evt) { detail2 = evt.detail; LiveUnit.Assert.isTrue(Equal(detail1, detail2)); handlerHitCount++; } function eventHandler3(evt) { detail3 = evt.detail; LiveUnit.Assert.isTrue(Equal(detail3, detail2)); handlerHitCount++; } WinJS.Promise.addEventListener("error", eventHandler1); WinJS.Promise.addEventListener("error", eventHandler2); WinJS.Promise.addEventListener("error", eventHandler3); try { var detail1, detail2, detail3; var handlerHitCount = 0, hitCount = 0; var p = new WinJS.Promise(function () { throw "Error initializing"; }); p.then(function () { hitCount++; }, function (e) { }); LiveUnit.Assert.areEqual(0, hitCount); LiveUnit.Assert.areEqual(6, handlerHitCount); } finally { WinJS.Promise.removeEventListener("error", eventHandler1); WinJS.Promise.removeEventListener("error", eventHandler2); WinJS.Promise.removeEventListener("error", eventHandler3); } } //Making sure that error property exists in the parameter and exception does not exist testCorrectnessOfErrors = function () { var errorString = "This is an error"; WinJS.Promise.onerror = function (evt) { var detail = evt.detail; LiveUnit.Assert.isTrue(!detail.exception); LiveUnit.Assert.isTrue(!!detail.error); LiveUnit.Assert.isTrue(!!detail.id); LiveUnit.Assert.areEqual(errorString, detail.error); } try { var p = new WinJS.Promise(function (c, e) { e(errorString); }); } finally { WinJS.Promise.onerror = undefined; } } // Testing parent list and making sure that the parent is falsy only in case of the root // This will still work work the first time because the parent is undefined for the initial error testOnErrorParentsList = function () { var parent = undefined; WinJS.Promise.onerror = function (evt) { var detail = evt.detail; LiveUnit.Assert.areEqual(parent, detail.parent); parent = detail.promise; } try { var p = new WinJS.Promise(function () { throw "exception inside function"; }). then(function () { }). then(function () { }). then(null, function () { }); } finally { WinJS.Promise.onerror = undefined; } } testOnErrorParameterProperties = function () { var exceptionStr = "exception inside function"; WinJS.Promise.onerror = function (evt) { var detail = evt.detail; if (!detail.parent) { LiveUnit.Assert.isTrue(!!detail.exception); LiveUnit.Assert.isTrue(!detail.handler); LiveUnit.Assert.isTrue(!detail.error); LiveUnit.Assert.areEqual(exceptionStr, detail.exception); } } try { var p = new WinJS.Promise(function () { throw exceptionStr; }). then(function () { }, function () { }); } finally { WinJS.Promise.onerror = undefined; } } // Throwing an error in error handler // This will result in throwing a new error with a new id which will result in a new a tree of onerror function call testThrowingAnErrorInErrorHandler = function () { var handlerHitCount = 0, hitCount = 0; var str; function eventHandler(evt) { handlerHitCount++; var detail = evt.detail; str = str || detail.exception; LiveUnit.Assert.areEqual(str, detail.exception); } WinJS.Promise.addEventListener("error", eventHandler); try { var p = new WinJS.Promise(function () { throw "Error initializing"; }); p. then(function () { hitCount++; }, function (e) { throw e; }). then(function () { hitCount++; }, function (e) { throw e; }). then(function () { hitCount++; }, function (e) { throw e; }); LiveUnit.Assert.areEqual(0, hitCount); LiveUnit.Assert.areEqual(4, handlerHitCount); } finally { WinJS.Promise.removeEventListener("error", eventHandler); } } // Testing an error chain testHugeErrorWithChain = function () { var handlerHitCount = 0, hitCount = 0; function eventHandler(evt) { handlerHitCount++; } WinJS.Promise.addEventListener("error", eventHandler); try { var p = new WinJS.Promise(function () { throw "Error initializing"; }); p. then(function () { hitCount++; }). then(function () { hitCount++; }). then(null, function (e) { throw e; }); LiveUnit.Assert.areEqual(0, hitCount); LiveUnit.Assert.areEqual(2, handlerHitCount); } finally { WinJS.Promise.removeEventListener("error", eventHandler); } } // Testing unregistering the onerror inside an error chain by using removeEventListener testUnregisterInHugeChain = function () { var handlerHitCount = 0, hitCount = 0; function eventHandler(evt) { handlerHitCount++; } WinJS.Promise.addEventListener("error", eventHandler); try { var p = new WinJS.Promise(function () { throw "Error initializing"; }); p. then( function () { hitCount++; }, function (e) { throw e; } ). then( function () { hitCount++; }, function (e) { WinJS.Promise.removeEventListener("error", eventHandler); throw e; } ). then( function () { hitCount++; }, function (e) { throw e; } ); LiveUnit.Assert.areEqual(0, hitCount); LiveUnit.Assert.areEqual(3, handlerHitCount); } finally { WinJS.Promise.removeEventListener("error", eventHandler); } } // Testing unregistering the onerror inside an error chain by setting onerror to undefined testSettingOnErrorToUndefinedInHugeChain = function () { var handlerHitCount = 0, hitCount = 0; WinJS.Promise.onerror = function (evt) { handlerHitCount++; } try { var p = new WinJS.Promise(function () { throw "Error initializing"; }); p. then( function () { hitCount++; }, function (e) { throw e; } ). then( function () { hitCount++; }, function (e) { WinJS.Promise.onerror = undefined; throw e; } ). then( function () { hitCount++; }, function (e) { } ); LiveUnit.Assert.areEqual(0, hitCount); LiveUnit.Assert.areEqual(3, handlerHitCount); } finally { WinJS.Promise.onerror = undefined; } } // Testing chaining when the then does not have an error handler so the error or the exception // gets chained to the next then so that it can be handled by an errorHandler testSettingOnErrorToUndefinedInHugeChain2 = function () { var handlerHitCount = 0, hitCount = 0; WinJS.Promise.onerror = function (evt) { handlerHitCount++; } try { var p = new WinJS.Promise(function () { throw "Error initializing"; }); p. then(function () { hitCount++; }). then( function () { hitCount++; }, function (e) { WinJS.Promise.onerror = undefined; throw e; } ). then(function () { hitCount++; }, function (e) { }); LiveUnit.Assert.areEqual(0, hitCount); LiveUnit.Assert.areEqual(2, handlerHitCount); } finally { WinJS.Promise.onerror = undefined; } } testRemovingOnErrorInHugeChain2 = function () { var handlerHitCount = 0, hitCount = 0; function eventHandler(evt) { handlerHitCount++; } WinJS.Promise.addEventListener("error", eventHandler); try { var p = new WinJS.Promise(function () { throw "Error initializing"; }); p. then(function () { hitCount++; }). then( function () { hitCount++; }, function (e) { WinJS.Promise.removeEventListener("error", eventHandler); throw e; } ). then(function () { hitCount++; }, function (e) { }); LiveUnit.Assert.areEqual(0, hitCount); LiveUnit.Assert.areEqual(2, handlerHitCount); } finally { WinJS.Promise.removeEventListener("error", eventHandler); } } // adding multiple listeners to onerror and make sure that they all get called testAddingMultipleListeners = function () { function eventHandler1(evt) { var detail = evt.detail; if (!detail.parent) handlerHitCount++; } function eventHandler2(evt) { var detail = evt.detail; if (!detail.parent) handlerHitCount++; } function eventHandler3(evt) { var detail = evt.detail; if (!detail.parent) handlerHitCount++; } WinJS.Promise.addEventListener("error", eventHandler1); WinJS.Promise.addEventListener("error", eventHandler1); WinJS.Promise.addEventListener("error", eventHandler2); WinJS.Promise.addEventListener("error", eventHandler3); try { var handlerHitCount = 0; var p = new WinJS.Promise(function () { throw "Error initializing"; }); var hitCompleteCount = 0; p. then(function () { hitCompleteCount++; }, function (e) { }); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(3, handlerHitCount); } finally { WinJS.Promise.removeEventListener("error", eventHandler1); WinJS.Promise.removeEventListener("error", eventHandler2); WinJS.Promise.removeEventListener("error", eventHandler3); } } // deleting the last listener of the error and make sure that it won't get called in future errors testDeletingMultipleErrorHandlers = function () { function eventHandler1(evt) { var detail = evt.detail; if (!detail.parent) handlerHitCount++; } function eventHandler2(evt) { var detail = evt.detail; WinJS.Promise.removeEventListener("error", eventHandler3); if (!detail.parent) handlerHitCount++; } function eventHandler3(evt) { var detail = evt.detail; if (!detail.parent) handlerHitCount++; } WinJS.Promise.addEventListener("error", eventHandler1); WinJS.Promise.addEventListener("error", eventHandler2); WinJS.Promise.addEventListener("error", eventHandler3); try { var handlerHitCount = 0; var p = new WinJS.Promise(function () { throw "Error initializing"; }); var hitCompleteCount = 0; p. then(function () { hitCompleteCount++; }, function (e) { }); var p2 = new WinJS.Promise(function () { throw "Error initializing 2"; }); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(5, handlerHitCount); } finally { WinJS.Promise.removeEventListener("error", eventHandler1); WinJS.Promise.removeEventListener("error", eventHandler2); WinJS.Promise.removeEventListener("error", eventHandler3); } } // deleting the listener in the middle of the onerror and make sure that it won't get called in future errors testDeletingMultipleErrorHandlers2 = function () { function eventHandler1(evt) { var detail = evt.detail; WinJS.Promise.removeEventListener("error", eventHandler2); if (!detail.parent) handlerHitCount++; } function eventHandler2(evt) { var detail = evt.detail; if (!detail.parent) handlerHitCount++; } function eventHandler3(evt) { var detail = evt.detail; if (!detail.parent) handlerHitCount++; } WinJS.Promise.addEventListener("error", eventHandler1); WinJS.Promise.addEventListener("error", eventHandler2); WinJS.Promise.addEventListener("error", eventHandler3); try { var handlerHitCount = 0; var p = new WinJS.Promise(function () { throw "Error initializing"; }); var hitCompleteCount = 0; var p2 = new WinJS.Promise(function () { throw "Error initializing2"; }); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(5, handlerHitCount); } finally { WinJS.Promise.removeEventListener("error", eventHandler1); WinJS.Promise.removeEventListener("error", eventHandler2); WinJS.Promise.removeEventListener("error", eventHandler3); } } testAddingFinally = function () { Object.getPrototypeOf(WinJS.Promise.prototype).cleanup = function (func) { return this.then( function (v) { func(); return v; }, function (e) { func(); throw e; } ); }; q.clear(); var hitCompleteCount = 0; var hitFirstFinallyCount = 0; var hitSecondFinallyCount = 0; var hitErrorCount = 0; (<any>asyncAdd(1, 2)). cleanup(function () { hitFirstFinallyCount++; // the return value from cleanup is irrelevant return 5; }). then(function (v) { hitCompleteCount++; LiveUnit.Assert.areEqual(3, v); throw "MyError"; }). cleanup(function () { hitSecondFinallyCount++; }). then(null, function (e) { hitErrorCount++; LiveUnit.Assert.areEqual("MyError", e); }); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitFirstFinallyCount); LiveUnit.Assert.areEqual(1, hitSecondFinallyCount); LiveUnit.Assert.areEqual(1, hitErrorCount); } testAddingAlways = function () { Object.getPrototypeOf(WinJS.Promise.prototype).always = function (func) { return this.then(func, func); }; q.clear(); var hitCompleteCount = 0; (<any>asyncAdd(1, 2)). always(function () { return 5; }). then(function (v) { hitCompleteCount++; LiveUnit.Assert.areEqual(5, v); }); q.drain(); LiveUnit.Assert.areEqual(1, hitCompleteCount); } testDoneSimple = function () { var old = WinJS.Promise['_doneHandler']; try { WinJS.Promise['_doneHandler'] = function (v) { throw v; }; var p: any = new WinJS.Promise(function (c, e) { e(1); }); var hitErrorCount = 0; p = p.then(null, function (e) { LiveUnit.Assert.areEqual(1, e); hitErrorCount++; throw e; }); LiveUnit.Assert.areEqual(1, hitErrorCount); var hitCatchCount = 0; try { p.done(); } catch (ex) { hitCatchCount++; LiveUnit.Assert.areEqual(1, ex); } LiveUnit.Assert.areEqual(1, hitCatchCount); } finally { WinJS.Promise['_doneHandler'] = old; } }; testDoneAsynchronous = function () { var old = WinJS.Promise['_doneHandler']; try { WinJS.Promise['_doneHandler'] = function (v) { throw v; }; q.clear(); var p: any = new WinJS.Promise(function (c, e) { q.schedule(function () { e(1) }); }); var hitErrorCount = 0; p = p.then(null, function (e) { LiveUnit.Assert.areEqual(1, e); hitErrorCount++; throw e; }); LiveUnit.Assert.areEqual(0, hitErrorCount); var hitCatchCount = 0; try { p.done(); } catch (ex) { hitCatchCount++; } LiveUnit.Assert.areEqual(0, hitErrorCount); LiveUnit.Assert.areEqual(0, hitCatchCount); // The exception will be thrown while the queue is draining try { q.drain(); } catch (ex) { hitCatchCount++; LiveUnit.Assert.areEqual(1, hitErrorCount); LiveUnit.Assert.areEqual(1, ex); } LiveUnit.Assert.areEqual(1, hitErrorCount); LiveUnit.Assert.areEqual(1, hitCatchCount); } finally { WinJS.Promise['_doneHandler'] = old; } }; testDoneDoesNotLetCancelEscape = function () { var old = WinJS.Promise['_doneHandler']; try { WinJS.Promise['_doneHandler'] = function (v) { throw v; }; q.clear(); var p: any = new WinJS.Promise(function (c, e) { q.schedule(function () { e(1) }); }); var hitErrorCount = 0; p = p.then(null, function (e) { LiveUnit.Assert.isTrue(e instanceof Error); LiveUnit.Assert.areEqual("Canceled", e.name); hitErrorCount++; throw e; }); LiveUnit.Assert.areEqual(0, hitErrorCount); var hitCatchCount = 0; try { p.done(); } catch (ex) { hitCatchCount++; } LiveUnit.Assert.areEqual(0, hitErrorCount); LiveUnit.Assert.areEqual(0, hitCatchCount); p.cancel(); // The exception will be thrown while the queue is draining try { q.drain(); } catch (ex) { hitCatchCount++; } LiveUnit.Assert.areEqual(1, hitErrorCount); LiveUnit.Assert.areEqual(0, hitCatchCount); } finally { WinJS.Promise['_doneHandler'] = old; } }; testDoneChainedSuccess = function (complete) { // test success case where done() chained to successful promise addAsyncNoQueue(1, 2). then(function (result) { LiveUnit.Assert.areEqual(3, result); return result; }). done(function (result) { LiveUnit.Assert.areEqual(3, result); complete(); }); } testErrorHandledDoneSuccess = function (complete) { // generate error in promise, handle error in then(), verify success in done() addAsyncNoQueue(1, 2, { throwException: 1 }). then(function () { LiveUnit.Assert.fail("expected error from prev promise"); }, function (e) { // handle the error LiveUnit.Assert.areEqual(e, "addAsyncNoQueue throwing requested exception"); }). done(function (result) { // should get here LiveUnit.Assert.areEqual(undefined, result, "expecting result to be undefined after handled error"); complete(); }); } testDoneChainedError = function (complete) { // chain done() to a promise chain that throws an exception not handled by intermediate then() addAsyncNoQueue(1, 2, { throwException: 1 }). then(function (result) { LiveUnit.Assert.fail("1 expecting error, not complete from done()"); return result; }). done(function () { LiveUnit.Assert.fail("2 expecting error, not complete from done()"); complete(); }, function (e) { LiveUnit.Assert.areEqual(e, "addAsyncNoQueue throwing requested exception"); complete(); } ); } testDoneAsErrorHandler = function (complete) { // use done() as an error handler addAsyncNoQueue(1, 2, { throwException: 1 }). done(function () { LiveUnit.Assert.fail("expected error, not complete from done()"); complete(); }, function (e) { LiveUnit.Assert.areEqual(e, "addAsyncNoQueue throwing requested exception"); complete(); } ); } testDoneUnhandledError = function (complete) { var old = WinJS.Promise['_doneHandler']; try { WinJS.Promise['_doneHandler'] = function (v) { throw v; }; // done() without error handler, expect throw() and onerror() var hitCount = 0; var catchHit = 0; WinJS.Promise.onerror = function (evt) { LiveUnit.Assert.isTrue(!!evt.detail.error); // verify error msg hitCount++; }; try { addAsyncNoQueue(1, 2, { throwException: 1 }). done(function () { LiveUnit.Assert.fail("expected error, not complete from done()"); complete(); }); } catch (ex) { LiveUnit.Assert.areEqual(ex, "addAsyncNoQueue throwing requested exception"); catchHit++; } finally { LiveUnit.Assert.areEqual(1, hitCount); // verify onerror was called LiveUnit.Assert.areEqual(1, catchHit); // verify catch was called // reset the onerror handler WinJS.Promise.onerror = undefined; complete(); } } finally { WinJS.Promise['_doneHandler'] = old; } } testDoneUnhandledError2 = function (complete) { var old = WinJS.Promise['_doneHandler']; try { WinJS.Promise['_doneHandler'] = function (v) { throw v; }; // empty done() without error handler, expect throw() and onerror() var hitCount = 0; var catchHit = 0; WinJS.Promise.onerror = function (evt) { LiveUnit.Assert.isTrue(!!evt.detail.error); // verify error msg hitCount++; }; try { addAsyncNoQueue(1, 2, { throwException: 1 }). done(); } catch (ex) { LiveUnit.Assert.areEqual(ex, "addAsyncNoQueue throwing requested exception"); catchHit++; } finally { LiveUnit.Assert.areEqual(1, hitCount); // verify onerror was called LiveUnit.Assert.areEqual(1, catchHit); // verify catch was called // reset the onerror handler WinJS.Promise.onerror = undefined; complete(); } } finally { WinJS.Promise['_doneHandler'] = old; } } testDoneCanceled = function (complete) { // validate canceled promise goes through done() error function var cancelCount = 0; var token; // create promise with a cancel handler. // This promise waits 500ms before completing to give time to cancel var x = new WinJS.Promise( function (c) { token = setTimeout(function () { cancelCount = -1; c(); }, 5); }, function () { clearTimeout(token); ++cancelCount; }); // call the promise x. then(function () { LiveUnit.Assert.fail("1 expected error from canceled promise"); }). done( function () { LiveUnit.Assert.fail("2 expected error from canceled promise"); complete(); }, function (e) { if (e.description) { LiveUnit.Assert.areEqual(e.description, "Canceled", "expected e.description == 'Canceled'"); } LiveUnit.Assert.areEqual(e.message, "Canceled", "expected e.message == 'Canceled'"); LiveUnit.Assert.areEqual(e.name, "Canceled", "expected e.name == 'Canceled'"); LiveUnit.Assert.areEqual(1, cancelCount, "expected cancel count == 1 in done()"); complete(); }); // since the promise is async and waiting 500ms in this case, we have time to cancel it x.cancel(); } testDoneProgress = function (complete) { // validate progress calls get to done() var expectedCount = 50; var progressCount = 0; // Create a promise which counts to 50, notifying done() of progress // We need to delay via setTimeout so we can hook up the done() statement to // monitor the progress calls. var x = new WinJS.Promise(function (c, e, p) { setTimeout(function () { for (var count = 0; count < expectedCount; count++) { p(count); }; c(1); }, 5); }); x.done( function (c) { LiveUnit.Assert.areEqual(1, c, "expected return value from complete == 1 from done()"); LiveUnit.Assert.areEqual(50, progressCount, "expected progressCount == 50 from done()"); complete(); }, function (e) { LiveUnit.Assert.fail("not expecting error in done(), got=" + e); complete(); }, function (p) { LiveUnit.Assert.areEqual(p, progressCount, "expected p == progressCount"); progressCount++; }); } testEmptyJoin = function (complete) { WinJS.Promise.join([]). then(null, errorHandler). then(complete); }; testEmptyAny = function (complete) { WinJS.Promise.any([]). then(null, errorHandler). then(complete); }; testStaticCanceledPromise = function (complete) { var hitCount = 0; WinJS.Promise.as() .then(function () { return WinJS.Promise.cancel; }) .then(null, function (error) { hitCount++; LiveUnit.Assert.areEqual("Canceled", error.name); LiveUnit.Assert.areEqual("Canceled", error.message); }) .then(null, errorHandler) .then(function () { LiveUnit.Assert.areEqual(1, hitCount); }) .then(null, errorHandler) .then(complete); }; testSignal = function (complete) { var hitComplete = 0; var hitError = 0; var hitProgress = 0; var s = new WinJS._Signal(); s.promise .then( function (value) { hitComplete++; LiveUnit.Assert.areEqual("complete value", value); }, function (error) { hitError++; }, function (progress) { hitProgress++; LiveUnit.Assert.areEqual(hitProgress, progress); } ) .then(null, errorHandler) .then(function () { LiveUnit.Assert.areEqual(1, hitComplete); LiveUnit.Assert.areEqual(0, hitError); LiveUnit.Assert.areEqual(2, hitProgress); }) .then(null, errorHandler) .then(complete); s.progress(1); s.progress(2); s.complete("complete value"); // shouldn't hit handlers for any of these s.progress(27); s.complete("other complete value"); s.error("an error?"); }; testSignalError = function (complete) { var hitComplete = 0; var hitError = 0; var hitProgress = 0; var s = new WinJS._Signal(); s.promise .then( function (value) { hitComplete++; }, function (error) { hitError++; LiveUnit.Assert.areEqual("error value", error); }, function (progress) { hitProgress++; LiveUnit.Assert.areEqual(hitProgress, progress); } ) .then(null, errorHandler) .then(function () { LiveUnit.Assert.areEqual(0, hitComplete); LiveUnit.Assert.areEqual(1, hitError); LiveUnit.Assert.areEqual(2, hitProgress); }) .then(null, errorHandler) .then(complete); s.progress(1); s.progress(2); s.error("error value"); // shouldn't hit handlers for any of these s.progress(27); s.complete("complete value"); s.error("another error?"); }; testNestedCancelationRecovery = function (complete) { var hitUnexpected = 0; var hitP1Complete = 0; var hitP2Complete = 0; var hitP3Complete = 0; function neverCompletes() { return new WinJS.Promise(function () { }); } var p1 = neverCompletes().then( function () { hitUnexpected++; }, function (e) { if (e instanceof Error && e.name === "Canceled") { return p2; } hitUnexpected++; } ); p1.then( function (v) { hitP1Complete++; }, function () { hitUnexpected++; } ); var p2 = neverCompletes().then( function () { hitUnexpected++; }, function (e) { if (e instanceof Error && e.name === "Canceled") { return p3; } hitUnexpected++; } ); p2.then( function (v) { hitP2Complete++; }, function () { hitUnexpected++; } ); p1.cancel(); var p3 = WinJS.Promise.timeout().then(function () { LiveUnit.Assert.areEqual(0, hitUnexpected); LiveUnit.Assert.areEqual(0, hitP1Complete); LiveUnit.Assert.areEqual(0, hitP2Complete); hitP3Complete++; return 1; }).then(function (v) { hitP3Complete++; return v; }); p2.cancel(); WinJS.Promise.timeout().then(function () { LiveUnit.Assert.areEqual(0, hitUnexpected); LiveUnit.Assert.areEqual(1, hitP1Complete); LiveUnit.Assert.areEqual(1, hitP2Complete); LiveUnit.Assert.areEqual(2, hitP3Complete); }) .then(null, errorHandler) .then(complete); }; testJoiningCanceledPromisesCancels = function () { var hitCompleteCount = 0, hitErrorCount = 0; var p1 = new WinJS.Promise(function () { }); var p2 = new WinJS.Promise(function () { }); var p3 = new WinJS.Promise(function () { }); var p = WinJS.Promise.join([p1, p2, p3]); p.then( function (v) { hitCompleteCount++; }, function (e) { hitErrorCount++; LiveUnit.Assert.isTrue(e instanceof Error); LiveUnit.Assert.areEqual("Canceled", e.name); } ); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); p1.cancel(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); p2.cancel(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); p3.cancel(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); }; testJoinSomeCanceledAndOtherFailedPromisesFails = function () { var hitCompleteCount = 0, hitErrorCount = 0; var p1 = new WinJS.Promise(function () { }); var p2 = new WinJS.Promise(function () { }); var p3e; var p3 = new WinJS.Promise(function (c, e) { p3e = e; }); var p = WinJS.Promise.join([p1, p2, p3]); p.then( function (v) { hitCompleteCount++; }, function (e) { hitErrorCount++; LiveUnit.Assert.isFalse(e instanceof Error); } ); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); p1.cancel(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); p2.cancel(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); p3e(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); }; testJoinSomeCanceledAndOtherCompletedPromisesCancels = function () { var hitCompleteCount = 0, hitErrorCount = 0; var p1 = new WinJS.Promise(function () { }); var p2 = new WinJS.Promise(function () { }); var p3c; var p3 = new WinJS.Promise(function (c) { p3c = c; }); var p = WinJS.Promise.join([p1, p2, p3]); p.then( function (v) { hitCompleteCount++; }, function (e) { hitErrorCount++; LiveUnit.Assert.isTrue(e instanceof Error); LiveUnit.Assert.areEqual("Canceled", e.name); } ); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); p1.cancel(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); p2.cancel(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); p3c(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); }; testAnyCanceledPromisesCancels = function () { var hitCompleteCount = 0, hitErrorCount = 0; var p1 = new WinJS.Promise(function () { }); var p2 = new WinJS.Promise(function () { }); var p3 = new WinJS.Promise(function () { }); var p = WinJS.Promise.any([p1, p2, p3]); p.then( function (v) { hitCompleteCount++; }, function (e) { hitErrorCount++; LiveUnit.Assert.isTrue(e instanceof Error); LiveUnit.Assert.areEqual("Canceled", e.name); } ); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); p1.cancel(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); p2.cancel(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); p3.cancel(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(1, hitErrorCount); }; testAnySomeCanceledPromisesStillSucceeds = function () { var hitCompleteCount = 0, hitErrorCount = 0; var p1 = new WinJS.Promise(function () { }); var p2 = new WinJS.Promise(function () { }); var p3c; var p3 = new WinJS.Promise(function (c) { p3c = c; }); var p = WinJS.Promise.any([p1, p2, p3]); p.then( function (v) { hitCompleteCount++; }, function (e) { hitErrorCount++; } ); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); p1.cancel(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); p2.cancel(); LiveUnit.Assert.areEqual(0, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); p3c(); LiveUnit.Assert.areEqual(1, hitCompleteCount); LiveUnit.Assert.areEqual(0, hitErrorCount); }; testCancelingPromiseWhichErrorCorrectsTheCancel = function () { var hitCount = 0; var complete; var p = new WinJS.Promise( function (c) { complete = c; }, function () { complete(1); } ); p.cancel(); p.then(function (v) { hitCount++; LiveUnit.Assert.areEqual(1, v); }); LiveUnit.Assert.areEqual(1, hitCount); }; testFIFODelivery = function () { var c; var p = new WinJS.Promise(function (complete) { c = complete; }); var count = 0; var p1 = p.then(function () { LiveUnit.Assert.areEqual(0, count); count++; }); p1.then(function () { LiveUnit.Assert.areEqual(3, count); count++; }); p1.then(function () { LiveUnit.Assert.areEqual(4, count); count++; }); var p2 = p.then(function () { LiveUnit.Assert.areEqual(1, count); count++; }); p1.then(function () { LiveUnit.Assert.areEqual(5, count); count++; }); p1.then(function () { LiveUnit.Assert.areEqual(6, count); count++; }); var p3 = p.then(function () { LiveUnit.Assert.areEqual(2, count); count++; }); p1.then(function () { LiveUnit.Assert.areEqual(7, count); count++; }); p1.then(function () { LiveUnit.Assert.areEqual(8, count); count++; }); c(); }; testRecursivelyChainingPromises = function (complete) { q.clear(); var count = 3000; var i = 0; function run() { if (i < count) { console.log("Execution #" + i, i); i++; return new WinJS.Promise(function (c) { q.schedule(function () { c(); }); }).then(run); } } run() .then(function () { LiveUnit.Assert.areEqual(count, i); }) .then(null, function () { LiveUnit.Assert.fail("should not get here"); }) .then(null, function () { ; }) .then(complete); q.drain(); }; }; } LiveUnit.registerTestClass("CorsicaTests.Promise");
the_stack
namespace DotVVM.Samples.Common.Api.AspNetCore { class ClientBase { public transformOptions(options: RequestInit) { options.credentials = "same-origin"; return Promise.resolve(options); } } /* tslint:disable */ /* eslint-disable */ //---------------------- // <auto-generated> // Generated using the NSwag toolchain v13.13.2.0 (NJsonSchema v10.5.2.0 (Newtonsoft.Json v10.0.0.0)) (http://NSwag.org) // </auto-generated> //---------------------- // ReSharper disable InconsistentNaming export class TestWebApiClientAspNetCore extends ClientBase { private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }; private baseUrl: string; protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined; constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) { super(); this.http = http ? http : <any>window; this.baseUrl = baseUrl !== undefined && baseUrl !== null ? baseUrl : "http://localhost:5001"; } /** * @param category (optional) * @return Success */ bindingSharingGetGet(category?: number | null | undefined): Promise<BindingSharingItemDTO[]> { let url_ = this.baseUrl + "/api/BindingSharing/get?"; if (category !== undefined && category !== null) url_ += "category=" + encodeURIComponent("" + category) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ = <RequestInit>{ method: "GET", headers: { "Accept": "application/json" } }; return this.transformOptions(options_).then(transformedOptions_ => { return this.http.fetch(url_, transformedOptions_); }).then((_response: Response) => { return this.processBindingSharingGetGet(_response); }); } protected processBindingSharingGetGet(response: Response): Promise<BindingSharingItemDTO[]> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 200) { return response.text().then((_responseText) => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); if (Array.isArray(resultData200)) { result200 = [] as any; for (let item of resultData200) result200!.push(BindingSharingItemDTO.fromJS(item)); } else { result200 = <any>null; } return result200; }); } else if (status !== 200 && status !== 204) { return response.text().then((_responseText) => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); }); } return Promise.resolve<BindingSharingItemDTO[]>(<any>null); } /** * @return Success */ bindingSharingGetGetWithRouteParam(category: number): Promise<BindingSharingItemDTO[]> { let url_ = this.baseUrl + "/api/BindingSharing/getWithRouteParam/{category}"; if (category === undefined || category === null) throw new Error("The parameter 'category' must be defined."); url_ = url_.replace("{category}", encodeURIComponent("" + category)); url_ = url_.replace(/[?&]$/, ""); let options_ = <RequestInit>{ method: "GET", headers: { "Accept": "application/json" } }; return this.transformOptions(options_).then(transformedOptions_ => { return this.http.fetch(url_, transformedOptions_); }).then((_response: Response) => { return this.processBindingSharingGetGetWithRouteParam(_response); }); } protected processBindingSharingGetGetWithRouteParam(response: Response): Promise<BindingSharingItemDTO[]> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 200) { return response.text().then((_responseText) => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); if (Array.isArray(resultData200)) { result200 = [] as any; for (let item of resultData200) result200!.push(BindingSharingItemDTO.fromJS(item)); } else { result200 = <any>null; } return result200; }); } else if (status !== 200 && status !== 204) { return response.text().then((_responseText) => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); }); } return Promise.resolve<BindingSharingItemDTO[]>(<any>null); } /** * @param category (optional) * @return Success */ bindingSharingPostPost(category?: number | null | undefined): Promise<BindingSharingItemDTO[]> { let url_ = this.baseUrl + "/api/BindingSharing/post?"; if (category !== undefined && category !== null) url_ += "category=" + encodeURIComponent("" + category) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ = <RequestInit>{ method: "POST", headers: { "Accept": "application/json" } }; return this.transformOptions(options_).then(transformedOptions_ => { return this.http.fetch(url_, transformedOptions_); }).then((_response: Response) => { return this.processBindingSharingPostPost(_response); }); } protected processBindingSharingPostPost(response: Response): Promise<BindingSharingItemDTO[]> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 200) { return response.text().then((_responseText) => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); if (Array.isArray(resultData200)) { result200 = [] as any; for (let item of resultData200) result200!.push(BindingSharingItemDTO.fromJS(item)); } else { result200 = <any>null; } return result200; }); } else if (status !== 200 && status !== 204) { return response.text().then((_responseText) => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); }); } return Promise.resolve<BindingSharingItemDTO[]>(<any>null); } /** * @return Success */ getCompanies(): Promise<CompanyOfString[]> { let url_ = this.baseUrl + "/api/Companies"; url_ = url_.replace(/[?&]$/, ""); let options_ = <RequestInit>{ method: "GET", headers: { "Accept": "application/json" } }; return this.transformOptions(options_).then(transformedOptions_ => { return this.http.fetch(url_, transformedOptions_); }).then((_response: Response) => { return this.processGetCompanies(_response); }); } protected processGetCompanies(response: Response): Promise<CompanyOfString[]> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 200) { return response.text().then((_responseText) => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); if (Array.isArray(resultData200)) { result200 = [] as any; for (let item of resultData200) result200!.push(CompanyOfString.fromJS(item)); } else { result200 = <any>null; } return result200; }); } else if (status !== 200 && status !== 204) { return response.text().then((_responseText) => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); }); } return Promise.resolve<CompanyOfString[]>(<any>null); } /** * @param sortingOptions (optional) * @param sortingOptions_SortDescending (optional) * @param sortingOptions_SortExpression (optional) * @return Success */ companiesGetSorted(sortingOptions?: any | null | undefined, sortingOptions_SortDescending?: boolean | null | undefined, sortingOptions_SortExpression?: string | null | undefined): Promise<GridViewDataSetOfCompanyOfBoolean> { let url_ = this.baseUrl + "/api/Companies/sorted?"; if (sortingOptions !== undefined && sortingOptions !== null) url_ += "sortingOptions=" + encodeURIComponent("" + sortingOptions) + "&"; if (sortingOptions_SortDescending !== undefined && sortingOptions_SortDescending !== null) url_ += "sortingOptions.SortDescending=" + encodeURIComponent("" + sortingOptions_SortDescending) + "&"; if (sortingOptions_SortExpression !== undefined && sortingOptions_SortExpression !== null) url_ += "sortingOptions.SortExpression=" + encodeURIComponent("" + sortingOptions_SortExpression) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ = <RequestInit>{ method: "GET", headers: { "Accept": "application/json" } }; return this.transformOptions(options_).then(transformedOptions_ => { return this.http.fetch(url_, transformedOptions_); }).then((_response: Response) => { return this.processCompaniesGetSorted(_response); }); } protected processCompaniesGetSorted(response: Response): Promise<GridViewDataSetOfCompanyOfBoolean> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 200) { return response.text().then((_responseText) => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = GridViewDataSetOfCompanyOfBoolean.fromJS(resultData200); return result200; }); } else if (status !== 200 && status !== 204) { return response.text().then((_responseText) => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); }); } return Promise.resolve<GridViewDataSetOfCompanyOfBoolean>(<any>null); } /** * @param pagingOptions (optional) * @param pagingOptions_PageIndex (optional) * @param pagingOptions_PageSize (optional) * @param pagingOptions_TotalItemsCount (optional) * @return Success */ companiesGetPaged(pagingOptions?: any | null | undefined, pagingOptions_PageIndex?: number | null | undefined, pagingOptions_PageSize?: number | null | undefined, pagingOptions_TotalItemsCount?: number | null | undefined): Promise<GridViewDataSetOfCompanyOfString> { let url_ = this.baseUrl + "/api/Companies/paged?"; if (pagingOptions !== undefined && pagingOptions !== null) url_ += "pagingOptions=" + encodeURIComponent("" + pagingOptions) + "&"; if (pagingOptions_PageIndex !== undefined && pagingOptions_PageIndex !== null) url_ += "pagingOptions.PageIndex=" + encodeURIComponent("" + pagingOptions_PageIndex) + "&"; if (pagingOptions_PageSize !== undefined && pagingOptions_PageSize !== null) url_ += "pagingOptions.PageSize=" + encodeURIComponent("" + pagingOptions_PageSize) + "&"; if (pagingOptions_TotalItemsCount !== undefined && pagingOptions_TotalItemsCount !== null) url_ += "pagingOptions.TotalItemsCount=" + encodeURIComponent("" + pagingOptions_TotalItemsCount) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ = <RequestInit>{ method: "GET", headers: { "Accept": "application/json" } }; return this.transformOptions(options_).then(transformedOptions_ => { return this.http.fetch(url_, transformedOptions_); }).then((_response: Response) => { return this.processCompaniesGetPaged(_response); }); } protected processCompaniesGetPaged(response: Response): Promise<GridViewDataSetOfCompanyOfString> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 200) { return response.text().then((_responseText) => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = GridViewDataSetOfCompanyOfString.fromJS(resultData200); return result200; }); } else if (status !== 200 && status !== 204) { return response.text().then((_responseText) => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); }); } return Promise.resolve<GridViewDataSetOfCompanyOfString>(<any>null); } /** * @param sortingOptions (optional) * @param sortingOptions_SortDescending (optional) * @param sortingOptions_SortExpression (optional) * @param pagingOptions (optional) * @param pagingOptions_PageIndex (optional) * @param pagingOptions_PageSize (optional) * @param pagingOptions_TotalItemsCount (optional) * @return Success */ companiesGetSortedandpaged(sortingOptions?: any | null | undefined, sortingOptions_SortDescending?: boolean | null | undefined, sortingOptions_SortExpression?: string | null | undefined, pagingOptions?: any | null | undefined, pagingOptions_PageIndex?: number | null | undefined, pagingOptions_PageSize?: number | null | undefined, pagingOptions_TotalItemsCount?: number | null | undefined): Promise<GridViewDataSetOfCompanyOfString> { let url_ = this.baseUrl + "/api/Companies/sortedandpaged?"; if (sortingOptions !== undefined && sortingOptions !== null) url_ += "sortingOptions=" + encodeURIComponent("" + sortingOptions) + "&"; if (sortingOptions_SortDescending !== undefined && sortingOptions_SortDescending !== null) url_ += "sortingOptions.SortDescending=" + encodeURIComponent("" + sortingOptions_SortDescending) + "&"; if (sortingOptions_SortExpression !== undefined && sortingOptions_SortExpression !== null) url_ += "sortingOptions.SortExpression=" + encodeURIComponent("" + sortingOptions_SortExpression) + "&"; if (pagingOptions !== undefined && pagingOptions !== null) url_ += "pagingOptions=" + encodeURIComponent("" + pagingOptions) + "&"; if (pagingOptions_PageIndex !== undefined && pagingOptions_PageIndex !== null) url_ += "pagingOptions.PageIndex=" + encodeURIComponent("" + pagingOptions_PageIndex) + "&"; if (pagingOptions_PageSize !== undefined && pagingOptions_PageSize !== null) url_ += "pagingOptions.PageSize=" + encodeURIComponent("" + pagingOptions_PageSize) + "&"; if (pagingOptions_TotalItemsCount !== undefined && pagingOptions_TotalItemsCount !== null) url_ += "pagingOptions.TotalItemsCount=" + encodeURIComponent("" + pagingOptions_TotalItemsCount) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ = <RequestInit>{ method: "GET", headers: { "Accept": "application/json" } }; return this.transformOptions(options_).then(transformedOptions_ => { return this.http.fetch(url_, transformedOptions_); }).then((_response: Response) => { return this.processCompaniesGetSortedandpaged(_response); }); } protected processCompaniesGetSortedandpaged(response: Response): Promise<GridViewDataSetOfCompanyOfString> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 200) { return response.text().then((_responseText) => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = GridViewDataSetOfCompanyOfString.fromJS(resultData200); return result200; }); } else if (status !== 200 && status !== 204) { return response.text().then((_responseText) => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); }); } return Promise.resolve<GridViewDataSetOfCompanyOfString>(<any>null); } /** * @param companyId (optional) * @param pageIndex (optional) * @param pageSize (optional) * @return Success */ getOrdersAll(companyId?: number | null | undefined, pageIndex?: number | null | undefined, pageSize?: number | null | undefined): Promise<Order[]> { let url_ = this.baseUrl + "/api/Orders?"; if (companyId !== undefined && companyId !== null) url_ += "companyId=" + encodeURIComponent("" + companyId) + "&"; if (pageIndex !== undefined && pageIndex !== null) url_ += "pageIndex=" + encodeURIComponent("" + pageIndex) + "&"; if (pageSize !== undefined && pageSize !== null) url_ += "pageSize=" + encodeURIComponent("" + pageSize) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ = <RequestInit>{ method: "GET", headers: { "Accept": "application/json" } }; return this.transformOptions(options_).then(transformedOptions_ => { return this.http.fetch(url_, transformedOptions_); }).then((_response: Response) => { return this.processGetOrdersAll(_response); }); } protected processGetOrdersAll(response: Response): Promise<Order[]> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 200) { return response.text().then((_responseText) => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); if (Array.isArray(resultData200)) { result200 = [] as any; for (let item of resultData200) result200!.push(Order.fromJS(item)); } else { result200 = <any>null; } return result200; }); } else if (status !== 200 && status !== 204) { return response.text().then((_responseText) => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); }); } return Promise.resolve<Order[]>(<any>null); } /** * @param body (optional) * @return Success */ postOrders(body?: Order | null | undefined): Promise<void> { let url_ = this.baseUrl + "/api/Orders"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ = <RequestInit>{ body: content_, method: "POST", headers: { "Content-Type": "application/json", } }; return this.transformOptions(options_).then(transformedOptions_ => { return this.http.fetch(url_, transformedOptions_); }).then((_response: Response) => { return this.processPostOrders(_response); }); } protected processPostOrders(response: Response): Promise<void> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 200) { return response.text().then((_responseText) => { return; }); } else if (status !== 200 && status !== 204) { return response.text().then((_responseText) => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); }); } return Promise.resolve<void>(<any>null); } /** * @return Success */ getOrders(orderId: number): Promise<Order> { let url_ = this.baseUrl + "/api/Orders/{orderId}"; if (orderId === undefined || orderId === null) throw new Error("The parameter 'orderId' must be defined."); url_ = url_.replace("{orderId}", encodeURIComponent("" + orderId)); url_ = url_.replace(/[?&]$/, ""); let options_ = <RequestInit>{ method: "GET", headers: { "Accept": "application/json" } }; return this.transformOptions(options_).then(transformedOptions_ => { return this.http.fetch(url_, transformedOptions_); }).then((_response: Response) => { return this.processGetOrders(_response); }); } protected processGetOrders(response: Response): Promise<Order> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 200) { return response.text().then((_responseText) => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = Order.fromJS(resultData200); return result200; }); } else if (status !== 200 && status !== 204) { return response.text().then((_responseText) => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); }); } return Promise.resolve<Order>(<any>null); } /** * @param body (optional) * @return Success */ putOrders(orderId: number, body?: Order | null | undefined): Promise<void> { let url_ = this.baseUrl + "/api/Orders/{orderId}"; if (orderId === undefined || orderId === null) throw new Error("The parameter 'orderId' must be defined."); url_ = url_.replace("{orderId}", encodeURIComponent("" + orderId)); url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ = <RequestInit>{ body: content_, method: "PUT", headers: { "Content-Type": "application/json", } }; return this.transformOptions(options_).then(transformedOptions_ => { return this.http.fetch(url_, transformedOptions_); }).then((_response: Response) => { return this.processPutOrders(_response); }); } protected processPutOrders(response: Response): Promise<void> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 200) { return response.text().then((_responseText) => { return; }); } else if (status !== 200 && status !== 204) { return response.text().then((_responseText) => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); }); } return Promise.resolve<void>(<any>null); } /** * @return Success */ ordersDeleteDelete(orderId: number): Promise<void> { let url_ = this.baseUrl + "/api/Orders/delete/{orderId}"; if (orderId === undefined || orderId === null) throw new Error("The parameter 'orderId' must be defined."); url_ = url_.replace("{orderId}", encodeURIComponent("" + orderId)); url_ = url_.replace(/[?&]$/, ""); let options_ = <RequestInit>{ method: "DELETE", headers: { } }; return this.transformOptions(options_).then(transformedOptions_ => { return this.http.fetch(url_, transformedOptions_); }).then((_response: Response) => { return this.processOrdersDeleteDelete(_response); }); } protected processOrdersDeleteDelete(response: Response): Promise<void> { const status = response.status; let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); }; if (status === 200) { return response.text().then((_responseText) => { return; }); } else if (status !== 200 && status !== 204) { return response.text().then((_responseText) => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); }); } return Promise.resolve<void>(<any>null); } } export class BindingSharingItemDTO implements IBindingSharingItemDTO { id!: number; name?: string | null; constructor(data?: IBindingSharingItemDTO) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(_data?: any) { if (_data) { this.id = _data["id"] !== undefined ? _data["id"] : <any>null; this.name = _data["name"] !== undefined ? _data["name"] : <any>null; } } static fromJS(data: any): BindingSharingItemDTO { data = typeof data === 'object' ? data : {}; let result = new BindingSharingItemDTO(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["id"] = this.id !== undefined ? this.id : <any>null; data["name"] = this.name !== undefined ? this.name : <any>null; return data; } } export interface IBindingSharingItemDTO { id: number; name?: string | null; } export class CompanyOfBoolean implements ICompanyOfBoolean { id?: number | null; name?: string | null; owner?: string | null; department?: boolean | null; constructor(data?: ICompanyOfBoolean) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(_data?: any) { if (_data) { this.id = _data["id"] !== undefined ? _data["id"] : <any>null; this.name = _data["name"] !== undefined ? _data["name"] : <any>null; this.owner = _data["owner"] !== undefined ? _data["owner"] : <any>null; this.department = _data["department"] !== undefined ? _data["department"] : <any>null; } } static fromJS(data: any): CompanyOfBoolean { data = typeof data === 'object' ? data : {}; let result = new CompanyOfBoolean(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["id"] = this.id !== undefined ? this.id : <any>null; data["name"] = this.name !== undefined ? this.name : <any>null; data["owner"] = this.owner !== undefined ? this.owner : <any>null; data["department"] = this.department !== undefined ? this.department : <any>null; return data; } } export interface ICompanyOfBoolean { id?: number | null; name?: string | null; owner?: string | null; department?: boolean | null; } export class CompanyOfString implements ICompanyOfString { Id?: number | null; Name?: string | null; Owner?: string | null; Department?: string | null; constructor(data?: ICompanyOfString) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(_data?: any) { if (_data) { this.Id = _data["id"] !== undefined ? _data["id"] : <any>null; this.Name = _data["name"] !== undefined ? _data["name"] : <any>null; this.Owner = _data["owner"] !== undefined ? _data["owner"] : <any>null; this.Department = _data["department"] !== undefined ? _data["department"] : <any>null; } } static fromJS(data: any): CompanyOfString { data = typeof data === 'object' ? data : {}; let result = new CompanyOfString(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["id"] = this.Id !== undefined ? this.Id : <any>null; data["name"] = this.Name !== undefined ? this.Name : <any>null; data["owner"] = this.Owner !== undefined ? this.Owner : <any>null; data["department"] = this.Department !== undefined ? this.Department : <any>null; return data; } } export interface ICompanyOfString { Id?: number | null; Name?: string | null; Owner?: string | null; Department?: string | null; } export class GridViewDataSetOfCompanyOfBoolean implements IGridViewDataSetOfCompanyOfBoolean { IsRefreshRequired?: boolean | null; Items?: CompanyOfBoolean[] | null; pagingOptions?: IPagingOptions | null; rowEditOptions?: IRowEditOptions | null; sortingOptions?: ISortingOptions | null; constructor(data?: IGridViewDataSetOfCompanyOfBoolean) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(_data?: any) { if (_data) { this.IsRefreshRequired = _data["isRefreshRequired"] !== undefined ? _data["isRefreshRequired"] : <any>null; if (Array.isArray(_data["items"])) { this.Items = [] as any; for (let item of _data["items"]) this.Items!.push(CompanyOfBoolean.fromJS(item)); } else { this.Items = <any>null; } this.pagingOptions = _data["pagingOptions"] ? IPagingOptions.fromJS(_data["pagingOptions"]) : <any>null; this.rowEditOptions = _data["rowEditOptions"] ? IRowEditOptions.fromJS(_data["rowEditOptions"]) : <any>null; this.sortingOptions = _data["sortingOptions"] ? ISortingOptions.fromJS(_data["sortingOptions"]) : <any>null; } } static fromJS(data: any): GridViewDataSetOfCompanyOfBoolean { data = typeof data === 'object' ? data : {}; let result = new GridViewDataSetOfCompanyOfBoolean(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["isRefreshRequired"] = this.IsRefreshRequired !== undefined ? this.IsRefreshRequired : <any>null; if (Array.isArray(this.Items)) { data["items"] = []; for (let item of this.Items) data["items"].push(item.toJSON()); } data["pagingOptions"] = this.pagingOptions ? this.pagingOptions.toJSON() : <any>null; data["rowEditOptions"] = this.rowEditOptions ? this.rowEditOptions.toJSON() : <any>null; data["sortingOptions"] = this.sortingOptions ? this.sortingOptions.toJSON() : <any>null; return data; } } export interface IGridViewDataSetOfCompanyOfBoolean { IsRefreshRequired?: boolean | null; Items?: CompanyOfBoolean[] | null; pagingOptions?: IPagingOptions | null; rowEditOptions?: IRowEditOptions | null; sortingOptions?: ISortingOptions | null; } export class GridViewDataSetOfCompanyOfString implements IGridViewDataSetOfCompanyOfString { IsRefreshRequired?: boolean | null; Items?: CompanyOfString[] | null; pagingOptions?: IPagingOptions | null; rowEditOptions?: IRowEditOptions | null; sortingOptions?: ISortingOptions | null; constructor(data?: IGridViewDataSetOfCompanyOfString) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(_data?: any) { if (_data) { this.IsRefreshRequired = _data["isRefreshRequired"] !== undefined ? _data["isRefreshRequired"] : <any>null; if (Array.isArray(_data["items"])) { this.Items = [] as any; for (let item of _data["items"]) this.Items!.push(CompanyOfString.fromJS(item)); } else { this.Items = <any>null; } this.pagingOptions = _data["pagingOptions"] ? IPagingOptions.fromJS(_data["pagingOptions"]) : <any>null; this.rowEditOptions = _data["rowEditOptions"] ? IRowEditOptions.fromJS(_data["rowEditOptions"]) : <any>null; this.sortingOptions = _data["sortingOptions"] ? ISortingOptions.fromJS(_data["sortingOptions"]) : <any>null; } } static fromJS(data: any): GridViewDataSetOfCompanyOfString { data = typeof data === 'object' ? data : {}; let result = new GridViewDataSetOfCompanyOfString(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["isRefreshRequired"] = this.IsRefreshRequired !== undefined ? this.IsRefreshRequired : <any>null; if (Array.isArray(this.Items)) { data["items"] = []; for (let item of this.Items) data["items"].push(item.toJSON()); } data["pagingOptions"] = this.pagingOptions ? this.pagingOptions.toJSON() : <any>null; data["rowEditOptions"] = this.rowEditOptions ? this.rowEditOptions.toJSON() : <any>null; data["sortingOptions"] = this.sortingOptions ? this.sortingOptions.toJSON() : <any>null; return data; } } export interface IGridViewDataSetOfCompanyOfString { IsRefreshRequired?: boolean | null; Items?: CompanyOfString[] | null; pagingOptions?: IPagingOptions | null; rowEditOptions?: IRowEditOptions | null; sortingOptions?: ISortingOptions | null; } export class INearPageIndexesProvider implements IINearPageIndexesProvider { constructor(data?: IINearPageIndexesProvider) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(_data?: any) { } static fromJS(data: any): INearPageIndexesProvider { data = typeof data === 'object' ? data : {}; let result = new INearPageIndexesProvider(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; return data; } } export interface IINearPageIndexesProvider { } export class IPagingOptions implements IIPagingOptions { PageIndex?: number | null; PageSize?: number | null; TotalItemsCount?: number | null; readonly IsFirstPage?: boolean | null; readonly IsLastPage?: boolean | null; readonly PagesCount?: number | null; readonly NearPageIndexes?: number[] | null; constructor(data?: IIPagingOptions) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(_data?: any) { if (_data) { this.PageIndex = _data["pageIndex"] !== undefined ? _data["pageIndex"] : <any>null; this.PageSize = _data["pageSize"] !== undefined ? _data["pageSize"] : <any>null; this.TotalItemsCount = _data["totalItemsCount"] !== undefined ? _data["totalItemsCount"] : <any>null; (<any>this).IsFirstPage = _data["isFirstPage"] !== undefined ? _data["isFirstPage"] : <any>null; (<any>this).IsLastPage = _data["isLastPage"] !== undefined ? _data["isLastPage"] : <any>null; (<any>this).PagesCount = _data["pagesCount"] !== undefined ? _data["pagesCount"] : <any>null; if (Array.isArray(_data["nearPageIndexes"])) { (<any>this).NearPageIndexes = [] as any; for (let item of _data["nearPageIndexes"]) (<any>this).NearPageIndexes!.push(item); } else { (<any>this).NearPageIndexes = <any>null; } } } static fromJS(data: any): IPagingOptions { data = typeof data === 'object' ? data : {}; let result = new IPagingOptions(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["pageIndex"] = this.PageIndex !== undefined ? this.PageIndex : <any>null; data["pageSize"] = this.PageSize !== undefined ? this.PageSize : <any>null; data["totalItemsCount"] = this.TotalItemsCount !== undefined ? this.TotalItemsCount : <any>null; data["isFirstPage"] = this.IsFirstPage !== undefined ? this.IsFirstPage : <any>null; data["isLastPage"] = this.IsLastPage !== undefined ? this.IsLastPage : <any>null; data["pagesCount"] = this.PagesCount !== undefined ? this.PagesCount : <any>null; if (Array.isArray(this.NearPageIndexes)) { data["nearPageIndexes"] = []; for (let item of this.NearPageIndexes) data["nearPageIndexes"].push(item); } return data; } } export interface IIPagingOptions { PageIndex?: number | null; PageSize?: number | null; TotalItemsCount?: number | null; IsFirstPage?: boolean | null; IsLastPage?: boolean | null; PagesCount?: number | null; NearPageIndexes?: number[] | null; } export class IRowEditOptions implements IIRowEditOptions { PrimaryKeyPropertyName?: string | null; EditRowId?: any | null; constructor(data?: IIRowEditOptions) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(_data?: any) { if (_data) { this.PrimaryKeyPropertyName = _data["primaryKeyPropertyName"] !== undefined ? _data["primaryKeyPropertyName"] : <any>null; this.EditRowId = _data["editRowId"] !== undefined ? _data["editRowId"] : <any>null; } } static fromJS(data: any): IRowEditOptions { data = typeof data === 'object' ? data : {}; let result = new IRowEditOptions(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["primaryKeyPropertyName"] = this.PrimaryKeyPropertyName !== undefined ? this.PrimaryKeyPropertyName : <any>null; data["editRowId"] = this.EditRowId !== undefined ? this.EditRowId : <any>null; return data; } } export interface IIRowEditOptions { PrimaryKeyPropertyName?: string | null; EditRowId?: any | null; } export class ISortingOptions implements IISortingOptions { SortDescending?: boolean | null; SortExpression?: string | null; constructor(data?: IISortingOptions) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(_data?: any) { if (_data) { this.SortDescending = _data["sortDescending"] !== undefined ? _data["sortDescending"] : <any>null; this.SortExpression = _data["sortExpression"] !== undefined ? _data["sortExpression"] : <any>null; } } static fromJS(data: any): ISortingOptions { data = typeof data === 'object' ? data : {}; let result = new ISortingOptions(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["sortDescending"] = this.SortDescending !== undefined ? this.SortDescending : <any>null; data["sortExpression"] = this.SortExpression !== undefined ? this.SortExpression : <any>null; return data; } } export interface IISortingOptions { SortDescending?: boolean | null; SortExpression?: string | null; } export class Order implements IOrder { id?: number | null; Number?: string | null; date?: Date | null; companyId?: number | null; orderItems?: OrderItem[] | null; constructor(data?: IOrder) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(_data?: any) { if (_data) { this.id = _data["id"] !== undefined ? _data["id"] : <any>null; this.Number = _data["Number"] !== undefined ? _data["Number"] : <any>null; this.date = _data["date"] ? new Date(_data["date"].toString()) : <any>null; this.companyId = _data["companyId"] !== undefined ? _data["companyId"] : <any>null; if (Array.isArray(_data["orderItems"])) { this.orderItems = [] as any; for (let item of _data["orderItems"]) this.orderItems!.push(OrderItem.fromJS(item)); } else { this.orderItems = <any>null; } } } static fromJS(data: any): Order { data = typeof data === 'object' ? data : {}; let result = new Order(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["id"] = this.id !== undefined ? this.id : <any>null; data["Number"] = this.Number !== undefined ? this.Number : <any>null; data["date"] = this.date ? this.date.toISOString() : <any>null; data["companyId"] = this.companyId !== undefined ? this.companyId : <any>null; if (Array.isArray(this.orderItems)) { data["orderItems"] = []; for (let item of this.orderItems) data["orderItems"].push(item.toJSON()); } return data; } } export interface IOrder { id?: number | null; Number?: string | null; date?: Date | null; companyId?: number | null; orderItems?: OrderItem[] | null; } export class OrderItem implements IOrderItem { id?: number | null; text?: string | null; amount?: number | null; discount?: number | null; isOnStock?: boolean | null; constructor(data?: IOrderItem) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(_data?: any) { if (_data) { this.id = _data["id"] !== undefined ? _data["id"] : <any>null; this.text = _data["text"] !== undefined ? _data["text"] : <any>null; this.amount = _data["amount"] !== undefined ? _data["amount"] : <any>null; this.discount = _data["discount"] !== undefined ? _data["discount"] : <any>null; this.isOnStock = _data["isOnStock"] !== undefined ? _data["isOnStock"] : <any>null; } } static fromJS(data: any): OrderItem { data = typeof data === 'object' ? data : {}; let result = new OrderItem(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["id"] = this.id !== undefined ? this.id : <any>null; data["text"] = this.text !== undefined ? this.text : <any>null; data["amount"] = this.amount !== undefined ? this.amount : <any>null; data["discount"] = this.discount !== undefined ? this.discount : <any>null; data["isOnStock"] = this.isOnStock !== undefined ? this.isOnStock : <any>null; return data; } } export interface IOrderItem { id?: number | null; text?: string | null; amount?: number | null; discount?: number | null; isOnStock?: boolean | null; } export class ApiException extends Error { message: string; status: number; response: string; headers: { [key: string]: any; }; result: any; constructor(message: string, status: number, response: string, headers: { [key: string]: any; }, result: any) { super(); this.message = message; this.status = status; this.response = response; this.headers = headers; this.result = result; } protected isApiException = true; static isApiException(obj: any): obj is ApiException { return obj.isApiException === true; } } function throwException(message: string, status: number, response: string, headers: { [key: string]: any; }, result?: any): any { if (result !== null && result !== undefined) throw result; else throw new ApiException(message, status, response, headers, null); } }
the_stack